export type ThemePreference = 'system' | 'light' | 'dark' export type ResolvedTheme = 'light' | 'dark' export const THEME_PREFERENCE_STORAGE_KEY = 'app-theme-preference' /** * 读取当前系统级色彩偏好 */ export function getSystemTheme(): ResolvedTheme { if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') { return 'light' } return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' } /** * 读取用户保存的主题喜好设置,默认未设置时为 'system'(跟随系统) */ export function getStoredThemePreference(storage?: Storage): ThemePreference { const targetStorage = storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined) if (!targetStorage) { return 'system' } const value = targetStorage.getItem(THEME_PREFERENCE_STORAGE_KEY) if (value === 'light' || value === 'dark' || value === 'system') { return value } return 'system' } /** * 保存用户的主题喜好;如为 'system' 则移除自定义项,恢复纯净跟随系统 */ export function setStoredThemePreference(pref: ThemePreference, storage?: Storage): void { const targetStorage = storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined) if (!targetStorage) { return } if (pref === 'system') { targetStorage.removeItem(THEME_PREFERENCE_STORAGE_KEY) } else { targetStorage.setItem(THEME_PREFERENCE_STORAGE_KEY, pref) } } /** * 根据喜好配置计算当前最终生效的明暗主题 */ export function resolveEffectiveTheme( preference: ThemePreference, systemTheme: ResolvedTheme = getSystemTheme(), ): ResolvedTheme { if (preference === 'system') { return systemTheme } return preference } /** * 将明暗主题属性同步到 DOM 根节点,以激活 CSS 选择器与原生色彩方案 */ export function applyThemeToDom(theme: ResolvedTheme, doc?: Document): void { const targetDoc = doc ?? (typeof document !== 'undefined' ? document : undefined) if (!targetDoc) { return } const root = targetDoc.documentElement root.setAttribute('data-theme', theme) root.classList.toggle('dark', theme === 'dark') root.style.colorScheme = theme }