// The reader's theme choice: follow the system, or pin light or dark. // // The choice lives in localStorage because `theme-init.ts` has to read it // synchronously before the first paint; the popup is an extension page, so // that storage is the extension's own origin. The resolved theme is written // to `data-theme`, which is the only thing the stylesheet keys off. export type ThemeChoice = 'system' | 'light' | 'dark' export type ResolvedTheme = 'light' | 'dark' export const THEME_KEY = 'substandard.theme' export const THEME_LABELS: Record = { system: 'System', light: 'Light', dark: 'Dark', } export function isThemeChoice(value: unknown): value is ThemeChoice { return value === 'system' || value === 'light' || value === 'dark' } export function readThemeChoice(): ThemeChoice { try { const stored = localStorage.getItem(THEME_KEY) return isThemeChoice(stored) ? stored : 'system' } catch { return 'system' } } export function prefersDark(): boolean { return ( typeof matchMedia === 'function' && matchMedia('(prefers-color-scheme: dark)').matches ) } export function resolveTheme(choice: ThemeChoice): ResolvedTheme { if (choice === 'system') return prefersDark() ? 'dark' : 'light' return choice } export function applyTheme(choice: ThemeChoice, root: HTMLElement = document.documentElement): void { const resolved = resolveTheme(choice) root.dataset.theme = resolved root.dataset.choice = choice root.style.colorScheme = resolved } export function setTheme(choice: ThemeChoice): void { try { localStorage.setItem(THEME_KEY, choice) } catch { // The popup is still usable when storage is unavailable; the choice just // does not outlive the open. } applyTheme(choice) } /** Re-resolve on system changes while the choice is `system`. */ export function watchSystemTheme(onChange: (resolved: ResolvedTheme) => void): () => void { if (typeof matchMedia !== 'function') return () => {} const media = matchMedia('(prefers-color-scheme: dark)') const handler = () => onChange(media.matches ? 'dark' : 'light') media.addEventListener('change', handler) return () => media.removeEventListener('change', handler) }