-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
1532 lines (1318 loc) · 51.1 KB
/
Copy pathpopup.js
File metadata and controls
1532 lines (1318 loc) · 51.1 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 弹窗主逻辑
import { I18n, _t } from './i18n.js';
import { escapeHtml, safeSetHTML } from './shared.js';
import { getAllBookmarks, analyzeBookmark, checkBrokenLinks } from './bookmark-scanner.js';
import { createCategoryFolder, batchMoveBookmarks } from './category-manager.js';
import { detectDuplicates } from './duplicate-detector.js';
import { backupBookmarks, restoreBookmarks, exportBookmarksToHTML, exportBookmarksToJSON, importBookmarksFromHTML } from './backup-manager.js';
import { logger } from './logger.js';
let categories = [];
let analysisResults = [];
let duplicates = [];
let selectedBookmarks = new Set();
let currentSettings = {};
let currentCategorySearch = '';
let currentDuplicateSearch = '';
let currentTypeFilters = new Set();
// ==================== 皮肤系统 ====================
const SKINS = [
{ id: 'default', nameKey: 'skinDefault' },
{ id: 'browser-native', nameKey: 'skinBrowserNative' },
{ id: 'minimal-business', nameKey: 'skinMinimalBusiness' },
{ id: 'classic-nostalgic', nameKey: 'skinClassicNostalgic' },
{ id: 'high-contrast-mono', nameKey: 'skinHighContrastMono' },
{ id: 'frosted-glass', nameKey: 'skinFrostedGlass' },
{ id: 'nature-low-saturation', nameKey: 'skinNatureLowSaturation' },
{ id: 'ocean-deep', nameKey: 'skinOceanDeep' },
{ id: 'sunset-glow', nameKey: 'skinSunsetGlow' },
{ id: 'starry-night', nameKey: 'skinStarryNight' },
{ id: 'cherry-blossom', nameKey: 'skinCherryBlossom' }
];
let customSkinData = null;
async function initSkin() {
const result = await chrome.storage.local.get(['skin', 'customSkin']);
const skin = result.skin || 'browser-native';
customSkinData = result.customSkin || null;
applySkin(skin);
}
function applySkin(skin) {
document.body.setAttribute('data-skin', skin);
const selector = document.getElementById('skinSelector');
if (selector) {
selector.value = skin;
}
const existingStyle = document.getElementById('custom-skin-style');
if (skin === 'custom' && customSkinData && customSkinData.css) {
if (existingStyle) {
existingStyle.textContent = customSkinData.css;
} else {
const style = document.createElement('style');
style.id = 'custom-skin-style';
style.textContent = customSkinData.css;
document.head.appendChild(style);
}
} else if (existingStyle) {
existingStyle.remove();
}
}
async function setSkin(skin) {
applySkin(skin);
await chrome.storage.local.set({ skin });
}
function initSkinSelector() {
const selector = document.getElementById('skinSelector');
if (!selector) return;
selector.textContent = '';
SKINS.forEach(skin => {
const option = document.createElement('option');
option.value = skin.id;
option.textContent = _t(skin.nameKey);
if (skin.id === (document.body.getAttribute('data-skin') || 'browser-native')) {
option.selected = true;
}
selector.appendChild(option);
});
if (customSkinData) {
const customOption = document.createElement('option');
customOption.value = 'custom';
customOption.textContent = customSkinData.name || _t('skinCustom') || 'Custom';
if ('custom' === document.body.getAttribute('data-skin')) {
customOption.selected = true;
}
selector.appendChild(customOption);
}
selector.addEventListener('change', (e) => {
setSkin(e.target.value);
});
}
// ==================== 深色模式 ====================
async function initTheme() {
const result = await chrome.storage.local.get('theme');
const theme = result.theme || 'light';
applyTheme(theme);
}
function applyTheme(theme) {
document.body.setAttribute('data-theme', theme);
const toggle = document.getElementById('themeToggle');
if (toggle) {
const moon = toggle.querySelector('.icon-moon');
const sun = toggle.querySelector('.icon-sun');
if (moon) moon.style.display = theme === 'dark' ? 'none' : 'block';
if (sun) sun.style.display = theme === 'dark' ? 'block' : 'none';
toggle.title = theme === 'dark' ? _t('tooltipLightMode') : _t('tooltipDarkMode');
}
}
async function toggleTheme() {
const current = document.body.getAttribute('data-theme') || 'light';
const next = current === 'dark' ? 'light' : 'dark';
applyTheme(next);
await chrome.storage.local.set({ theme: next });
}
// 初始化
document.addEventListener('DOMContentLoaded', async () => {
await I18n.init();
initLanguageSelector();
I18n.applyToPage();
await loadCategories();
await loadSettings();
setupEventListeners();
await loadBackupsList();
await initSkin();
initSkinSelector();
await initTheme();
});
// 初始化语言选择器
function initLanguageSelector() {
const selector = document.getElementById('langSelector');
if (!selector) return;
const locales = I18n.getSupportedLocales();
selector.textContent = '';
locales.forEach(loc => {
const option = document.createElement('option');
option.value = loc.code;
option.textContent = loc.native;
if (loc.code === I18n.getLocale()) {
option.selected = true;
}
selector.appendChild(option);
});
selector.addEventListener('change', (e) => {
I18n.setLocale(e.target.value);
});
}
// 语言切换时重新渲染动态内容
window.addEventListener('localeChanged', () => {
const currentTheme = document.body.getAttribute('data-theme') || 'light';
applyTheme(currentTheme);
initSkinSelector();
if (analysisResults.length > 0) {
displayCategories(currentCategorySearch);
}
if (duplicates.length > 0) {
displayDuplicates(currentFilterGroup, currentDuplicateSearch);
}
loadBackupsList();
if (brokenLinksResults.length > 0) {
displayBrokenLinksPopup();
}
});
// 加载分类规则
async function loadCategories() {
try {
const response = await chrome.runtime.sendMessage({ action: 'getCategories' });
if (response && response.categories) {
categories = response.categories;
}
} catch (error) {
console.error('加载分类规则失败:', error);
showMessage(_t('msgLoadCategoriesFailed'), 'error');
}
}
// 加载设置
async function loadSettings() {
const result = await chrome.storage.local.get('settings');
const settings = result.settings || {};
currentSettings = settings;
const autoBackupToggle = document.getElementById('autoBackupToggle');
autoBackupToggle.checked = settings.autoBackup !== false;
autoBackupToggle.addEventListener('change', async (e) => {
settings.autoBackup = e.target.checked;
await chrome.storage.local.set({ settings });
showMessage(_t('msgSettingsSaved'), 'success');
});
}
// 设置事件监听
function setupEventListeners() {
// 扫描按钮
document.getElementById('scanBtn').addEventListener('click', handleScan);
// 备份按钮
document.getElementById('backupBtn').addEventListener('click', handleBackup);
// 导出备份按钮(popup版)
document.getElementById('exportBackupBtnPopup')?.addEventListener('click', handleExportBackupPopup);
// 导入HTML书签(popup版)
document.getElementById('importFileInputPopup')?.addEventListener('change', handleImportFilePopup);
// 应用分类按钮
document.getElementById('applyCategoriesBtn').addEventListener('click', handleApplyCategories);
// 清理重复按钮
document.getElementById('removeDuplicatesBtn').addEventListener('click', handleRemoveDuplicates);
// 深色模式切换
document.getElementById('themeToggle')?.addEventListener('click', toggleTheme);
// 检查更新
document.getElementById('checkUpdateBtn')?.addEventListener('click', checkForUpdates);
// 搜索框
document.getElementById('categoriesSearch')?.addEventListener('input', (e) => {
currentCategorySearch = e.target.value.trim().toLowerCase();
displayCategories(currentCategorySearch);
});
document.getElementById('duplicatesSearch')?.addEventListener('input', (e) => {
currentDuplicateSearch = e.target.value.trim().toLowerCase();
displayDuplicates(currentFilterGroup, currentDuplicateSearch);
});
// 展开/折叠全部
document.getElementById('expandAllCategories')?.addEventListener('click', () => {
document.querySelectorAll('.category-group').forEach(g => g.classList.remove('collapsed'));
});
document.getElementById('collapseAllCategories')?.addEventListener('click', () => {
document.querySelectorAll('.category-group').forEach(g => g.classList.add('collapsed'));
});
// 分类组折叠切换(事件委托)
document.getElementById('categoriesList')?.addEventListener('click', (e) => {
const toggle = e.target.closest('.category-toggle');
if (toggle) {
const group = toggle.closest('.category-group');
group.classList.toggle('collapsed');
}
});
// 标签页切换
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const tabName = e.currentTarget.dataset.tab;
switchTab(tabName);
});
});
// 备份列表事件委托(替代内联onclick)
document.getElementById('backupsList').addEventListener('click', (e) => {
const restoreBtn = e.target.closest('[data-action="restore-backup"]');
if (restoreBtn) {
restoreBackup(parseInt(restoreBtn.dataset.index));
return;
}
const deleteBtn = e.target.closest('[data-action="delete-backup"]');
if (deleteBtn) {
deleteBackup(parseInt(deleteBtn.dataset.index));
return;
}
});
// 失效链接检测按钮
document.getElementById('checkBrokenLinksBtnPopup')?.addEventListener('click', handleCheckBrokenLinksPopup);
document.getElementById('selectAllBrokenBtnPopup')?.addEventListener('click', () => {
document.querySelectorAll('.broken-link-checkbox').forEach(cb => cb.checked = true);
});
document.getElementById('deselectAllBrokenBtnPopup')?.addEventListener('click', () => {
document.querySelectorAll('.broken-link-checkbox').forEach(cb => cb.checked = false);
});
document.getElementById('deleteBrokenLinksBtnPopup')?.addEventListener('click', handleDeleteBrokenLinksPopup);
// 失效链接搜索和排序
const brokenLinksSearchInputPopup = document.getElementById('brokenLinksSearchInputPopup');
if (brokenLinksSearchInputPopup) {
brokenLinksSearchInputPopup.addEventListener('input', (e) => {
brokenLinksSearchTermPopup = e.target.value.trim().toLowerCase();
displayBrokenLinksPopup();
});
}
const brokenLinksSortSelect = document.getElementById('brokenLinksSortPopup');
if (brokenLinksSortSelect) {
brokenLinksSortSelect.addEventListener('change', (e) => {
const field = e.target.value;
if (!field) {
brokenLinksSortPopup = { field: null, direction: 'asc' };
} else if (brokenLinksSortPopup.field === field) {
brokenLinksSortPopup.direction = brokenLinksSortPopup.direction === 'asc' ? 'desc' : 'asc';
} else {
brokenLinksSortPopup = { field, direction: 'asc' };
}
displayBrokenLinksPopup();
});
}
// 滚动辅助按钮
initScrollAssist('.scrollable-content');
}
// 滚动辅助按钮初始化
function initScrollAssist(scrollSelector) {
const scrollBtn = document.getElementById('scrollAssistBtn');
if (!scrollBtn) return;
const scrollContainer = document.querySelector(scrollSelector) || window;
const scrollEl = scrollContainer === window ? document.documentElement : scrollContainer;
function updateScrollBtn() {
const scrollTop = scrollEl.scrollTop || window.scrollY || 0;
const scrollHeight = scrollEl.scrollHeight || document.documentElement.scrollHeight;
const clientHeight = scrollEl.clientHeight || window.innerHeight;
if (scrollHeight <= clientHeight + 10) {
scrollBtn.classList.add('hidden');
return;
}
scrollBtn.classList.remove('hidden');
const nearBottom = scrollTop + clientHeight >= scrollHeight - 50;
if (nearBottom) {
scrollBtn.textContent = '▲';
scrollBtn.title = _t('btnScrollToTop');
scrollBtn.dataset.direction = 'top';
} else {
scrollBtn.textContent = '▼';
scrollBtn.title = _t('btnScrollToBottom');
scrollBtn.dataset.direction = 'bottom';
}
}
scrollBtn.addEventListener('click', () => {
if (scrollBtn.dataset.direction === 'top') {
scrollEl.scrollTo({ top: 0, behavior: 'smooth' });
} else {
scrollEl.scrollTo({ top: scrollEl.scrollHeight, behavior: 'smooth' });
}
});
scrollContainer.addEventListener('scroll', updateScrollBtn, { passive: true });
window.addEventListener('resize', updateScrollBtn, { passive: true });
// 延迟初始化,等待内容渲染
setTimeout(updateScrollBtn, 300);
}
// 处理扫描
async function handleScan() {
const scanBtn = document.getElementById('scanBtn');
const progressContainer = document.getElementById('progressContainer');
const progressFill = document.getElementById('progressFill');
const progressText = document.getElementById('progressText');
scanBtn.disabled = true;
progressContainer.classList.remove('hidden');
progressFill.style.width = '0%';
progressText.textContent = _t('progressGettingBookmarks');
try {
// 自动备份
const settingsResult = await chrome.storage.local.get('settings');
if (settingsResult.settings?.autoBackup) {
progressText.textContent = _t('progressAutoBackup');
await backupBookmarks();
await loadBackupsList();
}
// 获取所有书签
progressText.textContent = _t('progressAnalyzing');
const bookmarks = await getAllBookmarks();
// 分析每个书签
analysisResults = [];
const total = bookmarks.length;
for (let i = 0; i < total; i++) {
const result = await analyzeBookmark(bookmarks[i], categories);
analysisResults.push(result);
// 更新进度
const progress = ((i + 1) / total) * 100;
progressFill.style.width = `${progress}%`;
progressText.textContent = _t('progressAnalyzingItem', [`${i + 1}`, `${total}`]);
// 每处理10个让出控制权,避免阻塞UI
if (i % 10 === 0) {
await new Promise(resolve => setTimeout(resolve, 0));
}
}
// 检测重复
progressText.textContent = _t('progressDetectingDuplicates');
const threshold = (currentSettings.similarityThreshold || 80) / 100;
duplicates = await detectDuplicates(threshold);
// 显示统计信息
displayStats(bookmarks.length, duplicates.length);
// 显示分类建议
displayCategories(currentCategorySearch);
// 显示重复项
displayDuplicates(currentFilterGroup, currentDuplicateSearch);
progressText.textContent = _t('progressComplete');
showMessage(_t('msgScanComplete', [`${total}`]), 'success');
} catch (error) {
console.error('扫描失败:', error);
showMessage(_t('msgScanFailed') + error.message, 'error');
} finally {
scanBtn.disabled = false;
setTimeout(() => {
progressContainer.classList.add('hidden');
}, 1500);
}
}
// 显示统计信息
function displayStats(total, duplicateCount) {
const statsPanel = document.getElementById('statsPanel');
statsPanel.classList.remove('hidden');
document.getElementById('totalBookmarks').textContent = total;
const uncategorized = analysisResults.filter(r => !r.category || r.confidence === 'none').length;
document.getElementById('uncategorizedCount').textContent = uncategorized;
document.getElementById('duplicatesCount').textContent = duplicateCount;
}
// 显示分类建议
function displayCategories(searchTerm = '') {
const container = document.getElementById('categoriesList');
const applyBtn = document.getElementById('applyCategoriesBtn');
const toolbar = document.getElementById('categoriesToolbar');
// 按分类分组
const grouped = {};
for (const result of analysisResults) {
if (result.category && result.confidence !== 'none') {
const catName = result.category.name;
if (!grouped[catName]) {
grouped[catName] = [];
}
grouped[catName].push(result);
}
}
// 根据搜索词过滤
const term = searchTerm.toLowerCase();
for (const catName of Object.keys(grouped)) {
if (term) {
grouped[catName] = grouped[catName].filter(item => {
const title = (item.bookmark.title || '').toLowerCase();
const url = (item.bookmark.url || '').toLowerCase();
return title.includes(term) || url.includes(term);
});
}
}
for (const catName of Object.keys(grouped)) {
if (grouped[catName].length === 0) {
delete grouped[catName];
}
}
// 清空之前的选择状态
selectedBookmarks.clear();
if (Object.keys(grouped).length === 0) {
safeSetHTML(container, `<p class="empty-state">${term ? _t('emptyNoResults') : _t('emptyNoCategories')}</p>`);
applyBtn.classList.add('hidden');
toolbar?.classList.add('hidden');
return;
}
toolbar?.classList.remove('hidden');
let html = '';
for (const [catName, items] of Object.entries(grouped)) {
html += `
<div class="category-group">
<div class="category-header">
<div class="category-header-left">
<button class="category-toggle" aria-label="Toggle">▼</button>
<span class="category-name">${escapeHtml(catName)}</span>
</div>
<span class="category-count">${_t('labelBookmarksCount', [`${items.length}`])}</span>
</div>
<div class="category-items">
`;
for (const item of items) {
const bookmark = item.bookmark;
const confidenceClass = `confidence-${item.confidence}`;
const confidenceText = {
'high': _t('confidenceHigh'),
'medium': _t('confidenceMedium'),
'low': _t('confidenceLow')
}[item.confidence];
html += `
<div class="bookmark-item">
<input type="checkbox" class="bookmark-checkbox"
data-id="${bookmark.id}"
data-folder="${catName}"
checked>
<div class="bookmark-info">
<div class="bookmark-title">${escapeHtml(bookmark.title)}</div>
<div class="bookmark-url">${escapeHtml(bookmark.url)}</div>
<div class="bookmark-meta">
<span class="confidence-badge ${confidenceClass}">
${_t('labelConfidence')}${confidenceText}
</span>
</div>
</div>
</div>
`;
}
html += '</div></div>';
}
safeSetHTML(container, html);
applyBtn.classList.remove('hidden');
// 监听复选框变化
container.querySelectorAll('.bookmark-checkbox').forEach(checkbox => {
checkbox.addEventListener('change', (e) => {
if (e.target.checked) {
selectedBookmarks.add(e.target.dataset.id);
} else {
selectedBookmarks.delete(e.target.dataset.id);
}
});
// 初始化选中状态
selectedBookmarks.add(checkbox.dataset.id);
});
}
// 显示重复项(带标签筛选)
let currentFilterGroup = null; // 当前筛选的组索引,null表示显示全部
function displayDuplicates(filterGroupIndex = null, searchTerm = '') {
const container = document.getElementById('duplicatesList');
const removeBtn = document.getElementById('removeDuplicatesBtn');
const toolbar = document.getElementById('duplicatesToolbar');
if (duplicates.length === 0) {
safeSetHTML(container, `<p class="empty-state">${_t('emptyNoDuplicates')}</p>`);
removeBtn.classList.add('hidden');
toolbar?.classList.add('hidden');
currentFilterGroup = null; // 清除筛选状态
return;
}
// 安全检查:如果筛选索引超出范围,自动清除筛选
if (filterGroupIndex !== null && (filterGroupIndex < 0 || filterGroupIndex >= duplicates.length)) {
filterGroupIndex = null;
currentFilterGroup = null;
}
// 根据搜索词过滤
const term = searchTerm.toLowerCase();
let filteredDuplicates = duplicates;
if (term) {
filteredDuplicates = duplicates.map(group => ({
...group,
items: group.items.filter(item => {
const title = (item.title || '').toLowerCase();
const url = (item.url || '').toLowerCase();
return title.includes(term) || url.includes(term);
})
})).filter(group => group.items.length > 0);
}
// 根据重复类型筛选
if (currentTypeFilters.size > 0) {
filteredDuplicates = filteredDuplicates.filter(group => currentTypeFilters.has(group.type));
}
if (filteredDuplicates.length === 0) {
safeSetHTML(container, `<p class="empty-state">${_t('emptyNoResults')}</p>`);
removeBtn.classList.add('hidden');
toolbar?.classList.remove('hidden');
return;
}
toolbar?.classList.remove('hidden');
let html = '';
// 添加重复类型说明(可点击筛选)
const exactActive = currentTypeFilters.has('exact') ? 'filter-active' : '';
const similarActive = currentTypeFilters.has('similar') ? 'filter-active' : '';
const normalizedActive = currentTypeFilters.has('normalized') ? 'filter-active' : '';
html += `
<div class="duplicates-legend">
<div class="legend-item legend-exact ${exactActive}" data-action="filter-type" data-type="exact">
<span class="legend-dot"></span>
<div class="legend-text">
<span class="legend-label">${_t('duplicateExact')}</span>
<span class="legend-desc">${_t('duplicateExactDesc')}</span>
</div>
</div>
<div class="legend-item legend-similar ${similarActive}" data-action="filter-type" data-type="similar">
<span class="legend-dot"></span>
<div class="legend-text">
<span class="legend-label">${_t('duplicateSimilar')}</span>
<span class="legend-desc">${_t('duplicateSimilarDesc')}</span>
</div>
</div>
<div class="legend-item legend-normalized ${normalizedActive}" data-action="filter-type" data-type="normalized">
<span class="legend-dot"></span>
<div class="legend-text">
<span class="legend-label">${_t('duplicateNormalized')}</span>
<span class="legend-desc">${_t('duplicateNormalizedDesc')}</span>
</div>
</div>
</div>
`;
// 添加标签筛选区域(仅在未筛选时显示)
if (filterGroupIndex === null) {
html += '<div class="duplicate-filter-tags">';
filteredDuplicates.forEach((group, index) => {
const firstItem = group.items[0];
const fullTitle = firstItem.title;
const title = escapeHtml(fullTitle.substring(0, 20));
const count = group.items.length;
const tooltip = `标题:${fullTitle}\n网址:${firstItem.url}`;
const originalIndex = term ? duplicates.findIndex(g => g.items[0].id === firstItem.id) : index;
html += `
<button class="filter-tag" data-group-index="${originalIndex >= 0 ? originalIndex : index}" title="${tooltip.replace(/"/g, '"')}">
<span class="filter-tag-title">${title}</span>
<span class="filter-tag-count">(${count})</span>
</button>
`;
});
html += '</div>';
} else {
// 显示返回按钮和当前筛选信息
html += `
<div class="duplicate-filter-info">
<button class="btn-back-filter" data-action="clear-filter">${_t('btnBackToAll')}</button>
<span class="filter-label">${_t('labelViewing')}${escapeHtml(filteredDuplicates[filterGroupIndex].items[0].title.substring(0, 30))}</span>
</div>
`;
}
// 确定要显示的组列表
const groupsToShow = filterGroupIndex !== null ?
[{ ...filteredDuplicates[filterGroupIndex], originalIndex: filterGroupIndex }] :
filteredDuplicates.map((group, index) => {
const originalIndex = term ? duplicates.findIndex(g => g.items[0].id === group.items[0].id) : index;
return { ...group, originalIndex: originalIndex >= 0 ? originalIndex : index };
});
groupsToShow.forEach((group, displayIndex) => {
const actualIndex = group.originalIndex;
let typeText = _t('duplicateSimilar');
if (group.type === 'exact') {
typeText = _t('duplicateExact');
} else if (group.type === 'normalized') {
typeText = _t('duplicateNormalized');
}
const similarityText = group.similarity ?
_t('labelSimilarity', [`${(group.similarity * 100).toFixed(0)}`]) : '';
const typeClass = group.type === 'exact' ? 'exact' : (group.type === 'normalized' ? 'normalized' : 'similar');
html += `
<div class="duplicate-group duplicate-group-${typeClass}" data-group-index="${actualIndex}">
<div class="duplicate-type duplicate-type-${typeClass}">${typeText} ${similarityText}</div>
`;
group.items.forEach((item, idx) => {
const showPath = currentSettings.showPath !== false;
const pathHtml = (showPath && item.path) ?
`<div class="bookmark-path">📁 ${escapeHtml(item.path)}</div>` : '';
// Note: path is translated in utils.js via _t('bookmarksBar') / _t('unknownPath')
// 智能默认勾选:优先保留书签栏中的副本;若全组都在书签栏中,则保留第一个
const nonBarItems = group.items.filter(i => !i.inBookmarksBar);
const shouldCheck = nonBarItems.length > 0 ? !item.inBookmarksBar : (idx !== 0);
html += `
<div class="duplicate-item">
<input type="checkbox" name="duplicate-${actualIndex}-${idx}"
value="${item.id}"
class="duplicate-checkbox"
data-id="${item.id}"
data-group="${actualIndex}"
${shouldCheck ? 'checked' : ''}>
<div class="bookmark-info">
<div class="bookmark-title">${escapeHtml(item.title)}</div>
<div class="bookmark-url">${escapeHtml(item.url)}</div>
${pathHtml}
</div>
<button class="btn-delete-single"
data-action="delete-single"
data-bookmark-id="${item.id}"
data-group-index="${actualIndex}"
data-item-index="${idx}"
title="${_t('tooltipDeleteBookmark')}">
🗑️
</button>
</div>
`;
});
html += '</div>';
});
safeSetHTML(container, html);
removeBtn.classList.remove('hidden');
// 更新当前筛选状态
currentFilterGroup = filterGroupIndex;
// 绑定事件监听器(替代内联onclick)
bindDuplicateEvents();
}
// 绑定重复项相关的事件监听器
function bindDuplicateEvents() {
const container = document.getElementById('duplicatesList');
// 克隆节点以移除旧的事件监听器(避免重复绑定)
const newContainer = container.cloneNode(true);
container.parentNode.replaceChild(newContainer, container);
// 筛选标签点击事件(使用事件委托)
newContainer.addEventListener('click', (e) => {
// 类型筛选标签
const typeFilter = e.target.closest('[data-action="filter-type"]');
if (typeFilter) {
const type = typeFilter.dataset.type;
if (currentTypeFilters.has(type)) {
currentTypeFilters.delete(type);
} else {
currentTypeFilters.add(type);
}
// 类型筛选改变时,清除分组筛选(因为组列表可能变化)
currentFilterGroup = null;
displayDuplicates(null, currentDuplicateSearch);
return;
}
// 分组筛选标签
const filterTag = e.target.closest('.filter-tag');
if (filterTag) {
const groupIndex = parseInt(filterTag.dataset.groupIndex);
filterDuplicates(groupIndex);
return;
}
// 返回全部按钮
const backFilter = e.target.closest('[data-action="clear-filter"]');
if (backFilter) {
clearDuplicateFilter();
return;
}
// 单个删除按钮(使用事件委托)
const deleteBtn = e.target.closest('[data-action="delete-single"]');
if (deleteBtn) {
const bookmarkId = deleteBtn.dataset.bookmarkId;
const groupIndex = parseInt(deleteBtn.dataset.groupIndex);
const itemIndex = parseInt(deleteBtn.dataset.itemIndex);
deleteSingleDuplicate(bookmarkId, groupIndex, itemIndex);
return;
}
});
}
// 应用分类
async function handleApplyCategories() {
if (selectedBookmarks.size === 0) {
showMessage(_t('msgNoBookmarksSelected'), 'warning');
return;
}
if (!confirm(_t('confirmApplyCategories', [`${selectedBookmarks.size}`]))) {
return;
}
const applyBtn = document.getElementById('applyCategoriesBtn');
applyBtn.disabled = true;
applyBtn.textContent = _t('statusApplying');
try {
// 收集需要移动的书签
const moves = [];
document.querySelectorAll('.bookmark-checkbox:checked').forEach(checkbox => {
moves.push({
id: checkbox.dataset.id,
folder: checkbox.dataset.folder
});
});
// 按文件夹分组
const folderGroups = {};
for (const move of moves) {
if (!folderGroups[move.folder]) {
folderGroups[move.folder] = [];
}
folderGroups[move.folder].push(move.id);
}
// 执行移动
let successCount = 0;
for (const [folderName, ids] of Object.entries(folderGroups)) {
// 创建或获取文件夹
const folder = await createCategoryFolder(folderName);
// 批量移动
const results = await batchMoveBookmarks(ids, folder.id);
successCount += results.filter(r => r.success).length;
}
showMessage(_t('msgApplySuccess', [`${successCount}`]), 'success');
// 重新扫描
setTimeout(() => {
handleScan();
}, 1000);
} catch (error) {
console.error('应用分类失败:', error);
showMessage(_t('msgApplyFailed') + error.message, 'error');
} finally {
applyBtn.disabled = false;
applyBtn.textContent = _t('btnApplyCategories');
}
}
// 筛选重复项(点击标签)
function filterDuplicates(groupIndex) {
displayDuplicates(groupIndex);
}
// 清除筛选,显示全部
function clearDuplicateFilter() {
currentFilterGroup = null;
currentTypeFilters.clear();
displayDuplicates(null, currentDuplicateSearch);
}
// 删除单个重复项
async function deleteSingleDuplicate(bookmarkId, groupIndex, itemIndex) {
if (!confirm(_t('confirmDeleteBookmark'))) {
return;
}
try {
await chrome.bookmarks.remove(bookmarkId);
showMessage(_t('msgDeleteSuccess'), 'success');
// 从数据中移除该项
const group = duplicates[groupIndex];
if (!group) {
console.error('组不存在:', groupIndex);
displayDuplicates(currentFilterGroup);
return;
}
group.items.splice(itemIndex, 1);
// 如果该组只剩一个或没有项目,从列表中移除该组
const groupWasRemoved = group.items.length <= 1;
if (groupWasRemoved) {
duplicates.splice(groupIndex, 1);
// 如果当前处于筛选模式,需要调整筛选索引
if (currentFilterGroup !== null) {
if (currentFilterGroup === groupIndex) {
// 删除了当前筛选的组,清除筛选状态
currentFilterGroup = null;
} else if (currentFilterGroup > groupIndex) {
// 删除了当前筛选组之前的组,索引需要前移
currentFilterGroup--;
}
}
}
// 重新显示(保持当前筛选状态)
displayDuplicates(currentFilterGroup);
} catch (error) {
console.error('Delete failed:', error);
showMessage(_t('msgDeleteFailed') + error.message, 'error');
}
}
// 清理重复项(支持多选)
async function handleRemoveDuplicates() {
// 获取所有选中的复选框
const selectedCheckboxes = document.querySelectorAll('.duplicate-checkbox:checked');
if (selectedCheckboxes.length === 0) {
showMessage(_t('msgNoDuplicatesSelected'), 'warning');
return;
}
if (!confirm(_t('confirmRemoveDuplicates', [`${selectedCheckboxes.length}`]))) {
return;
}
const removeBtn = document.getElementById('removeDuplicatesBtn');
removeBtn.disabled = true;
removeBtn.textContent = _t('statusDeleting');
try {
let deleteCount = 0;
const deletedIds = new Set();
// 批量删除选中的书签
for (const checkbox of selectedCheckboxes) {
try {
await chrome.bookmarks.remove(checkbox.value);
deleteCount++;
deletedIds.add(checkbox.value);
} catch (error) {
console.error('删除失败:', error);
}
}
showMessage(_t('msgRemoveSuccess', [`${deleteCount}`]), 'success');
// 立即从本地数据中移除被删除的项目(关键修复)
const groupsToRemove = [];
duplicates.forEach((group, groupIndex) => {
group.items = group.items.filter(item => !deletedIds.has(item.id));
if (group.items.length <= 1) {
groupsToRemove.push(groupIndex);
}
});
// 从后往前删除空组,避免索引前移问题
for (let i = groupsToRemove.length - 1; i >= 0; i--) {
const groupIndex = groupsToRemove[i];
duplicates.splice(groupIndex, 1);
// 如果当前处于筛选模式,同步调整筛选索引
if (currentFilterGroup !== null) {
if (currentFilterGroup === groupIndex) {
currentFilterGroup = null;
} else if (currentFilterGroup > groupIndex) {
currentFilterGroup--;
}
}
}
// 立即刷新页面显示
displayDuplicates(currentFilterGroup);
} catch (error) {
console.error('清理重复失败:', error);
showMessage(_t('msgRemoveFailed') + error.message, 'error');
} finally {
removeBtn.disabled = false;
removeBtn.textContent = _t('btnRemoveDuplicates');
}
}
// 处理备份
async function handleBackup() {
const backupBtn = document.getElementById('backupBtn');
backupBtn.disabled = true;
backupBtn.textContent = '备份中...';
try {
await backupBookmarks();
await loadBackupsList();
showMessage(_t('msgBackupSuccess'), 'success');