Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
338 lines (297 loc) · 10.4 KB
/
Copy pathbackground.js
File metadata and controls
338 lines (297 loc) · 10.4 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Hyliter 后台脚本
// 职责:
// 1. 保留左键点击工具栏图标在“开启/暂停”之间切换整个插件(暂停显示 OFF 徽标)。
// 2. 在工具栏图标右键菜单中提供侧边栏、设置与快速备份入口,并随界面语言实时更新文案。
// 3. 代理执行 WebDAV 网络请求。
importScripts('i18n.js', 'webdav.js');
const STORAGE_KEY = 'hyliterEnabled';
const TEMP_ONLY_KEY = 'hyliterTempOnly';
const DATA_KEY = 'hyliterData';
const WEBDAV_KEY = 'hyliterWebdavConfig';
const LANG_KEY = HyliterI18n.LANG_KEY;
const BADGE_OFF_BG = '#9AA0A6';
const BADGE_TEMP_BG = '#F06292'; // 粉红色:仅用于临时标记模式
const MENU_TEMP_ONLY = 'hyliter-temp-only';
const MENU_TOGGLE_SIDEBAR = 'hyliter-toggle-sidebar';
const MENU_OPEN_OPTIONS = 'hyliter-open-options';
const MENU_QUICK_BACKUP = 'hyliter-quick-backup';
function createEmptyData() {
return {
version: 1,
updatedAt: Date.now(),
pages: {},
};
}
async function getEnabled() {
const result = await chrome.storage.local.get({ [STORAGE_KEY]: true });
return result[STORAGE_KEY];
}
async function getTempOnly() {
const result = await chrome.storage.local.get({ [TEMP_ONLY_KEY]: false });
return !!result[TEMP_ONLY_KEY];
}
async function getLanguage() {
const result = await chrome.storage.local.get({ [LANG_KEY]: HyliterI18n.DEFAULT_LANG });
return HyliterI18n.normalizeLang(result[LANG_KEY]);
}
async function getHyliterData() {
const result = await chrome.storage.local.get({ [DATA_KEY]: null });
const data = result[DATA_KEY];
if (!data || typeof data !== 'object' || !data.pages) {
return createEmptyData();
}
return data;
}
async function getWebdavConfig() {
const result = await chrome.storage.local.get({
[WEBDAV_KEY]: {
url: '',
username: '',
password: '',
remotePath: HyliterWebDAV.DEFAULT_REMOTE_PATH,
lastBackupAt: null,
lastRestoreAt: null,
},
});
return result[WEBDAV_KEY];
}
const DEFAULT_ICON_PATHS = {
16: 'ico16.png',
48: 'ico48.png',
128: 'ico128.png',
};
let tempIconImageDataPromise = null;
async function buildTempIconImageData() {
if (!tempIconImageDataPromise) {
tempIconImageDataPromise = (async () => {
const resp = await fetch(chrome.runtime.getURL('ico128.png'));
const blob = await resp.blob();
const bitmap = await createImageBitmap(blob);
const renderSize = (size) => {
const canvas = new OffscreenCanvas(size, size);
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, size, size);
ctx.drawImage(bitmap, 0, 0, size, size);
// 右下角粉色实心圆(无白色外圈)+ 居中白色大写字母 T
const r = Math.round(size * 0.32);
const cx = size - r;
const cy = size - r;
ctx.save();
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.fillStyle = BADGE_TEMP_BG;
ctx.fill();
// 用几何矢量绘制大写 T:加宽顶部横杠,在 16x16 / 32x32 图标尺寸下更锐利易识别
const stroke = Math.max(1.5, Math.round(size * 0.095 * 2) / 2);
const barW = Math.round(r * 1.28);
const stemH = Math.round(r * 1.16);
const topY = Math.round(cy - stemH / 2);
const leftX = Math.round(cx - barW / 2);
const stemX = Math.round(cx - stroke / 2);
ctx.fillStyle = '#ffffff';
// 顶部加长横杠
ctx.fillRect(leftX, topY, barW, stroke);
// 居中竖杠
ctx.fillRect(stemX, topY, stroke, stemH);
ctx.restore();
return ctx.getImageData(0, 0, size, size);
};
return {
16: renderSize(16),
32: renderSize(32),
};
})().catch((err) => {
tempIconImageDataPromise = null;
throw err;
});
}
return tempIconImageDataPromise;
}
async function applyBadge(enabled, tempOnly = false) {
if (!enabled) {
await chrome.action.setIcon({ path: DEFAULT_ICON_PATHS }).catch(() => {});
await chrome.action.setBadgeText({ text: 'OFF' });
await chrome.action.setBadgeBackgroundColor({ color: BADGE_OFF_BG });
} else if (tempOnly) {
try {
const imageData = await buildTempIconImageData();
await chrome.action.setBadgeText({ text: '' });
await chrome.action.setIcon({ imageData });
} catch (e) {
// 兜底:若环境不支持 OffscreenCanvas,使用粉色单字母 t 徽标
await chrome.action.setIcon({ path: DEFAULT_ICON_PATHS }).catch(() => {});
await chrome.action.setBadgeText({ text: 'T' });
await chrome.action.setBadgeBackgroundColor({ color: BADGE_TEMP_BG });
}
} else {
await chrome.action.setIcon({ path: DEFAULT_ICON_PATHS }).catch(() => {});
await chrome.action.setBadgeText({ text: '' });
}
}
async function syncBadge() {
const [enabled, tempOnly] = await Promise.all([getEnabled(), getTempOnly()]);
await applyBadge(enabled, tempOnly);
}
function getBrowserMenuLang() {
const uiLang = (chrome.i18n && typeof chrome.i18n.getUILanguage === 'function')
? chrome.i18n.getUILanguage()
: 'en';
return HyliterI18n.detectBrowserLang(uiLang);
}
async function setupContextMenus() {
const lang = getBrowserMenuLang();
const t = (key) => HyliterI18n.t(lang, key);
const tempOnly = await getTempOnly();
chrome.action.setTitle({ title: t('actionTitle') }).catch(() => {});
chrome.contextMenus.removeAll(() => {
chrome.contextMenus.create({
id: MENU_TEMP_ONLY,
type: 'checkbox',
checked: tempOnly,
title: t('menuTempOnly'),
contexts: ['action'],
});
chrome.contextMenus.create({
id: MENU_TOGGLE_SIDEBAR,
title: t('menuToggleSidebar'),
contexts: ['action', 'page'],
});
chrome.contextMenus.create({
id: MENU_OPEN_OPTIONS,
title: t('menuOpenOptions'),
contexts: ['action'],
});
chrome.contextMenus.create({
id: MENU_QUICK_BACKUP,
title: t('menuQuickBackup'),
contexts: ['action'],
});
});
}
chrome.runtime.onInstalled.addListener(() => {
syncBadge();
setupContextMenus();
});
chrome.runtime.onStartup.addListener(() => {
syncBadge();
setupContextMenus();
});
syncBadge();
// 左键点击工具栏图标:保留原有“开启/暂停”开关行为
chrome.action.onClicked.addListener(async () => {
const [enabled, tempOnly] = await Promise.all([getEnabled(), getTempOnly()]);
const next = !enabled;
await chrome.storage.local.set({ [STORAGE_KEY]: next });
await applyBadge(next, tempOnly);
});
// 右键菜单点击处理
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId === MENU_TEMP_ONLY) {
const curTempOnly = await getTempOnly();
const nextTempOnly = !curTempOnly;
// 开启或退出“仅用于临时标记”时,均保持插件处于启用状态
await chrome.storage.local.set({
[STORAGE_KEY]: true,
[TEMP_ONLY_KEY]: nextTempOnly,
});
await applyBadge(true, nextTempOnly);
chrome.contextMenus.update(MENU_TEMP_ONLY, { checked: nextTempOnly }, () => {
void chrome.runtime.lastError;
});
return;
}
if (info.menuItemId === MENU_OPEN_OPTIONS) {
chrome.runtime.openOptionsPage();
return;
}
if (info.menuItemId === MENU_TOGGLE_SIDEBAR) {
if (await getTempOnly()) return;
const targetTab = tab && tab.id ? tab : (await chrome.tabs.query({ active: true, currentWindow: true }))[0];
if (targetTab && targetTab.id) {
chrome.tabs.sendMessage(targetTab.id, { type: 'HYLITER_TOGGLE_SIDEBAR' }).catch(() => {
chrome.runtime.openOptionsPage();
});
}
return;
}
if (info.menuItemId === MENU_QUICK_BACKUP) {
const config = await getWebdavConfig();
if (!config.url) {
chrome.runtime.openOptionsPage();
return;
}
try {
const lang = await getLanguage();
const data = await getHyliterData();
const res = await HyliterWebDAV.uploadBackup(config, data, lang);
await chrome.storage.local.set({
[WEBDAV_KEY]: { ...config, lastBackupAt: res.exportedAt },
});
await flashBadge('OK', '#30a46c');
} catch (err) {
await flashBadge('ERR', '#e5484d');
}
}
});
async function flashBadge(text, color) {
await chrome.action.setBadgeText({ text });
await chrome.action.setBadgeBackgroundColor({ color });
setTimeout(syncBadge, 2200);
}
// 统一消息通道:供 content.js 与 options.js 调用
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (!message || !message.type) return false;
if (message.type === 'HYLITER_OPEN_OPTIONS') {
chrome.runtime.openOptionsPage();
sendResponse({ ok: true });
return false;
}
if (message.type === 'HYLITER_WEBDAV_TEST') {
getLanguage()
.then((lang) => HyliterWebDAV.testConnection(message.config, lang))
.then((res) => sendResponse(res))
.catch((err) => sendResponse({ ok: false, error: err.message || String(err) }));
return true;
}
if (message.type === 'HYLITER_WEBDAV_BACKUP') {
(async () => {
const lang = await getLanguage();
const config = message.config || (await getWebdavConfig());
const data = await getHyliterData();
const res = await HyliterWebDAV.uploadBackup(config, data, lang);
await chrome.storage.local.set({
[WEBDAV_KEY]: { ...config, lastBackupAt: res.exportedAt },
});
sendResponse({ ok: true, exportedAt: res.exportedAt, remotePath: res.remotePath });
})().catch((err) => sendResponse({ ok: false, error: err.message || String(err) }));
return true;
}
if (message.type === 'HYLITER_WEBDAV_RESTORE') {
(async () => {
const lang = await getLanguage();
const config = message.config || (await getWebdavConfig());
const strategy = message.strategy === 'overwrite' ? 'overwrite' : 'merge';
const remote = await HyliterWebDAV.downloadBackup(config, lang);
let nextData;
if (strategy === 'overwrite') {
nextData = remote.data;
} else {
const localData = await getHyliterData();
nextData = HyliterWebDAV.mergeHyliterData(localData, remote.data);
}
const restoredAt = Date.now();
await chrome.storage.local.set({
[DATA_KEY]: nextData,
[WEBDAV_KEY]: { ...config, lastRestoreAt: restoredAt },
});
sendResponse({
ok: true,
restoredAt,
strategy,
pageCount: Object.keys(nextData.pages || {}).length,
});
})().catch((err) => sendResponse({ ok: false, error: err.message || String(err) }));
return true;
}
return false;
});