/** * Light / dark theme — shared names and the pre-paint script. Pure: safe on the * server and in the browser. * * The theme never reaches the server HTML (pages are ISR/SSG, one HTML for * everyone): sets `data-theme` on before the first paint, * from the visitor's choice (localStorage — an interface preference, no cookie, * no tracking, no consent needed) or Site Settings → Theme → Default theme. */ export type Theme = 'dark' | 'light' /** Site Settings → Default theme. 'system' follows the device (prefers-color-scheme). */ export type ThemeSetting = 'system' | Theme /** localStorage key of the visitor's choice. */ export const THEME_STORAGE_KEY = 'ipal-theme' /** Attribute on : `[data-theme=dark]`, Tailwind `@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *))`. */ export const THEME_ATTRIBUTE = 'data-theme' /** Set on for a moment while switching — for a colour transition only then (`[data-theme-switching] * { transition: … }`). */ export const THEME_SWITCHING_ATTRIBUTE = 'data-theme-switching' export const isTheme = (value: unknown): value is Theme => value === 'light' || value === 'dark' export const isThemeSetting = (value: unknown): value is ThemeSetting => value === 'system' || isTheme(value) /** Theme options from Site Settings — what getSiteShell(locale).theme holds. */ export type ThemeConfig = { /** Visitors may switch (and their choice is remembered). */ allowToggle: boolean /** null: no Site Settings — no attribute, the base (light) CSS applies. */ defaultTheme: null | ThemeSetting /** Accessible name of the switch, e.g. "Dark mode" (Site Settings → Theme). */ toggleLabel: null | string } /** Reads Theme options from a Site Settings document. */ export function themeConfigFrom(settings: unknown): ThemeConfig { const s = (settings && typeof settings === 'object' ? settings : {}) as Record const label = typeof s.themeToggleLabel === 'string' && s.themeToggleLabel.trim() ? s.themeToggleLabel.trim() : null return { allowToggle: s.allowThemeToggle === true, defaultTheme: isThemeSetting(s.defaultTheme) ? s.defaultTheme : null, toggleLabel: label, } } /** * The inline script for : stored choice (only when the toggle is * allowed) → default theme → for 'system' the device setting. Sets * `data-theme` and `color-scheme` (native controls, scrollbars) on . */ export function themeScript({ allowToggle, defaultTheme }: Pick): string { const stored = allowToggle ? `try{var s=localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});if(s==='light'||s==='dark')t=s}catch(e){}` : '' return ( `(function(){var d=document.documentElement,t=${JSON.stringify(defaultTheme ?? null)};${stored}` + `if(t==='system')t=window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';` + `if(t==='light'||t==='dark'){d.setAttribute(${JSON.stringify(THEME_ATTRIBUTE)},t);d.style.colorScheme=t}})()` ) }