(function () { var btn = document.getElementById("theme-toggle"); var choices = Array.prototype.slice.call(document.querySelectorAll("[data-theme-choice]")); var media = window.matchMedia("(prefers-color-scheme: dark)"); if (!btn && choices.length === 0) return; function storedTheme() { try { var value = localStorage.getItem("theme"); return value === "dark" || value === "light" ? value : "system"; } catch (_error) { return "system"; } } var selectedTheme = storedTheme(); function isDark() { var t = document.documentElement.getAttribute("data-theme"); if (t) return t === "dark"; return media.matches; } function icon(dark) { if (dark) { return ''; } return ''; } function setTheme(theme) { if (theme !== "system" && theme !== "light" && theme !== "dark") return; selectedTheme = theme; if (theme === "system") { document.documentElement.removeAttribute("data-theme"); try { localStorage.removeItem("theme"); } catch (_error) { // The system preference still works when storage is unavailable. } } else { document.documentElement.setAttribute("data-theme", theme); try { localStorage.setItem("theme", theme); } catch (_error) { // The current document can still use the requested theme. } } update(); } function update() { var dark = isDark(); if (btn) { btn.innerHTML = icon(dark); btn.setAttribute("aria-label", dark ? "Use light theme" : "Use dark theme"); btn.setAttribute("title", dark ? "Use light theme" : "Use dark theme"); } choices.forEach(function (choice) { choice.setAttribute("aria-pressed", choice.getAttribute("data-theme-choice") === selectedTheme ? "true" : "false"); }); } if (btn) { btn.addEventListener("click", function () { setTheme(isDark() ? "light" : "dark"); }); } choices.forEach(function (choice) { choice.addEventListener("click", function () { setTheme(choice.getAttribute("data-theme-choice")); }); }); if (typeof media.addEventListener === "function") { media.addEventListener("change", function () { if (selectedTheme === "system") update(); }); } update(); })();