// Light/dark toggle in the nav. // The inline script in base.html applies a saved choice before the page draws; // this file wires up the button. With nothing saved the site follows the // system setting (prefers-color-scheme), see the dark-mode tokens in base.css. (function () { const root = document.documentElement; const systemDark = window.matchMedia("(prefers-color-scheme: dark)"); function currentTheme() { const chosen = root.dataset.theme; if (chosen === "light" || chosen === "dark") return chosen; return systemDark.matches ? "dark" : "light"; } function updateButtons() { const label = currentTheme() === "dark" ? "Switch to light mode" : "Switch to dark mode"; document.querySelectorAll(".theme-toggle").forEach(btn => { btn.setAttribute("aria-label", label); btn.setAttribute("title", label); }); } function setTheme(theme) { root.dataset.theme = theme; try { localStorage.setItem("theme", theme); } catch (e) { } updateButtons(); } document.querySelectorAll(".theme-toggle").forEach(btn => { btn.addEventListener("click", () => { setTheme(currentTheme() === "dark" ? "light" : "dark"); }); }); // Keep the label right if the system setting changes while nothing is saved systemDark.addEventListener("change", updateButtons); // Another tab changed the theme window.addEventListener("storage", event => { if (event.key !== "theme") return; if (event.newValue === "light" || event.newValue === "dark") root.dataset.theme = event.newValue; else delete root.dataset.theme; updateButtons(); }); updateButtons(); })();