Files
chess-endgame-trainer/lib/chesstrainer_web/components/layouts/theme_script.html.heex
T
2026-11-06 15:42:52 +01:00

74 lines
2.5 KiB
Plaintext

<script>
(() => {
const systemMode = () => matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
const storedMode = () => {
try { return localStorage.getItem("phx:theme"); } catch (_) { return null; }
};
const persistMode = (mode) => {
try {
if (mode === "system") localStorage.removeItem("phx:theme");
else localStorage.setItem("phx:theme", mode);
} catch (_) {
// Storage can be blocked (private modes, embedded browsers); the
// mode still applies for this page load.
}
};
const selectedMode = () => {
const source = document.documentElement.getAttribute("data-theme-source");
return source === "system" ? "system" : document.documentElement.getAttribute("data-theme");
};
const syncChecked = () => {
document.querySelectorAll("[data-phx-theme]").forEach((button) => {
button.setAttribute("aria-checked", String(button.dataset.phxTheme === selectedMode()));
});
};
const setMode = (mode) => {
if (mode !== "system" && mode !== "light" && mode !== "dark") return;
if (mode === "system") {
persistMode("system");
document.documentElement.setAttribute("data-theme", systemMode());
document.documentElement.setAttribute("data-theme-source", "system");
} else {
persistMode(mode);
document.documentElement.setAttribute("data-theme", mode);
document.documentElement.setAttribute("data-theme-source", "user");
}
syncChecked();
};
if (!document.documentElement.hasAttribute("data-theme")) {
setMode(storedMode() || "system");
}
document.addEventListener("DOMContentLoaded", syncChecked);
// Plain DOM so the switch also works on controller-rendered pages
// (the landing page ships no LiveView runtime).
document.addEventListener("click", (event) => {
const button = event.target instanceof Element && event.target.closest("[data-phx-theme]");
if (button) setMode(button.dataset.phxTheme);
});
window.addEventListener("storage", (event) => {
if (event.key === "phx:theme") setMode(event.newValue || "system");
});
window.addEventListener("phx:set-theme", (event) => {
setMode(event.target?.dataset?.phxTheme);
});
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
if (document.documentElement.getAttribute("data-theme-source") === "system") {
document.documentElement.setAttribute("data-theme", systemMode());
}
});
})();
</script>