Repository navigation
Expand file tree
/
Copy paththemeManager.js
More file actions
121 lines (107 loc) · 3.19 KB
/
Copy paththemeManager.js
File metadata and controls
121 lines (107 loc) · 3.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
* 主题管理器
* 负责处理主题的切换、系统主题的监听等功能
*/
class ThemeManager {
static #instance = null;
#currentTheme = null;
#systemThemeMediaQuery = null;
constructor() {
if (ThemeManager.#instance) {
return ThemeManager.#instance;
}
ThemeManager.#instance = this;
this.init();
}
/**
* 初始化主题管理器
*/
async init() {
// 初始化系统主题监听
this.#systemThemeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
this.#systemThemeMediaQuery.addEventListener('change', () => this.handleSystemThemeChange());
// 监听设置变化
chrome.runtime.onMessage.addListener(this.handleMessage.bind(this));
// 获取当前主题设置
await this.loadAndApplyTheme();
}
/**
* 处理消息
* @param {Object} message - 消息
* @param {Object} sender - 发送者
* @param {Function} sendResponse - 发送响应
*/
async handleMessage(message, sender, sendResponse) {
if (message.type === MessageType.THEME_CHANGED) {
await this.loadAndApplyTheme();
}
}
/**
* 加载并应用主题
*/
async loadAndApplyTheme() {
try {
const settings = await SettingsManager.get('display.theme');
this.#currentTheme = settings.mode;
logger.info('加载主题设置成功, 应用主题:', settings.mode);
this.applyTheme(settings.mode);
} catch (error) {
logger.error('加载主题设置失败:', error);
// 默认使用系统主题
this.applyTheme('system');
}
}
/**
* 应用指定的主题
* @param {string} theme - 主题模式:'light' | 'dark' | 'system'
*/
applyTheme(theme) {
const root = document.documentElement;
// 移除所有主题相关的属性
root.removeAttribute('data-theme');
// 设置新的主题
if (theme === 'system') {
root.setAttribute('data-theme', 'system');
} else {
root.setAttribute('data-theme', theme);
}
this.#currentTheme = theme;
}
/**
* 处理系统主题变化
*/
handleSystemThemeChange() {
if (this.#currentTheme === 'system') {
this.applyTheme('system');
}
}
/**
* 获取当前主题
* @returns {string} 当前主题模式
*/
getCurrentTheme() {
return this.#currentTheme;
}
/**
* 更新主题设置
* @param {Object} themeSettings - 新的主题设置
*/
async updateTheme(themeSettings) {
try {
await updateSettingsWithSync({
display: {
theme: themeSettings
}
});
sendMessageSafely({
type: MessageType.THEME_CHANGED
});
await this.loadAndApplyTheme();
} catch (error) {
logger.error('更新主题设置失败:', error);
throw error;
}
}
}
// 导出单例实例
const themeManager = new ThemeManager();