/** * 主题管理工具类 * 负责主题切换、主题状态监听和主题信息获取 */ /** 主题模式枚举 */ export enum ThemeMode { /** 浅色模式 */ LIGHT = 'light', /** 深色模式 */ DARK = 'dark' } /** 主题变化回调函数类型 */ type ThemeChangeCallback = (theme: ThemeMode) => void class Theme { /** 主题变化监听器列表 */ private listeners: ThemeChangeCallback[] = [] /** 当前主题模式 */ private currentTheme: ThemeMode = ThemeMode.LIGHT constructor() { this.init() } /** * 初始化主题管理器 * 获取系统当前主题并监听主题变化 */ private init(): void { // 获取系统信息,判断当前主题 const systemInfo = wx.getSystemInfoSync() this.currentTheme = systemInfo.theme === 'dark' ? ThemeMode.DARK : ThemeMode.LIGHT // 监听主题变化事件 wx.onThemeChange((result) => { const newTheme = result.theme === 'dark' ? ThemeMode.DARK : ThemeMode.LIGHT this.currentTheme = newTheme this.notifyListeners(newTheme) }) } /** * 获取当前主题模式 * @returns 当前主题模式 */ getTheme(): ThemeMode { return this.currentTheme } /** * 判断是否为深色模式 * @returns 是否为深色模式 */ isDark(): boolean { return this.currentTheme === ThemeMode.DARK } /** * 判断是否为浅色模式 * @returns 是否为浅色模式 */ isLight(): boolean { return this.currentTheme === ThemeMode.LIGHT } /** * 监听主题变化 * @param callback 主题变化时的回调函数 * @returns 取消监听的函数 */ onChange(callback: ThemeChangeCallback): () => void { this.listeners.push(callback) // 返回取消监听的函数 return () => { const index = this.listeners.indexOf(callback) if (index > -1) { this.listeners.splice(index, 1) } } } /** * 通知所有监听器主题已变化 * @param theme 新的主题模式 */ private notifyListeners(theme: ThemeMode): void { this.listeners.forEach(callback => { try { callback(theme) } catch (error) { console.error('主题变化监听器执行出错:', error) } }) } } // 导出单例 export default new Theme()