// 主题三态管理:跟随系统 / 浅色 / 深色,存 localStorage,通过 data-theme 覆盖 CSS token // Theme tri-state management: system / light / dark, persisted in localStorage, // overriding CSS tokens via the data-theme attribute (function () { const KEY = 'hearth-theme'; const ORDER = ['system', 'light', 'dark']; const LABELS = { system: '跟随系统', light: '浅色', dark: '深色' }; window.theme = { // 当前主题(默认跟随系统) get() { return localStorage.getItem(KEY) || 'system'; }, // 应用主题:写入 data-theme 属性(system 时移除) apply(t) { localStorage.setItem(KEY, t); const root = document.documentElement; if (t === 'light') root.setAttribute('data-theme', 'light'); else if (t === 'dark') root.setAttribute('data-theme', 'dark'); else root.removeAttribute('data-theme'); }, // 三态循环,返回新主题 cycle() { const cur = this.get(); const next = ORDER[(ORDER.indexOf(cur) + 1) % ORDER.length]; this.apply(next); return next; }, // 主题显示名 label(t) { return LABELS[t] || t; }, }; // 启动即应用已存主题 window.theme.apply(window.theme.get()); })();