From 00b232c2826756bbd395c7f0fe0be8e3179f9801 Mon Sep 17 00:00:00 2001 From: Francisco Arceo Date: Wed, 16 Apr 2025 14:58:25 -0600 Subject: [PATCH] chore: Fix to persist the theme preference across page navigation. (#1974) # What does this PR do? This PR persists the theme preference across page navigation. Currently, if the default theme is detected, it is used. But if a user flips **_the default theme_** and goes to a new page, the theme will switch back to the default. This resolves that issue. ## Test Plan [Describe the tests you ran to verify your changes with result summaries. *Provide clear instructions so the plan can be easily re-executed.*] [//]: # (## Documentation) Signed-off-by: Francisco Javier Arceo --- docs/_static/js/detect_theme.js | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/docs/_static/js/detect_theme.js b/docs/_static/js/detect_theme.js index 484b2bb8b..712565ef7 100644 --- a/docs/_static/js/detect_theme.js +++ b/docs/_static/js/detect_theme.js @@ -1,9 +1,32 @@ document.addEventListener("DOMContentLoaded", function () { const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; const htmlElement = document.documentElement; - if (prefersDark) { - htmlElement.setAttribute("data-theme", "dark"); + + // Check if theme is saved in localStorage + const savedTheme = localStorage.getItem("sphinx-rtd-theme"); + + if (savedTheme) { + // Use the saved theme preference + htmlElement.setAttribute("data-theme", savedTheme); + document.body.classList.toggle("dark", savedTheme === "dark"); } else { - htmlElement.setAttribute("data-theme", "light"); + // Fall back to system preference + const theme = prefersDark ? "dark" : "light"; + htmlElement.setAttribute("data-theme", theme); + document.body.classList.toggle("dark", theme === "dark"); + // Save initial preference + localStorage.setItem("sphinx-rtd-theme", theme); } + + // Listen for theme changes from the existing toggle + const observer = new MutationObserver(function(mutations) { + mutations.forEach(function(mutation) { + if (mutation.attributeName === "data-theme") { + const currentTheme = htmlElement.getAttribute("data-theme"); + localStorage.setItem("sphinx-rtd-theme", currentTheme); + } + }); + }); + + observer.observe(htmlElement, { attributes: true }); });