/** * Theme preference helpers. The browser keeps the choice in localStorage only; * nothing is stored server-side. THEME_BOOT_JS runs in before the CSS so * the first paint already uses the resolved theme (no flash). */ export const THEME_KEY = 'kody-factory-theme' export type ThemePreference = 'light' | 'dark' | 'system' export type ResolvedTheme = 'light' | 'dark' export function parseTheme(value: unknown): ThemePreference { return value === 'light' || value === 'dark' ? value : 'system' } export function resolveThemePreference(pref: unknown, systemPrefersDark: boolean): ResolvedTheme { const p = parseTheme(pref) if (p === 'system') return systemPrefersDark ? 'dark' : 'light' return p } /** Same rules as parseTheme/resolveThemePreference, as a tiny ES5 head script. */ export const THEME_BOOT_JS = `(function(){try{var d=document.documentElement,p=localStorage.getItem(${JSON.stringify( THEME_KEY, )});if(p!=='light'&&p!=='dark')p='system';var t=p==='system'?(window.matchMedia&&matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'):p;d.setAttribute('data-theme',t);d.setAttribute('data-theme-pref',p);d.style.colorScheme=t}catch(e){}})()`