mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 03:32:06 +00:00
404 and 500 drafts
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
<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>
|
||||
Reference in New Issue
Block a user