import type { ThemeProposal } from './types.js'; /** * Apply a `ThemeProposal` as CSS custom-property overrides on a * target element. Defaults to `document.documentElement` so the * entire page re-tints in one call. * * Returns a function that *removes* the overrides — useful for * temporary preview surfaces (e.g. the showcase studio). */ export function applyTheme( theme: ThemeProposal, target?: HTMLElement, ): () => void { if (typeof document === 'undefined') return () => {}; const el = target ?? document.documentElement; const mapping: Array<[keyof ThemeProposal, string]> = [ ['accent', '--bl-accent'], ['surface', '--bl-surface'], ['surfaceCard', '--bl-surface-card'], ['surfaceMuted', '--bl-surface-muted'], ['textPrimary', '--bl-text-primary'], ['textSecondary', '--bl-text-secondary'], ['success', '--bl-success'], ['warning', '--bl-warning'], ['danger', '--bl-danger'], ['info', '--bl-info'], ['border', '--bl-border'], ]; const previous = mapping.map( ([_, css]) => [css, el.style.getPropertyValue(css)] as const, ); for (const [k, css] of mapping) { const v = theme[k]; if (typeof v === 'string') { el.style.setProperty(css, v); } } return () => { for (const [css, prev] of previous) { if (prev) el.style.setProperty(css, prev); else el.style.removeProperty(css); } }; }