Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177/** * Which theme the app wears, and how it decides. * * Three *modes*, one *theme*: * * - **mode** is what the listener asked for: `system`, `light`, or `dark`. It is the * thing persisted to disk and the thing the `:theme` verb writes, and it is the only * one of the two with three values. `system` is not a fourth appearance — it is a * standing instruction to follow the operating system, which is what makes it the * default: an app that overrides a machine-wide setting nobody asked it to override is * the bug, not the feature. * - **theme** is what is actually painted: `light` or `dark`, with no third value. It is * `mode` with the `system` case resolved against `prefers-color-scheme`, and it is the * value `accent.ts` needs — because the accent is *ink*, and which lightness reads as * ink is a question only the ground can answer. * * The distinction earns its keep the moment a `system` listener switches their OS at * sunset: the persisted mode has to stay `system` through it (the instruction was not * "dark forever", it was "follow the machine"), while the painted theme flips. A single * stored value could not do both, which is why there are two. * * The DOM contract is one attribute — `data-theme` on `<html>`, `light` or `dark`, never * `system` — because CSS keys surfaces off it and should never have to reason about an * operating system. `startThemeSync` owns writing it: it resolves the mode on boot, * re-applies whenever the mode or the machine changes, and (only while a mode is * `system`) listens for the machine changing underneath it. */import { createEffect, createMemo, createSignal, onCleanup } from "solid-js";import * as v from "valibot";
import { createPersistentSignal } from "../persist";
/** What the listener asked for. The three states `:theme` swaps between. */export type ThemeMode = "system" | "light" | "dark";
/** What is painted: the mode with `system` resolved. The only thing `accent.ts` reads. */export type Theme = "light" | "dark";
const STORAGE_KEY = "hackermusic.theme.v1";
/** * The cycle order `:theme` walks with no argument. `system` leads because it is both the * default and the one mode that can answer "what colour should this be" better than the * app can, and a listener who cycles once from where they started expects to land on the * next real appearance, not back on the same one. */const MODE_ORDER: readonly ThemeMode[] = ["system", "light", "dark"];
/** A stored mode, and nothing that is not one: a hand-edited value is the default. */const ModeSchema = v.pipe(v.string(), v.picklist(["system", "light", "dark"]));
const modeStore = createPersistentSignal<ThemeMode>(STORAGE_KEY, "system", { schema: ModeSchema,});
/** * Whether the machine is currently asking for a dark theme. * * A plain mirror plus a signal, for the same reason `persist.ts` keeps one: the OS * listener that updates it is an event handler outside any reactive scope, so the write * is imperative and the read is sometimes imperative too (`resolveTheme` is called from * `applyTheme`, not from a compute). The signal is purely the change-notification channel * the memo subscribes to; the `let` is the synchronous source of truth the imperative path * reads. Absent `matchMedia` — the test runner, a headless render — the app keeps its own * identity and reports dark, which is the theme every screen of it was drawn in. */let osDark = prefersDarkFromOs();const [osDarkSignal, setOsDarkSignal] = createSignal<boolean>(osDark, { name: "theme-os-dark" });
function prefersDarkFromOs(): boolean { return globalThis.matchMedia?.("(prefers-color-scheme: dark)")?.matches ?? true;}
/** * The theme to paint right now, resolved without a tracking scope: the mode, and the * machine only while the mode says to ask it. `light`/`dark` are returned verbatim, so an * explicit choice is not disturbed by a sunset it never asked about. */export function resolveTheme(): Theme { const mode = modeStore.peek(); if (mode !== "system") return mode; return osDark ? "dark" : "light";}
/** * The reactive face of `resolveTheme`, for anything that repaints on a theme change (the * accent, chiefly). Named so a diagnostic report says `theme-effective` rather than an * anonymous memo when it explains why a scope re-ran. */export const effectiveTheme = createMemo<Theme>( () => { const mode = themeMode(); if (mode !== "system") return mode; return osDarkSignal() ? "dark" : "light"; }, { name: "theme-effective" },);
/** The persisted mode, reactively. `system` unless somebody said otherwise. */export function themeMode(): ThemeMode { return modeStore.get();}
/** The persisted mode, synchronously — for command handlers and guards. */export function peekThemeMode(): ThemeMode { return modeStore.peek();}
/** Ask for a mode. Returns what it landed on, which is what a command line reports. */export function setThemeMode(mode: ThemeMode): ThemeMode { return modeStore.set(mode);}
/** * Step to the next mode and return it. The `:theme` verb with no argument; cycling is also * how a listener gets *back* to `system` after having pinned a theme, so all three states * are reachable from any start point in at most two presses. */export function cycleThemeMode(): ThemeMode { const at = MODE_ORDER.indexOf(modeStore.peek()); const next = MODE_ORDER[(at + 1 + MODE_ORDER.length) % MODE_ORDER.length]!; return modeStore.set(next);}
/** The modes in cycle order, for a `:help` line and for tests that pin the order. */export function themeModes(): readonly ThemeMode[] { return MODE_ORDER;}
/** * Write the resolved theme onto the document, imperatively. * * One attribute and nothing else: `data-theme` is the whole contract, and CSS owns every * colour that hangs off it (including `color-scheme`, so native controls and scrollbars * flip with the tokens rather than being told twice). Written on every call, not diffed — * it is a single attribute set, and the cost of reading it back to compare is not worth a * branch that could itself drift from the truth on the element. */export function applyTheme(): Theme { const theme = resolveTheme(); document.documentElement.dataset.theme = theme; return theme;}
/** * Call once from the app root, beside the other `start*Sync`s. * * Two jobs kept apart on purpose. The effect repaints the attribute whenever the mode * changes or — while the mode is `system` — the machine's own preference does; the media * listener is registered once and feeds that effect the only input it cannot read for * itself. The listener is guarded because `matchMedia` is not everywhere (and not in the * test runner), and it is torn down with the root that owns it rather than left to fire * into a page that has moved on. */export function startThemeSync(): void { applyTheme();
// Re-apply on every change to the resolved theme. The compute reads nothing but the // memo, so this scope re-runs on a theme flip and on nothing else. createEffect( () => effectiveTheme(), () => { applyTheme(); }, { name: "theme-apply" }, );
const mq = globalThis.matchMedia?.("(prefers-color-scheme: dark)"); if (!mq) return; const onChange = (e: MediaQueryListEvent) => { osDark = e.matches; setOsDarkSignal(() => e.matches); }; mq.addEventListener?.("change", onChange); onCleanup(() => mq.removeEventListener?.("change", onChange));}