-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoptions.js
More file actions
509 lines (447 loc) · 19.5 KB
/
Copy pathoptions.js
File metadata and controls
509 lines (447 loc) · 19.5 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// 配置页面逻辑
document.addEventListener('DOMContentLoaded', async () => {
// 先初始化 i18n,确保后续渲染读取到的是已翻译文本
if (window.i18n) {
try {
await window.i18n.init();
} catch (e) {
console.warn('[options] i18n init failed', e);
}
}
// 绑定语言下拉框
const languageSelect = document.getElementById('language-select');
if (languageSelect && window.i18n) {
languageSelect.value = window.i18n.getPreference();
languageSelect.addEventListener('change', async (e) => {
try {
await window.i18n.setLanguage(e.target.value);
} catch (err) {
console.warn('[options] setLanguage failed', err);
}
});
}
// 模拟chrome.storage API用于预览
if (typeof chrome === 'undefined' || !chrome.storage) {
const mockStore = {
urls: ['https://github.com', 'https://stackoverflow.com', 'https://developer.mozilla.org'],
theme: 'system'
};
window.chrome = {
storage: {
sync: {
get: (keys) => {
if (Array.isArray(keys)) {
return Promise.resolve(keys.reduce((result, key) => {
result[key] = mockStore[key];
return result;
}, {}));
}
if (typeof keys === 'string') {
return Promise.resolve({ [keys]: mockStore[keys] });
}
return Promise.resolve({ ...mockStore });
},
set: (data) => {
Object.assign(mockStore, data);
return Promise.resolve();
}
},
onChanged: {
addListener: () => {}
}
},
runtime: {
sendMessage: (message) => Promise.resolve({ success: true }),
getManifest: () => ({ version: 'Preview' })
}
};
}
// 读取实际配置的快捷键并渲染
loadShortcuts();
async function loadShortcuts() {
const searchKeyEl = document.getElementById('shortcut-search');
const batchKeyEl = document.getElementById('shortcut-batch');
const dupKeyEl = document.getElementById('shortcut-duplicate');
const heroKeyEl = document.getElementById('heroShortcut');
try {
const commands = await chrome.commands.getAll();
const map = {};
commands.forEach(cmd => { map[cmd.name] = cmd.shortcut; });
if (searchKeyEl) renderShortcut(searchKeyEl, map['search-tabs-bookmarks']);
if (batchKeyEl) renderShortcut(batchKeyEl, map['open-all-urls']);
if (dupKeyEl) renderShortcut(dupKeyEl, map['duplicate-current-tab']);
if (heroKeyEl) renderShortcut(heroKeyEl, map['search-tabs-bookmarks']);
} catch (e) {
// 降级:平台推断
const isMac = navigator.platform.toUpperCase().includes('MAC') ||
navigator.userAgent.toUpperCase().includes('MAC');
const searchFallback = isMac ? 'Command+K' : 'Alt+K';
if (searchKeyEl) renderShortcut(searchKeyEl, searchFallback);
if (batchKeyEl) renderShortcut(batchKeyEl, isMac ? 'Command+Shift+U' : 'Ctrl+Shift+U');
if (dupKeyEl) renderShortcut(dupKeyEl, isMac ? 'Command+E' : 'Ctrl+Shift+E');
if (heroKeyEl) renderShortcut(heroKeyEl, searchFallback);
}
}
// 将 "Command+Shift+K" 这类字符串拆成多个 <kbd> 片段
function renderShortcut(container, shortcut) {
if (!shortcut) {
const notSet = window.i18n ? window.i18n.t('options_shortcutNotSet') : 'Not set';
container.innerHTML = `<span style="color:var(--muted);font-size:11px;">${escapeHtml(notSet)}</span>`;
return;
}
const KEY_MAP = {
'Command': '⌘', 'Ctrl': '⌃', 'Alt': '⌥', 'Shift': '⇧',
'MacCtrl': '⌃', 'Up': '↑', 'Down': '↓', 'Left': '←', 'Right': '→',
'Space': 'Space', 'Escape': 'Esc', 'Return': '↵'
};
const parts = shortcut.split('+').map(k => KEY_MAP[k] || k);
// 单键直接替换容器内容(保持父级 <kbd> 不变)
if (container.tagName === 'KBD') {
container.textContent = parts.join('');
return;
}
// 多键:渲染为一排 <kbd> 标签
container.innerHTML = parts.map(k => `<kbd>${k}</kbd>`).join('');
}
const urlInput = document.getElementById('urlInput');
const addBtn = document.getElementById('addBtn');
const urlList = document.getElementById('urlList');
const urlCount = document.getElementById('urlCount');
const emptyState = document.getElementById('emptyState');
const inputError = document.getElementById('inputError');
const inputSuccess = document.getElementById('inputSuccess');
const openAllBtn = document.getElementById('openAllBtn');
const clearAllBtn = document.getElementById('clearAllBtn');
const themeSelect = document.getElementById('themeSelect');
const quickPickToggle = document.getElementById('quickPickEnabled');
const pinyinMatchingToggle = document.getElementById('pinyinMatchingEnabled');
const tabGroupingToggle = document.getElementById('tabGroupingEnabled');
const resultsLimitSelect = document.getElementById('resultsLimit');
const preferenceKeys = window.PouncePreferences.SEARCH_PREFERENCE_KEYS;
const normalizeSearchPreferences = window.PouncePreferences.normalizeSearchPreferences;
let urls = [];
let themeManager;
// "Manage →" / hero "Change shortcut" 按钮:引导用户到快捷键设置页
function openShortcutsSettings() {
// chrome://extensions/shortcuts 无法通过 tabs.create 打开
// 导航当前标签页是唯一可行方式
chrome.tabs.getCurrent(tab => {
if (tab) chrome.tabs.update(tab.id, { url: 'chrome://extensions/shortcuts' });
});
}
const manageShortcutsBtn = document.getElementById('manageShortcutsBtn');
if (manageShortcutsBtn) {
manageShortcutsBtn.addEventListener('click', openShortcutsSettings);
}
const heroChangeShortcutBtn = document.getElementById('heroChangeShortcutBtn');
if (heroChangeShortcutBtn) {
heroChangeShortcutBtn.addEventListener('click', openShortcutsSettings);
}
// 初始化加载数据
loadUrls();
// 初始化主题管理器
initThemeManager();
// 初始化搜索行为偏好
initSearchPreferences();
// 动态设置版本号
try {
const manifestData = chrome.runtime.getManifest();
const versionElement = document.getElementById('optionsVersionText');
if (versionElement) {
versionElement.textContent = window.i18n
? window.i18n.t('options_versionLabel', [manifestData.version])
: 'Version ' + manifestData.version;
}
} catch (error) {
console.error('Failed to set version:', error);
}
// 添加按钮事件
addBtn.addEventListener('click', addUrl);
// 回车键添加
urlInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
addUrl();
}
});
// 打开所有URL按钮事件
openAllBtn.addEventListener('click', async () => {
if (urls.length === 0) {
showError(window.i18n ? window.i18n.t('options_noUrlsToOpen') : 'No URLs to open');
return;
}
openAllBtn.disabled = true;
const buttonText = openAllBtn.querySelector('span:not(.button-icon)');
const originalText = buttonText ? buttonText.textContent : 'Open All';
if (buttonText) buttonText.textContent = window.i18n ? window.i18n.t('popup_opening') : 'Opening...';
try {
await chrome.runtime.sendMessage({ action: 'openAllUrls' });
showSuccess(window.i18n ? window.i18n.t('options_openedOk') : 'All URLs opened successfully');
} catch (error) {
showError(window.i18n
? window.i18n.t('options_openFailed', [error.message])
: 'Failed to open: ' + error.message);
} finally {
openAllBtn.disabled = false;
if (buttonText) buttonText.textContent = originalText;
}
});
// 清空所有按钮事件
clearAllBtn.addEventListener('click', () => {
if (urls.length === 0) {
showError(window.i18n ? window.i18n.t('options_noUrlsToClear') : 'No URLs to clear');
return;
}
const confirmMsg = window.i18n
? window.i18n.t('options_clearUrlsConfirm')
: 'Are you sure you want to clear all URLs? This action cannot be undone.';
if (confirm(confirmMsg)) {
urls = [];
saveUrls();
renderUrlList();
showSuccess(window.i18n ? window.i18n.t('options_clearedOk') : 'All URLs cleared');
}
});
// 从存储加载 URL 列表
async function loadUrls() {
try {
const result = await chrome.storage.sync.get(['urls']);
urls = result.urls || [];
renderUrlList();
} catch (error) {
console.error('Failed to load data:', error);
showError(window.i18n ? window.i18n.t('options_loadFailed') : 'Failed to load data');
}
}
// 保存 URL 列表到存储
async function saveUrls() {
try {
await chrome.storage.sync.set({ urls: urls });
} catch (error) {
console.error('Failed to save data:', error);
showError(window.i18n ? window.i18n.t('options_saveFailed') : 'Failed to save data');
}
}
// 验证和规范化 URL
function validateAndNormalizeUrl(input) {
if (!input || !input.trim()) {
throw new Error(window.i18n ? window.i18n.t('options_urlEmpty') : 'Please enter a URL');
}
let url = input.trim();
// 自动补全协议前缀
if (!url.match(/^https?:\/\//i)) {
url = 'https://' + url;
}
// 验证 URL 格式
try {
const urlObj = new URL(url);
// 检查协议
if (!['http:', 'https:'].includes(urlObj.protocol)) {
throw new Error(window.i18n ? window.i18n.t('options_protocolError') : 'Only HTTP and HTTPS protocols are supported');
}
// 检查主机名
if (!urlObj.hostname) {
throw new Error(window.i18n ? window.i18n.t('options_urlInvalid') : 'Invalid URL format');
}
return urlObj.href;
} catch (e) {
if (e.message.includes('Invalid URL')) {
throw new Error(window.i18n ? window.i18n.t('options_urlInvalid') : 'Invalid URL format');
}
throw e;
}
}
// 添加 URL
async function addUrl() {
hideMessages();
try {
const normalizedUrl = validateAndNormalizeUrl(urlInput.value);
// 检查是否已存在
if (urls.includes(normalizedUrl)) {
throw new Error(window.i18n ? window.i18n.t('options_urlDuplicate') : 'This URL already exists');
}
// 添加到列表
urls.push(normalizedUrl);
await saveUrls();
// 更新界面
renderUrlList();
urlInput.value = '';
showSuccess(window.i18n ? window.i18n.t('options_urlAdded') : 'URL added successfully');
} catch (error) {
showError(error.message);
}
}
// 删除 URL
async function removeUrl(index) {
if (index >= 0 && index < urls.length) {
urls.splice(index, 1);
await saveUrls();
renderUrlList();
showSuccess(window.i18n ? window.i18n.t('options_urlRemoved') : 'URL removed successfully');
}
}
// 渲染 URL 列表
function renderUrlList() {
// 更新 "$count$ saved URLs" 文案(整体替换,原 #urlCount span 内嵌入数字)
const urlCountLabel = document.getElementById('urlCountLabel');
if (urlCountLabel) {
const label = window.i18n
? window.i18n.t('options_savedUrlsCount', [String(urls.length)])
: `${urls.length} saved URLs`;
urlCountLabel.textContent = label;
} else if (urlCount) {
urlCount.textContent = urls.length;
}
if (urls.length === 0) {
const noUrls = window.i18n ? window.i18n.t('options_noUrlsYet') : 'No URLs yet';
const addAbove = window.i18n ? window.i18n.t('options_addUrlAbove') : 'Add a URL above to get started';
urlList.innerHTML = `<div class="empty-state" id="emptyState">${escapeHtml(noUrls)}<br>${escapeHtml(addAbove)}</div>`;
return;
}
const openIcon = `<svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.9297 2H14.9297V6" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M7.59631 9.33333L14.9296 2" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12.9297 8.66667V12.6667C12.9297 13.0203 12.7892 13.3594 12.5392 13.6095C12.2891 13.8595 11.95 14 11.5964 14H4.26302C3.9094 14 3.57026 13.8595 3.32021 13.6095C3.07016 13.3594 2.92969 13.0203 2.92969 12.6667V5.33333C2.92969 4.97971 3.07016 4.64057 3.32021 4.39052C3.57026 4.14048 3.9094 4 4.26302 4H8.26302" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`;
const deleteIcon = `<svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.50256 7.33333V11.3333" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10.1693 7.33333V11.3333" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M13.5026 4V13.3333C13.5026 13.687 13.3622 14.0261 13.1121 14.2761C12.8621 14.5262 12.5229 14.6667 12.1693 14.6667H5.50264C5.14902 14.6667 4.80988 14.5262 4.55984 14.2761C4.30979 14.0261 4.16931 13.687 4.16931 13.3333V4" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M2.83594 4H14.8359" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6.16931 3.99999V2.66666C6.16931 2.31304 6.30979 1.9739 6.55984 1.72385C6.80988 1.4738 7.14902 1.33333 7.50264 1.33333H10.1693C10.5229 1.33333 10.8621 1.4738 11.1121 1.72385C11.3622 1.9739 11.5026 2.31304 11.5026 2.66666V3.99999" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`;
const openTitle = window.i18n ? window.i18n.t('options_openUrlTitle') : 'Open URL';
const removeTitle = window.i18n ? window.i18n.t('options_removeUrlTitle') : 'Remove URL';
const listHtml = urls.map((url, index) => `
<div class="url-item">
<span class="url-index">${index + 1}</span>
<span class="url-text">${escapeHtml(url)}</span>
<button class="open-btn" data-url="${escapeHtml(url)}" title="${escapeHtml(openTitle)}">${openIcon}</button>
<button class="delete-btn" data-index="${index}" title="${escapeHtml(removeTitle)}">${deleteIcon}</button>
</div>
`).join('');
urlList.innerHTML = listHtml;
// 为打开按钮添加事件监听器
const openButtons = urlList.querySelectorAll('.open-btn');
openButtons.forEach(button => {
button.addEventListener('click', (e) => {
const url = e.currentTarget.dataset.url;
chrome.tabs.create({ url, active: true });
});
});
// 为删除按钮添加事件监听器
const deleteButtons = urlList.querySelectorAll('.delete-btn');
deleteButtons.forEach(button => {
button.addEventListener('click', (e) => {
const index = parseInt(e.currentTarget.dataset.index);
removeUrl(index);
});
});
}
// 移除全局函数,现在使用事件监听器
// window.removeUrlAt = removeUrl;
// 显示错误消息
function showError(message) {
hideMessages();
inputError.textContent = message;
inputError.style.display = 'block';
setTimeout(hideMessages, 5000);
}
// 显示成功消息
function showSuccess(message) {
hideMessages();
inputSuccess.textContent = message;
inputSuccess.style.display = 'block';
setTimeout(hideMessages, 3000);
}
// 隐藏消息
function hideMessages() {
inputError.style.display = 'none';
inputSuccess.style.display = 'none';
}
// HTML 转义
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// 初始化主题管理器
async function initThemeManager() {
try {
themeManager = new ThemeManager();
// 直接从 storage 读取已保存主题,避免 ThemeManager async init 未完成时 getCurrentTheme() 返回默认值
const { theme: savedTheme } = await chrome.storage.sync.get(['theme']);
themeSelect.value = savedTheme || 'system';
// 监听主题选择变化
themeSelect.addEventListener('change', async (e) => {
await themeManager.setTheme(e.target.value);
showSuccess(window.i18n ? window.i18n.t('options_themeUpdated') : 'Theme updated successfully');
});
// 监听来自其他页面的主题变更(storage onChanged 比消息传递更可靠)
// 同步处理语言变更:重新加载翻译并刷新下拉框选中项
chrome.storage.onChanged.addListener(async (changes, area) => {
if (area !== 'sync') return;
if (changes.theme) {
themeSelect.value = changes.theme.newValue || 'system';
}
if (changes.language && window.i18n) {
try {
await window.i18n.reload();
} catch (e) {
console.warn('[options] i18n reload failed', e);
}
const sel = document.getElementById('language-select');
if (sel) sel.value = window.i18n.getPreference();
// 重新渲染包含动态文本的 URL 列表
renderUrlList();
}
});
} catch (error) {
console.error('Failed to initialize theme manager:', error);
}
}
async function initSearchPreferences() {
try {
const savedPreferences = await chrome.storage.sync.get(preferenceKeys);
applySearchPreferenceToggles(normalizeSearchPreferences(savedPreferences));
quickPickToggle.addEventListener('change', () => {
saveSearchPreference('quickPickEnabled', quickPickToggle.checked);
});
pinyinMatchingToggle.addEventListener('change', () => {
saveSearchPreference('pinyinMatchingEnabled', pinyinMatchingToggle.checked);
});
tabGroupingToggle.addEventListener('change', () => {
saveSearchPreference('tabGroupingEnabled', tabGroupingToggle.checked);
});
resultsLimitSelect.addEventListener('change', () => {
saveSearchPreference('resultsLimit', Number(resultsLimitSelect.value));
});
chrome.storage.onChanged.addListener((changes, area) => {
if (area !== 'sync') return;
const changedPreference = preferenceKeys.some(key => changes[key]);
if (!changedPreference) return;
applySearchPreferenceToggles(normalizeSearchPreferences({
quickPickEnabled: changes.quickPickEnabled ? changes.quickPickEnabled.newValue : quickPickToggle.checked,
pinyinMatchingEnabled: changes.pinyinMatchingEnabled ? changes.pinyinMatchingEnabled.newValue : pinyinMatchingToggle.checked,
tabGroupingEnabled: changes.tabGroupingEnabled ? changes.tabGroupingEnabled.newValue : tabGroupingToggle.checked,
resultsLimit: changes.resultsLimit ? changes.resultsLimit.newValue : Number(resultsLimitSelect.value)
}));
});
} catch (error) {
console.error('Failed to initialize search preferences:', error);
}
}
function applySearchPreferenceToggles(preferences) {
quickPickToggle.checked = preferences.quickPickEnabled;
pinyinMatchingToggle.checked = preferences.pinyinMatchingEnabled;
tabGroupingToggle.checked = preferences.tabGroupingEnabled;
resultsLimitSelect.value = String(preferences.resultsLimit);
}
async function saveSearchPreference(key, value) {
try {
await chrome.storage.sync.set({ [key]: value });
} catch (error) {
console.error('Failed to save search preference:', error);
showError(window.i18n ? window.i18n.t('options_settingSaveFailed') : 'Failed to save setting');
}
}
});