import { createSignal } from "solid-js"; /** Light or dark as the system has it, or one chosen here; kept in this browser only. */ export type Theme = "system" | "light" | "dark"; const KEY = "parfait:theme"; const system = matchMedia("(prefers-color-scheme: dark)"); const read = (): Theme => { try { const kept = localStorage.getItem(KEY); if (kept === "light" || kept === "dark") return kept; } catch {} return "system"; }; const [chosen, setChosen] = createSignal(read()); export const theme = chosen; /** * Says on the page which it is, which the palette follows (as index.html does at the start). A * change crossfades the whole page at once, where the browser can, rather than flipping, with each * thing that eases its colours (a row, a button) catching up at its own pace: those are held still * while it does. */ const apply = () => { const root = document.documentElement; const theme = chosen() === "dark" || (chosen() === "system" && system.matches) ? "dark" : "light"; if (root.dataset.theme === theme) return; const change = () => { root.dataset.themeChanging = ""; root.dataset.theme = theme; }; const done = () => delete root.dataset.themeChanging; if (!document.startViewTransition || matchMedia("(prefers-reduced-motion: reduce)").matches) { change(); // Once drawn in its new colours, things ease again. return requestAnimationFrame(() => requestAnimationFrame(done)); } void document.startViewTransition(change).finished.finally(done); }; export const setTheme = (next: Theme) => { try { if (next === "system") localStorage.removeItem(KEY); else localStorage.setItem(KEY, next); } catch {} setChosen(next); apply(); }; // The system changing its mind, and another window of parfait choosing. system.addEventListener("change", apply); addEventListener("storage", (event) => { if (event.key !== KEY && event.key !== null) return; setChosen(read()); apply(); });