-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
6904 lines (5924 loc) · 225 KB
/
Copy pathscript.js
File metadata and controls
6904 lines (5924 loc) · 225 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
// ==================== 配置 ====================
const CONFIG = {
debug: false, // 生产环境设置为 false
defaultShortcuts: [
{ name: 'Google', url: 'https://www.google.com', icon: '' },
{ name: 'YouTube', url: 'https://www.youtube.com', icon: '' },
{ name: 'GitHub', url: 'https://github.com', icon: '' },
{ name: '百度', url: 'https://www.baidu.com', icon: '' },
{ name: '知乎', url: 'https://www.zhihu.com', icon: '' },
{ name: 'B站', url: 'https://www.bilibili.com', icon: '' }
],
searchEngines: {
google: 'https://www.google.com/search?q=',
bing: 'https://www.bing.com/search?q=',
baidu: 'https://www.baidu.com/s?wd='
},
defaultSettings: {
searchEngine: 'google',
searchOpacity: 5,
autoHideControls: false, // 默认不自动隐藏
gridColumns: 12 // 默认每行12个图标
}
};
const ICON_FALLBACK_TIMEOUT_MS = 2500;
const ALLOWED_SHORTCUT_PROTOCOLS = new Set([
'http:',
'https:',
'chrome:',
'chrome-extension:',
'file:',
'ftp:',
'mailto:'
]);
function normalizeShortcutUrl(rawUrl) {
if (typeof rawUrl !== 'string') return null;
const trimmed = rawUrl.trim();
if (!trimmed) return null;
const hasScheme = /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(trimmed);
const candidate = hasScheme ? trimmed : `https://${trimmed}`;
try {
const parsed = new URL(candidate);
if (!ALLOWED_SHORTCUT_PROTOCOLS.has(parsed.protocol)) return null;
return parsed.href;
} catch {
return null;
}
}
// ==================== 调试日志 ====================
const Logger = {
debug: (...args) => {
if (CONFIG.debug) {
console.log('[DEBUG]', ...args); // ✅ 修复:使用 console.log
}
},
warn: (...args) => {
if (CONFIG.debug) {
console.warn('[WARN]', ...args); // ✅ 修复:使用 console.warn
}
},
error: (...args) => {
// 错误日志始终显示
console.error('[ERROR]', ...args); // ✅ 修复:使用 console.error
}
};
// ==================== 全局错误处理 ====================
// ✅ 添加全局错误捕获,记录错误日志
window.addEventListener('error', (event) => {
Logger.error('Global error:', event.error || event.message, 'at', event.filename, 'line', event.lineno);
});
window.addEventListener('unhandledrejection', (event) => {
Logger.error('Unhandled promise rejection:', event.reason);
});
// ==================== 状态管理 ====================
const State = {
currentEngine: CONFIG.defaultSettings.searchEngine,
customEngineUrl: '', // 自定义搜索引擎URL
tabs: [],
currentTabId: null,
shortcuts: [],
editingIndex: -1, // -1表示添加模式,>=0表示编辑模式
editingTabId: null, // 用于标签页编辑模式
editingFolderItemIndex: -1, // 用于编辑分组内的快捷方式
undoData: null, // 用于存储撤回数据
undoTimeout: null, // 撤回提示的定时器
countdownInterval: null, // 倒计时interval
draggedItem: null, // 拖拽的元素
dropTarget: null, // 放置目标
lastFolderMovePosition: null, // 记录上次文件夹移动位置,防止重复触发
draggingTab: false, // 是否正在拖拽标签页
selectedShortcutIds: new Set(),
lastSelectedShortcutId: null,
selectedFolderItemIds: new Set(),
lastSelectedFolderItemId: null
};
// 将 State 暴露到全局作用域,供 drag-handler.js 使用
window.State = State;
// 拖拽处理器实例
const dragHandler = new DragHandler();
// ==================== 资源清理管理器 ====================
class CleanupManager {
constructor() {
this.timers = new Set();
// 页面卸载时清理所有资源
window.addEventListener('beforeunload', () => {
this.cleanup();
});
}
setTimeout(callback, delay) {
const id = setTimeout(() => {
callback();
this.timers.delete(id);
}, delay);
this.timers.add(id);
return id;
}
setInterval(callback, delay) {
const id = setInterval(callback, delay);
this.timers.add(id);
return id;
}
clearTimer(id) {
clearTimeout(id);
clearInterval(id);
this.timers.delete(id);
}
cleanup() {
this.timers.forEach(id => {
clearTimeout(id);
clearInterval(id);
});
this.timers.clear();
Logger.debug('Cleaned up', this.timers.size, 'timers');
}
}
const cleanupManager = new CleanupManager();
// ==================== 数据校验 ====================
const Validator = {
// 校验标签页数据结构
isValidTab(tab) {
return tab &&
typeof tab.id === 'string' &&
typeof tab.name === 'string' &&
Array.isArray(tab.shortcuts);
},
// 校验快捷方式数据结构
isValidShortcut(shortcut) {
if (!shortcut) return false;
// 分组类型
if (shortcut.type === 'folder') {
return typeof shortcut.name === 'string' &&
Array.isArray(shortcut.items) &&
shortcut.items.every(item => this.isValidShortcut(item));
}
// 普通快捷方式
return typeof shortcut.name === 'string' &&
typeof shortcut.url === 'string' &&
normalizeShortcutUrl(shortcut.url) !== null;
},
// 清理无效数据
sanitizeTabs(tabs) {
if (!Array.isArray(tabs)) return [];
return tabs
.filter(tab => this.isValidTab(tab))
.map(tab => ({
...tab,
shortcuts: this.sanitizeShortcuts(tab.shortcuts)
}));
},
sanitizeShortcuts(shortcuts) {
if (!Array.isArray(shortcuts)) return [];
return shortcuts.filter(shortcut => this.isValidShortcut(shortcut));
}
};
// ==================== 统一提示系统 ====================
class ToastManager {
constructor() {
this.toasts = [];
}
// 显示提示
show(message, type = 'info', duration = 3000) {
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
// 根据类型选择图标和样式
const styles = {
success: {
icon: '✓',
background: 'rgba(255, 255, 255, 0.15)',
borderColor: 'rgba(52, 211, 153, 0.5)',
iconColor: '#34d399',
shadowColor: 'rgba(52, 211, 153, 0.2)'
},
error: {
icon: '✕',
background: 'rgba(255, 255, 255, 0.15)',
borderColor: 'rgba(248, 113, 113, 0.5)',
iconColor: '#f87171',
shadowColor: 'rgba(248, 113, 113, 0.2)'
},
warning: {
icon: '⚠',
background: 'rgba(255, 255, 255, 0.15)',
borderColor: 'rgba(251, 191, 36, 0.5)',
iconColor: '#fbbf24',
shadowColor: 'rgba(251, 191, 36, 0.2)'
},
info: {
icon: 'ℹ',
background: 'rgba(255, 255, 255, 0.15)',
borderColor: 'rgba(96, 165, 250, 0.5)',
iconColor: '#60a5fa',
shadowColor: 'rgba(96, 165, 250, 0.2)'
}
};
const style = styles[type] || styles.info;
const iconSpan = document.createElement('span');
iconSpan.className = 'toast-icon';
iconSpan.textContent = style.icon;
iconSpan.style.color = style.iconColor;
iconSpan.style.fontWeight = 'bold';
iconSpan.style.fontSize = '16px';
const messageSpan = document.createElement('span');
messageSpan.className = 'toast-message';
messageSpan.textContent = message;
toast.appendChild(iconSpan);
toast.appendChild(messageSpan);
toast.style.cssText = `
position: fixed;
top: ${80 + this.toasts.length * 70}px;
left: 50%;
transform: translateX(-50%);
background: ${style.background};
backdrop-filter: blur(20px) saturate(180%);
-webkit-backdrop-filter: blur(20px) saturate(180%);
border: 1px solid ${style.borderColor};
color: white;
padding: 14px 24px;
border-radius: 12px;
font-size: 14px;
font-weight: 500;
box-shadow: 0 8px 32px ${style.shadowColor}, 0 4px 12px rgba(0, 0, 0, 0.15);
z-index: 10000;
display: inline-flex;
align-items: center;
gap: 10px;
opacity: 0;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
pointer-events: none;
width: auto;
white-space: nowrap;
`;
document.body.appendChild(toast);
// 添加到数组
this.toasts.push(toast);
// 触发动画
requestAnimationFrame(() => {
toast.style.opacity = '1';
toast.style.transform = 'translateX(-50%) translateY(0)';
});
// 自动移除
setTimeout(() => {
this.remove(toast);
}, duration);
return toast;
}
// 移除提示
remove(toast) {
toast.style.opacity = '0';
toast.style.transform = 'translateX(-50%) translateY(-20px)';
setTimeout(() => {
if (toast.parentNode) {
toast.remove();
}
// 从数组中移除
const index = this.toasts.indexOf(toast);
if (index > -1) {
this.toasts.splice(index, 1);
}
// 重新排列剩余的 toast
this.toasts.forEach((t, i) => {
t.style.top = `${80 + i * 70}px`;
});
}, 300);
}
// 快捷方法
success(message, duration) {
return this.show(message, 'success', duration);
}
error(message, duration) {
return this.show(message, 'error', duration);
}
warning(message, duration) {
return this.show(message, 'warning', duration);
}
info(message, duration) {
return this.show(message, 'info', duration);
}
}
// 创建全局实例
const Toast = new ToastManager();
// ==================== 工具函数 ====================
const Utils = {
// 获取 Favicon URL(优先使用浏览器缓存)
getFaviconUrl(url) {
try {
const pageUrl = new URL(url).href;
if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.getURL &&
typeof location !== 'undefined' && location.protocol === 'chrome-extension:') {
const base = chrome.runtime.getURL('_favicon/');
return `${base}?pageUrl=${encodeURIComponent(pageUrl)}&size=128`;
}
return `chrome://favicon2/?size=128&scale=1&pageUrl=${encodeURIComponent(pageUrl)}`;
} catch {
return Utils.getDefaultIconData();
}
},
// 获取 Favicon URL(外网兜底)
getGoogleFaviconUrl(url) {
try {
const domain = new URL(url).origin;
return `https://www.google.com/s2/favicons?domain=${domain}&sz=128`;
} catch {
return null;
}
},
// 默认占位图标(SVG)
getDefaultIconData() {
return 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23ffffff"><circle cx="12" cy="12" r="10"/></svg>';
},
// 判断是否为内嵌图标
isDataIcon(icon) {
return typeof icon === 'string' && icon.startsWith('data:image');
},
// 生成文字图标(SVG)
generateTextIcon(text, customColor = null) {
if (!text || text.trim().length === 0) {
return null;
}
// 限制1-3个字符
const displayText = text.trim().substring(0, 3).toUpperCase();
// 根据文本生成一个确定的颜色
const colors = [
'#667eea', // 蓝紫
'#764ba2', // 深紫
'#f093fb', // 粉紫
'#4facfe', // 天蓝
'#00f2fe', // 青色
'#43e97b', // 薄荷绿
'#38f9d7', // 青绿
'#fa709a', // 粉红
'#fee140', // 金黄
'#30cfd0', // 青蓝
'#a8edea', // 浅青
'#ff6a00', // 橙色
'#ee0979', // 玫红
'#a770ef', // 紫色
'#fda085' // 橘粉
];
// 确定背景颜色:优先使用自定义颜色,否则根据文本计算
let backgroundColor;
if (customColor) {
backgroundColor = customColor;
} else {
// 根据文本内容计算颜色索引
let hash = 0;
for (let i = 0; i < displayText.length; i++) {
hash = displayText.charCodeAt(i) + ((hash << 5) - hash);
}
const colorIndex = Math.abs(hash) % colors.length;
backgroundColor = colors[colorIndex];
}
// 使用文本和颜色生成唯一 hash(用于 SVG gradient ID)
let hash = 0;
const hashText = displayText + backgroundColor;
for (let i = 0; i < hashText.length; i++) {
hash = hashText.charCodeAt(i) + ((hash << 5) - hash);
}
hash = Math.abs(hash);
// 根据字符数调整字体大小
let fontSize;
if (displayText.length === 1) {
fontSize = '32';
} else if (displayText.length === 2) {
fontSize = '24';
} else {
fontSize = '20'; // 3个字符使用更小的字体
}
// 生成SVG
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
<defs>
<linearGradient id="grad${hash}" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:${backgroundColor};stop-opacity:1" />
<stop offset="100%" style="stop-color:${backgroundColor};stop-opacity:0.8" />
</linearGradient>
</defs>
<rect width="64" height="64" rx="12" fill="url(#grad${hash})"/>
<text x="50%" y="50%" dominant-baseline="central" text-anchor="middle"
font-family="Arial, -apple-system, BlinkMacSystemFont, sans-serif"
font-size="${fontSize}" font-weight="bold" fill="white">
${displayText}
</text>
</svg>`;
// 转换为 Base64
try {
return `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(svg)))}`;
} catch (error) {
Logger.error('Generate text icon error:', error);
return null;
}
},
// 获取文字图标可用颜色列表
getTextIconColors() {
return [
'#667eea', // 蓝紫
'#764ba2', // 深紫
'#f093fb', // 粉紫
'#4facfe', // 天蓝
'#00f2fe', // 青色
'#43e97b', // 薄荷绿
'#38f9d7', // 青绿
'#fa709a', // 粉红
'#fee140', // 金黄
'#30cfd0', // 青蓝
'#a8edea', // 浅青
'#ff6a00', // 橙色
'#ee0979', // 玫红
'#a770ef', // 紫色
'#fda085' // 橘粉
];
},
// 解析文字图标(从 SVG base64 中提取文字和颜色)
parseTextIcon(iconData) {
if (!iconData || !iconData.startsWith('data:image/svg+xml;base64,')) {
return null;
}
try {
// 解码 base64
const base64Data = iconData.replace('data:image/svg+xml;base64,', '');
const svgXml = decodeURIComponent(escape(atob(base64Data)));
// 解析 SVG
const parser = new DOMParser();
const svgDoc = parser.parseFromString(svgXml, 'image/svg+xml');
// 提取文字内容
const textElement = svgDoc.querySelector('text');
if (!textElement) return null;
const text = textElement.textContent.trim();
if (!text) return null;
// 提取颜色(从第一个 stop 元素)
const firstStop = svgDoc.querySelector('stop');
let color = null;
if (firstStop) {
const stopColor = firstStop.getAttribute('style');
if (stopColor) {
// 匹配 stop-color: 后面的颜色值(可能是 #hex 或 rgb/rgba 格式)
const match = stopColor.match(/stop-color:\s*([^;]+)/);
if (match) {
color = match[1].trim();
// 移除可能的引号
color = color.replace(/['"]/g, '');
}
}
}
return {
text: text,
color: color
};
} catch (error) {
Logger.error('Parse text icon error:', error);
return null;
}
},
// 验证 URL
validateUrl(url) {
return normalizeShortcutUrl(url);
},
// 安全获取元素
getElement(id) {
return document.getElementById(id);
},
// 生成唯一 ID
generateId() {
return `id_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
},
// 🔑 新增:确保快捷方式有唯一 ID
ensureShortcutId(shortcut) {
if (!shortcut._id) {
shortcut._id = Utils.generateId();
}
return shortcut._id;
},
// 🔑 新增:确保分组内的项目也有唯一 ID
ensureShortcutIds(shortcuts) {
shortcuts.forEach(shortcut => {
Utils.ensureShortcutId(shortcut);
if (shortcut.type === 'folder' && shortcut.items) {
shortcut.items.forEach(item => Utils.ensureShortcutId(item));
}
});
},
// 获取下一个分组名称
getNextFolderName() {
let maxNum = 0;
State.shortcuts.forEach(shortcut => {
if (shortcut.type === 'folder') {
const match = shortcut.name.match(/^组(\d+)$/);
if (match) {
const num = parseInt(match[1]);
if (num > maxNum) maxNum = num;
}
}
});
return `组${maxNum + 1}`;
},
// 显示撤回提示(支持多个提示,最多3个)
showUndoToast(message, onUndo) {
// 初始化撤回提示数组(如果不存在)
if (!window.undoToasts) {
window.undoToasts = [];
}
// 如果已经有3个提示,移除最旧的(数组末尾的)
if (window.undoToasts.length >= 3) {
const oldestToast = window.undoToasts.pop(); // 🔑 从末尾移除
if (oldestToast.element && oldestToast.element.parentNode) {
oldestToast.element.remove();
}
if (oldestToast.timeout) {
clearTimeout(oldestToast.timeout);
}
if (oldestToast.interval) {
clearInterval(oldestToast.interval);
}
}
// 创建新的撤回提示元素
const toast = document.createElement('div');
toast.className = 'undo-toast';
const messageEl = document.createElement('span');
messageEl.className = 'undo-message';
const undoBtn = document.createElement('button');
undoBtn.className = 'undo-btn';
undoBtn.textContent = '撤回';
toast.appendChild(messageEl);
toast.appendChild(undoBtn);
document.body.appendChild(toast);
// 🔑 关键:新提示始终在最上面(top: 20px)
toast.style.top = '20px';
// 将现有的提示向下移动
window.undoToasts.forEach((toastItem, idx) => {
if (toastItem.element && toastItem.element.parentNode) {
toastItem.element.style.top = `${20 + (idx + 1) * 76}px`;
}
});
// 使用 setTimeout 确保 DOM 更新后再添加 show 类
setTimeout(() => {
toast.classList.add('show');
}, 10);
// 倒计时
const baseMessage = message;
let countdown = 5;
messageEl.textContent = `${baseMessage} (${countdown}s)`;
// ✅ 使用 cleanupManager 管理定时器
const countdownInterval = cleanupManager.setInterval(() => {
countdown--;
if (countdown > 0) {
messageEl.textContent = `${baseMessage} (${countdown}s)`;
} else {
cleanupManager.clearTimer(countdownInterval);
}
}, 1000);
// 移除提示的函数
const removeToast = () => {
toast.classList.remove('show');
setTimeout(() => {
if (toast.parentNode) {
toast.remove();
}
// 从数组中移除
const index = window.undoToasts.findIndex(t => t.element === toast);
if (index !== -1) {
window.undoToasts.splice(index, 1);
}
// 重新调整剩余提示的位置
window.undoToasts.forEach((toastItem, idx) => {
if (toastItem.element && toastItem.element.parentNode) {
toastItem.element.style.top = `${20 + idx * 76}px`;
}
});
}, 300); // 等待动画完成
// ✅ 清除定时器
if (toastData.timeout) {
cleanupManager.clearTimer(toastData.timeout);
}
if (toastData.interval) {
cleanupManager.clearTimer(toastData.interval);
}
};
// 撤回按钮事件
undoBtn.addEventListener('click', () => {
onUndo();
removeToast();
});
// ✅ 5秒后自动隐藏 - 使用 cleanupManager
const timeout = cleanupManager.setTimeout(() => {
removeToast();
}, 5000);
// 保存提示数据
const toastData = {
element: toast,
timeout: timeout,
interval: countdownInterval
};
// 🔑 关键:新提示插入到数组开头,这样索引0永远是最新的
window.undoToasts.unshift(toastData);
}
};
// ==================== 存储管理 ====================
const Storage = {
async get(keys) {
try {
return await chrome.storage.local.get(keys);
} catch (error) {
Logger.error('Storage get error:', error);
return {};
}
},
async set(data) {
try {
await chrome.storage.local.set(data);
return true;
} catch (error) {
Logger.error('Storage set error:', error);
return false;
}
},
// 加载标签页数据
async loadTabs() {
const result = await this.get(['tabs']);
if (result.tabs && result.tabs.length > 0) {
// ✅ 校验并清理数据
const validTabs = Validator.sanitizeTabs(result.tabs);
// 🔑 关键修复:确保所有快捷方式都有唯一 ID
validTabs.forEach(tab => {
if (tab.shortcuts) {
Utils.ensureShortcutIds(tab.shortcuts);
}
});
if (validTabs.length > 0) {
State.tabs = validTabs;
// 始终切换到第一个标签页,不记住上次打开的标签页
State.currentTabId = State.tabs[0].id;
} else {
Logger.warn('所有标签页数据无效,初始化默认标签页');
// 如果所有数据都无效,初始化默认标签页
await this.initDefaultTab();
}
} else {
await this.initDefaultTab();
}
return State.tabs;
},
// ✅ 初始化默认标签页
async initDefaultTab() {
const defaultTab = {
id: Utils.generateId(),
name: '页1',
shortcuts: CONFIG.defaultShortcuts.map(s => ({
...s,
icon: s.icon || Utils.getFaviconUrl(s.url)
}))
};
State.tabs = [defaultTab];
State.currentTabId = defaultTab.id;
await this.saveTabs();
},
// 保存标签页数据
async saveTabs() {
// 🔑 关键修复:添加调试日志,确认保存的数据
Logger.debug('Saving tabs:', State.tabs.length, 'tabs');
State.tabs.forEach((tab, index) => {
Logger.debug(`Tab ${index}: ${tab.name}, shortcuts: ${tab.shortcuts?.length || 0}`);
});
const result = await this.set({
tabs: State.tabs,
currentTabId: State.currentTabId
});
if (result) {
Logger.debug('Tabs saved successfully');
} else {
Logger.error('Failed to save tabs');
}
return result;
},
// 保存快捷方式到当前标签页
async saveShortcuts() {
const currentTab = State.tabs.find(t => t.id === State.currentTabId);
if (currentTab) {
// 🔑 关键修复:确保保存的是 State.shortcuts 的深拷贝,避免引用问题
currentTab.shortcuts = JSON.parse(JSON.stringify(State.shortcuts));
Logger.debug('Saving shortcuts to tab:', currentTab.name, 'count:', currentTab.shortcuts.length);
return await this.saveTabs();
}
Logger.warn('Current tab not found, cannot save shortcuts');
return false;
},
// 加载设置
async loadSettings() {
const result = await this.get(['background', 'searchEngine', 'searchOpacity', 'autoHideControls', 'customEngineUrl', 'gridColumns']);
return {
background: result.background || null,
searchEngine: result.searchEngine || CONFIG.defaultSettings.searchEngine,
searchOpacity: result.searchOpacity !== undefined ? result.searchOpacity : CONFIG.defaultSettings.searchOpacity,
autoHideControls: result.autoHideControls !== undefined ? result.autoHideControls : CONFIG.defaultSettings.autoHideControls,
customEngineUrl: result.customEngineUrl || '',
gridColumns: result.gridColumns !== undefined ? result.gridColumns : 12
};
}
};
// ==================== 图标缓存管理 ====================
const IconCacheManager = {
inFlight: new Map(),
attemptMap: new Map(),
queue: [],
activeCount: 0,
maxConcurrent: 3,
saveTimer: null,
isConvertingAll: false,
statsCache: null,
statsCacheTime: 0,
preloadImages: new Set(),
isImageUrl(url) {
return typeof url === 'string' && url.length > 0;
},
shouldAttempt(shortcut, iconUrl) {
const id = Utils.ensureShortcutId(shortcut);
const key = iconUrl || '';
const lastKey = this.attemptMap.get(id);
if (lastKey === key) return false;
this.attemptMap.set(id, key);
return true;
},
scheduleSave() {
if (this.saveTimer) return;
this.saveTimer = cleanupManager.setTimeout(() => {
this.saveTimer = null;
Storage.saveTabs();
}, 800);
},
async fetchAsDataUrl(url) {
if (!this.isImageUrl(url) || Utils.isDataIcon(url)) return url;
if (this.inFlight.has(url)) {
return this.inFlight.get(url);
}
const promise = (async () => {
try {
const response = await fetch(url, { credentials: 'omit' });
if (!response.ok) return null;
const blob = await response.blob();
if (!blob || !blob.type || !blob.type.startsWith('image/')) {
return null;
}
return await new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => {
resolve(typeof reader.result === 'string' ? reader.result : null);
};
reader.onerror = () => resolve(null);
reader.readAsDataURL(blob);
});
} catch (error) {
Logger.warn('Fetch icon failed:', url, error);
return null;
}
})();
this.inFlight.set(url, promise);
try {
return await promise;
} finally {
this.inFlight.delete(url);
}
},
async cacheIconForShortcut(shortcut, iconUrl) {
if (!shortcut || !this.isImageUrl(iconUrl)) return;
if (iconUrl === Utils.getDefaultIconData()) return;
if (Utils.isDataIcon(shortcut.icon)) return;
if (!this.shouldAttempt(shortcut, iconUrl)) return;
const dataUrl = await this.fetchAsDataUrl(iconUrl);
if (!dataUrl || !Utils.isDataIcon(dataUrl)) return;
if (Utils.isDataIcon(shortcut.icon)) return;
shortcut.icon = dataUrl;
this.scheduleSave();
},
enqueue(task) {
this.queue.push(task);
this.runQueue();
},
runQueue() {
while (this.activeCount < this.maxConcurrent && this.queue.length > 0) {
const task = this.queue.shift();
this.activeCount += 1;
task().finally(() => {
this.activeCount -= 1;
if (this.activeCount === 0 && this.queue.length === 0) {
this.isConvertingAll = false;
}
this.runQueue();
});
}
},
preloadIconForItem(item) {
if (!item || Utils.isDataIcon(item.icon)) return;
const urls = [];
if (this.isImageUrl(item.icon)) {
urls.push(item.icon);
}
const faviconUrl = Utils.getFaviconUrl(item.url);
if (this.isImageUrl(faviconUrl)) {
urls.push(faviconUrl);
}
const googleUrl = Utils.getGoogleFaviconUrl(item.url);
if (this.isImageUrl(googleUrl)) {
urls.push(googleUrl);
}
if (urls.length === 0) return;
const img = new Image();
this.preloadImages.add(img);
let timeoutId = null;
const cleanup = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
this.preloadImages.delete(img);
};
const tryLoad = (index) => {
if (index >= urls.length) {
cleanup();
return;
}
const url = urls[index];
img.onload = () => {
if (img.naturalWidth > 1 && img.naturalHeight > 1) {
this.cacheIconForShortcut(item, img.currentSrc || img.src);
cleanup();
return;
}
tryLoad(index + 1);
};
img.onerror = () => {
tryLoad(index + 1);
};
img.src = url;
};
timeoutId = setTimeout(() => {
cleanup();
}, 7000);
tryLoad(0);
},
preloadAllShortcutIcons(tabs) {
if (!Array.isArray(tabs)) return;
tabs.forEach(tab => {
(tab.shortcuts || []).forEach(shortcut => {
if (shortcut.type === 'folder') {
if (Array.isArray(shortcut.items)) {
shortcut.items.forEach(item => this.preloadIconForItem(item));
}
return;
}
this.preloadIconForItem(shortcut);
});
});
},
async getDataIconStats() {
const now = Date.now();
if (this.statsCache && (now - this.statsCacheTime) < 3000) {
return this.statsCache;
}
const result = await Storage.get(['tabs']);
const tabs = result.tabs || [];
let dataIconCount = 0;
let nonDataIconCount = 0;
let totalChars = 0;
const collect = (icon) => {
if (!icon) return;