import type { ThemeAPI } from './types'; /** * Theme management system for bare-v2 * Handles dark/light mode toggle and persistence */ class Theme implements ThemeAPI { private readonly storageKey = 'bare-theme'; private readonly darkClass = 'dark'; init(): void { // Initialize theme from localStorage or system preference const savedTheme = localStorage.getItem(this.storageKey); if (savedTheme) { this.set(savedTheme as 'light' | 'dark'); } else { // Default to system preference const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; this.set(prefersDark ? 'dark' : 'light'); } // Listen for system theme changes window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => { // Only auto-switch if user hasn't manually set a preference if (!localStorage.getItem(this.storageKey)) { this.set(e.matches ? 'dark' : 'light'); } }); } toggle(): void { const current = this.get(); this.set(current === 'dark' ? 'light' : 'dark'); } set(theme: 'light' | 'dark'): void { const html = document.documentElement; if (theme === 'dark') { html.classList.add(this.darkClass); } else { html.classList.remove(this.darkClass); } // Persist choice localStorage.setItem(this.storageKey, theme); // Dispatch custom event for other components to listen window.dispatchEvent(new CustomEvent('bare-theme-change', { detail: { theme } })); } get(): 'light' | 'dark' { return document.documentElement.classList.contains(this.darkClass) ? 'dark' : 'light'; } } export const createTheme = (): ThemeAPI => new Theme();