Repository navigation
Expand file tree
/
Copy pathnav.js
More file actions
1102 lines (976 loc) · 43.5 KB
/
Copy pathnav.js
File metadata and controls
1102 lines (976 loc) · 43.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
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
(() => {
'use strict';
// ===================== 工具函数 =====================
const $ = (id) => document.getElementById(id);
function escapeHtml(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
}[c]));
}
function domainOf(url) {
if (!url) return '';
try { return new URL(url).hostname.replace(/^www\./, ''); } catch { return ''; }
}
function avatarClass(text) {
let code = 0;
for (let i = 0; i < (text || '').length; i++) code = (code * 31 + text.charCodeAt(i)) | 0;
return 'c' + ((Math.abs(code) % 6) + 1);
}
function countBookmarks(node) {
if (!node) return 0;
if (node.url) return 1;
return (node.children || []).reduce((s, c) => s + countBookmarks(c), 0);
}
function countFolders(node) {
if (!node || !node.children) return 0;
let n = 0;
for (const c of node.children) { if (c.children) { if (countBookmarks(c) > 0) n++; n += countFolders(c); } }
return n;
}
const FOLDER_SVG =
'<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>';
function domainInitial(url) {
const d = domainOf(url);
return d ? d.charAt(0).toUpperCase() : '?';
}
function markKeyword(text, keyword) {
if (!keyword) return escapeHtml(text);
const escaped = escapeHtml(text);
const idx = escaped.toLowerCase().indexOf(keyword.toLowerCase());
if (idx === -1) return escaped;
return escaped.slice(0, idx)
+ '<mark class="mark">' + escaped.slice(idx, idx + keyword.length) + '</mark>'
+ escaped.slice(idx + keyword.length);
}
// ===================== 数据加载 =====================
let rootNode = null;
async function loadBookmarks() {
const tree = await chrome.bookmarks.getTree();
rootNode = tree[0];
await getFoldState().catch(() => {});
renderAll();
}
// ===================== 渲染 =====================
function cardHtml(item, query) {
const cls = avatarClass(item.title);
const secondLine = item.path ? item.path : domainOf(item.url);
const titleHtml = query ? markKeyword(item.title, query) : escapeHtml(item.title);
const domainHtml = query ? markKeyword(secondLine, query) : escapeHtml(secondLine);
<
8000
div id="LC73" class="react-file-line html-div" data-testid="code-cell" data-line-number="73" style="position:relative"> const host = domainOf(item.url);
const iconImg = host
? '<img class="nav-favicon-img" data-host="' + escapeHtml(host) + '" alt="" referrerpolicy="no-referrer" />'
: '';
return (
'<div class="nav-card" data-id="' + escapeHtml(item.id) + '" data-url="' + escapeHtml(item.url) + '" title="' + escapeHtml(item.title) + '\n' + escapeHtml(secondLine) + '">' +
'<span class="nav-status-dot" hidden></span>' +
'<span class="nav-card-icon">' +
'<span class="nav-favicon-placeholder ' + cls + '">' + escapeHtml(domainInitial(item.url)) + '</span>' +
iconImg +
'</span>' +
'<span class="nav-card-info">' +
'<span class="nav-card-title">' + titleHtml + '</span>' +
'<span class="nav-card-domain">' + domainHtml + '</span>' +
'</span>' +
'<span class="nav-card-actions">' +
'<button class="nav-card-btn nav-edit" data-action="edit" title="编辑">'
+ '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z"/></svg>'
+ '</button>'
+ '<button class="nav-card-btn nav-del" data-action="delete" title="删除">'
+ '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>'
+ '</button>' +
'</span>' +
'</div>'
);
}
// 折叠状态:以「标题 + 层级」作为 key 持久化到 storage,避免同名文件夹冲突
const FOLD_KEY = 'folderFoldState';
let foldState = null;
async function getFoldState() {
if (foldState) return foldState;
const r = await chrome.storage.local.get(FOLD_KEY);
foldState = r[FOLD_KEY] || {};
return foldState;
}
function foldStorageKey(node, depth) {
return depth + ':' + (node.title || '未命名文件夹');
}
// 展示方式:图标磁贴(默认)/ 卡片列表,持久化到 storage
const VIEW_KEY = 'navViewMode';
function applyViewMode(mode) {
const isCard = mode === 'card';
document.body.classList.toggle('view-tile', !isCard);
document.querySelectorAll('.nav-view-btn').forEach(btn => {
btn.classList.toggle('is-active', btn.dataset.view === (isCard ? 'card' : 'tile'));
});
}
async function restoreViewMode() {
try {
const r = await chrome.storage.local.get(VIEW_KEY);
applyViewMode(r[VIEW_KEY] === 'card' ? 'card' : 'tile');
} catch { applyViewMode('tile'); }
}
function renderFolderHtml(node, depth, query) {
const direct = (node.children || []).filter(c => c.url);
const subs = (node.children || []).filter(c => c.children && countBookmarks(c) > 0);
const total = countBookmarks(node);
if (total === 0) return '';
const key = foldStorageKey(node, depth);
const folded = foldState && foldState[key] === true;
let html = '<section class="nav-group' + (depth > 0 ? ' nav-group-sub' : '') + (folded ? ' nav-group-folded' : '') + '" data-fold-key="' + escapeHtml(key) + '">';
html += '<div class="nav-group-head" data-fold-toggle data-folder-id="' + escapeHtml(node.id) + '">'
+ '<svg class="nav-group-arrow" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 6 15 12 9 18"/></svg>'
+ '<span class="nav-group-icon">' + FOLDER_SVG + '</span>'
+ '<span class="nav-group-title">' + escapeHtml(node.title || '未命名文件夹') + '</span>'
+ '<span class="nav-group-count">' + total + ' 项</span>'
+ '<span class="nav-group-actions">'
+ '<button class="nav-group-btn" data-action="add-here" title="在此文件夹新建书签"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg></button>'
+ '<button class="nav-group-btn" data-action="add-sub" title="新建子文件夹"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/><line x1="12" y1="11" x2="12" y2="17"/><line x1="9" y1="14" x2="15" y2="14"/></svg></button>'
+ '<button class="nav-group-btn" data-action="rename" title="重命名文件夹"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z"/></svg></button>'
+ '<button class="nav-group-btn nav-group-btn-del" data-action="delete" title="删除文件夹"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg></button>'
+ '</span>'
+ '</div>';
html += '<div class="nav-group-body">';
if (direct.length) html += '<div class="nav-grid">' + direct.map(i => cardHtml(i, query)).join('') + '</div>';
for (const sub of subs) html += renderFolderHtml(sub, depth + 1, query);
html += '</div>';
html += '</section>';
return html;
}
// 全部折叠 / 全部展开:遍历所有目录,切换折叠态并同步持久化
async function setAllFolded(fold) {
const state = await getFoldState();
const groups = document.querySelectorAll('.nav-group');
groups.forEach(g => {
const key = g.dataset.foldKey;
if (key) state[key] = fold;
g.classList.toggle('nav-group-folded', fold);
});
chrome.storage.local.set({ [FOLD_KEY]: state });
updateCollapseToggle();
}
// 切换按钮:根据当前是否为「全展开」决定下一次动作
function toggleAllFolded() {
const groups = document.querySelectorAll('.nav-group');
const allFolded = groups.length > 0 && [...groups].every(g => g.classList.contains('nav-group-folded'));
setAllFolded(!allFolded);
}
// 刷新切换按钮的图标 / 文字 / 标题,反映当前整体状态
function updateCollapseToggle() {
const groups = document.querySelectorAll('.nav-group');
const allExpanded = groups.length > 0 && [...groups].every(g => !g.classList.contains('nav-group-folded'));
const btn = $('collapseToggleBtn');
const ico = $('collapseToggleIco');
const txt = $('collapseToggleText');
if (!btn || !ico || !txt) return;
if (allExpanded) {
ico.innerHTML = '<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"/><polyline points="9 13 12 16 15 13"/>';
txt.textContent = '全部折叠';
btn.title = '全部折叠';
btn.classList.remove('is-expand');
} else {
ico.innerHTML = '<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"/><polyline points="11 9 14 12 11 15"/>';
txt.textContent = '全部展开';
btn.title = '全部展开';
btn.classList.add('is-expand');
}
}
// ===================== 检查链接在线状态 =====================
const ONLINE_CACHE_KEY = 'onlineCache';
let >
async function getOnlineCache() {
if (onlineCache) return onlineCache;
const r = await chrome.storage.local.get(ONLINE_CACHE_KEY);
|| {};
return onlineCache;
}
async function saveOnlineCache(url, ok) {
const cache = await getOnlineCache();
cache[url] = ok ? 1 : 0;
const keys = Object.keys(cache);
if (keys.length > 2000) delete cache[keys[0]];
chrome.storage.local.set({ [ONLINE_CACHE_KEY]: cache });
}
function checkUrlOnline(url) {
return new Promise(resolve => {
if (!url) { resolve(false); return; }
let done = false;
const finish = (ok) => { if (!done) { done = true; resolve(ok); } };
const timer = setTimeout(() => finish(false), 8000);
fetch(url, { method: 'GET', mode: 'no-cors', cache: 'no-store' })
.then(() => { clearTimeout(timer); finish(true); })
.catch(() => { clearTimeout(timer); finish(false); });
});
}
async function applyOnlineCache() {
const cache = await getOnlineCache();
document.querySelectorAll('.nav-card[data-url]').forEach(card => {
const v = cache[card.dataset.url];
if (v === undefined) return;
const dot = card.querySelector('.nav-status-dot');
if (!dot) return;
dot.className = 'nav-status-dot ' + (v ? 'online' : 'offline');
dot.hidden = false;
});
}
async function checkAllOnline() {
const btn = $('checkBtn');
if (btn.disabled) return;
const cards = Array.from(document.querySelectorAll('.nav-card[data-url]'));
if (!cards.length) { toast('没有可检查的链接'); return; }
btn.disabled = true;
const originalHtml = btn.innerHTML;
btn.innerHTML = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="nav-spin-icon"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg> 检查中…';
let offline = 0;
for (const card of cards) {
const url = card.dataset.url;
const dot = card.querySelector('.nav-status-dot');
const ok = await checkUrlOnline(url);
await saveOnlineCache(url, ok);
if (ok) { online++; if (dot) { dot.className = 'nav-status-dot online'; dot.hidden = false; } }
else { offline++; if (dot) { dot.className = 'nav-status-dot offline'; dot.hidden = false; } }
}
btn.disabled = false;
btn.innerHTML = originalHtml;
toast('检查完成:' + online + ' 个在线,' + offline + ' 个离线');
}
// ===================== 导出书签 =====================
function exportBookmarks() {
if (!rootNode) { toast('书签尚未加载'); return; }
const data = {
version: 1,
timestamp: Date.now(),
exportedAt: new Date().toISOString(),
tree: rootNode
};
const json = JSON.stringify(data, null, 2);
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
const dateStr = new Date().toISOString().slice(0, 10);
a.href = url;
a.download = 'minimark-bookmarks-' + dateStr + '.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 1000);
toast('书签已导出');
}
// ===================== 导入书签 =====================
async function importNodes(nodes, parentId) {
for (const node of nodes) {
if (node.url) {
await chrome.bookmarks.create({ parentId, title: node.title || node.url, url: node.url });
} else if (node.children) {
const folder = await chrome.bookmarks.create({ parentId, title: node.title || '导入的文件夹' });
await importNodes(node.children, folder.id);
}
}
}
async function importBookmarks(e) {
const file = e.target.files && e.target.files[0];
e.target.value = '';
if (!file) return;
let parsed;
try {
const text = await file.text();
parsed = JSON.parse(text);
} catch (err) {
toast('文件解析失败:不是有效的 JSON');
return;
}
let nodes;
if (parsed && parsed.tree) nodes = parsed.tree.children;
else if (Array.isArray(parsed)) nodes = parsed;
else if (parsed && parsed.children) nodes = parsed.children;
else { toast('文件格式不正确'); return; }
if (!nodes || !nodes.length) { toast('文件中没有书签'); return; }
try {
// Chrome 根节点(id "0")不允许直接创建子项(否则报
// "Can't modify the root bookmark folders"),顶层只有三个固定文件夹。
// 本扩展导出的文件顶层正是这三个固定文件夹:对号入座还原到同名真实
// 文件夹(id "1"/"2"/"3" 即真实固定文件夹),不产生多余层级;
// 其余格式的内容统一导入书签栏(id "1")。
const PERMANENT = { '1': '书签栏', '2': '其他书签', '3': '移动设备书签' };
const isFullExport = Array.isArray(nodes) && nodes.length > 0 &&
nodes.every(n => n && n.children && PERMANENT[String(n.id)]);
if (isFullExport) {
let total = 0;
for (const n of nodes) {
const items = n.children || [];
total += items.length;
await importNodes(items, String(n.id));
}
toast('导入成功,共 ' + total + ' 项');
} else {
await importNodes(nodes, '1');
toast('导入成功,共 ' + nodes.length + ' 项');
}
await loadBookmarks();
} catch (err) {
console.error(err);
toast('导入失败:' + (err.message || err));
}
}
function renderAll(query) {
if (!rootNode || !rootNode.children || !rootNode.children.length) { renderStats(); return; }
const loose = [];
let html = '';
for (const ch of rootNode.children) {
if (ch.url) loose.push(ch);
else if (ch.children) html += renderFolderHtml(ch, 0, query);
}
if (loose.length) html += renderFolderHtml({ id: rootNode.id, title: '未分类', children: loose }, 0, query);
$('navEmpty').hidden = true;
$('navMain').innerHTML = html;
loadFavicons().catch(() => {});
applyOnlineCache().catch(() => {});
renderStats();
updateCollapseToggle();
}
// ===================== 图标缓存 =====================
const FAVICON_CACHE_KEY = 'faviconCache';
let faviconCache = null;
async function getFaviconCache() {
if (faviconCache) return faviconCache;
const r = await chrome.storage.local.get(FAVICON_CACHE_KEY);
faviconCache = r[FAVICON_CACHE_KEY] || {};
return faviconCache;
}
async function setFaviconCache(host, value) {
const cache = await getFaviconCache();
cache[host] = value;
const keys = Object.keys(cache);
if (keys.length > 500) { delete cache[keys[0]]; }
chrome.storage.local.set({ [FAVICON_CACHE_KEY]: cache });
}
async function loadFavicons() {
const imgs = document.querySelectorAll('.nav-favicon-img[data-host]');
if (!imgs.length) return;
const cache = await getFaviconCache();
for (const img of imgs) {
const host = img.dataset.host;
delete img.dataset.host;
if (!host) continue;
const cached = cache[host];
if (cached === false) { img.remove(); continue; }
if (cached && cached !== true) {
img.src = cached;
img.style.display = 'block';
img.previousElementSibling.style.display = 'none';
continue;
}
const url = 'https://0x3.com/icon?host=' + encodeURIComponent(host);
let resolved = false;
const timer = setTimeout(() => onDone(false), 5000);
function onDone(ok) {
if (resolved) return;
resolved = true;
clearTimeout(timer);
if (ok) {
img.style.display = 'block';
img.previousElementSibling.style.display = 'none';
setFaviconCache(host, true);
} else {
img.remove();
setFaviconCache(host, false);
}
}
img. => onDone(true);
img. => onDone(false);
img.src = url;
}
}
function renderStats() {
if (!rootNode) return;
$('statTotal').textContent = countBookmarks(rootNode).toLocaleString();
$('statFolders').textContent = countFolders(rootNode).toLocaleString();
$('navStats').hidden = false;
}
// ===================== 时钟与问候语 =====================
const WEEK_CN = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
function greetingOf(hour) {
if (hour >= 5 && hour < 11) return '早上好';
if (hour >= 11 && hour < 13) return '中午好';
if (hour >= 13 && hour < 18) return '下午好';
if (hour >= 18 && hour < 23) return '晚上好';
return '夜深了';
}
function updateClock() {
const now = new Date();
const time = $('clockTime');
const greet = $('clockGreet');
if (!time || !greet) return;
time.textContent = String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0');
greet.textContent = greetingOf(now.getHours()) + ' · ' + (now.getMonth() + 1) + '月' + now.getDate() + '日 ' + WEEK_CN[now.getDay()];
}
// 先对齐到整分再按分钟轮询,避免 setInterval 长期漂移
function startClock() {
updateClock();
const now = new Date();
const delay = (60 - now.getSeconds()) * 1000 - now.getMilliseconds() + 50;
setTimeout(() => {
updateClock();
setInterval(updateClock, 60000);
}, delay);
}
// ===================== 搜索 =====================
function flattenWithPath(node, path, out) {
if (!node) return;
if (node.url) { out.push({ id: node.id, title: node.title || domainOf(node.url), url: node.url, path: path.join(' / ') }); return; }
if (!node.children) return;
for (const ch of node.children) {
if (ch.children) flattenWithPath(ch, path.concat(ch.title || '未命名'), out);
else flattenWithPath(ch, path, out);
}
}
let searchTimer = null;
function doSearch() { clearTimeout(searchTimer); searchTimer = setTimeout(doSearchImpl, 120); }
function doSearchImpl() {
const q = $('searchInput').value.trim();
$('searchClearBtn').hidden = !q;
$('statFilter').hidden = !q;
$('statFilterSep').hidden = !q;
if (!q) { hidePanel(); renderAll(''); renderStats(); return; }
const flat = [];
flattenWithPath(rootNode, [], flat);
const hits = flat.filter(it =>
it.title.toLowerCase().includes(q.toLowerCase()) || it.url.toLowerCase().includes(q.toLowerCase())
);
$('statMatched').textContent = hits.length.toLocaleString();
renderPanel(q, hits);
if (!hits.length) {
$('navMain').innerHTML = '';
$('navEmpty').hidden = false;
$('navEmptyText').textContent = '未找到匹配「' + q + '」的书签';
return;
}
$('navEmpty').hidden = true;
$('navMain').innerHTML =
'<section class="nav-group">'
+ '<div class="nav-group-head"><span class="nav-group-icon">' + FOLDER_SVG + '</span><span class="nav-group-title">搜索结果</span><span class="nav-group-count">' + hits.length + ' 项</span></div>'
+ '<div class="nav-grid">' + hits.map(i => cardHtml(i, q)).join('') + '</div>'
+ '</section>';
loadFavicons().catch(() => {});
applyOnlineCache().catch(() => {});
}
// ===================== 搜索候选(打开网址 / 搜索引擎 / 本地书签) =====================
// 接管新标签页后原生搜索框不再存在,这里补上「回车直达」的能力
const SEARCH_ENGINE_NAME = 'Bing';
const SEARCH_ENGINE_URL = (q) => 'https://www.bing.com/search?q=' + encodeURIComponent(q);
const PANEL_BOOKMARK_LIMIT = 6;
const ICON_LINK = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>';
const ICON_SEARCH = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>';
const ICON_BOOKMARK = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>';
let panelItems = [];
let panelIndex = 0;
let panelQuery = '';
// 判断输入是否像网址:带协议、localhost,或形如 a.b 的域名
function looksLikeUrl(q) {
if (/\s/.test(q)) return false;
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(q)) return true;
if (/^localhost(:\d+)?([/?#].*)?$/i.test(q)) return true;
return /^[\w-]+(\.[\w-]+)+([/?#].*)?$/.test(q);
}
function toUrl(q) {
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(q)) return q;
if (/^localhost(:\d+)?([/?#].*)?$/i.test(q)) return 'http://' + q;
return 'https://' + q;
}
function buildPanelItems(q, hits) {
const items = [];
if (looksLikeUrl(q)) {
items.push({ kind: 'open', url: toUrl(q), title: q, sub: '在浏览器中打开此网址', icon: ICON_LINK, tag: '打开' });
}
items.push({ kind: 'search', url: SEARCH_ENGINE_URL(q), title: q, sub: '用 ' + SEARCH_ENGINE_NAME + ' 搜索', icon: ICON_SEARCH, tag: '搜索' });
if (hits.length) items.push({ kind: 'sep' });
hits.slice(0, PANEL_BOOKMARK_LIMIT).forEach(h => {
items.push({ kind: 'bookmark', url: h.url, title: h.title, sub: h.path || domainOf(h.url), icon: ICON_BOOKMARK, tag: '书签' });
});
return items;
}
function renderPanel(q, hits) {
const panel = $('searchPanel');
if (!panel) return;
if (!q) { hidePanel(); return; }
panelItems = buildPanelItems(q, hits);
panelQuery = q;
panelIndex = 0;
panel.innerHTML = panelItems.map((it, i) => {
if (it.kind === 'sep') return '<div class="nav-search-sep"></div>';
return '<div class="nav-search-item' + (i === 0 ? ' is-active' : '') + '" data-index="' + i + '" role="option">'
+ '<span class="nav-search-item-ico">' + it.icon + '</span>'
+ '<span class="nav-search-item-body">'
+ '<span class="nav-search-item-title">' + escapeHtml(it.title) + '</span>'
+ '<span class="nav-search-item-sub">' + escapeHtml(it.sub) + '</span>'
+ '</span>'
+ '<span class="nav-search-item-kind">' + it.tag + '</span>'
+ '</div>';
}).join('');
panel.hidden = false;
}
function hidePanel() {
const panel = $('searchPanel');
if (panel) panel.hidden = true;
panelItems = [];
panelIndex = 0;
panelQuery = '';
}
function movePanel(delta) {
const selectable = panelItems
.map((it, i) => ({ it, i }))
.filter(o => o.it.kind !== 'sep')
.map(o => o.i);
if (!selectable.length) return;
let pos = selectable.indexOf(panelIndex);
pos = pos === -1 ? 0 : (pos + delta + selectable.length) % selectable.length;
panelIndex = selectable[pos];
const panel = $('searchPanel');
if (!panel) return;
panel.querySelectorAll('.nav-search-item').forEach(el => {
const active = Number(el.dataset.index) === panelIndex;
el.classList.toggle('is-active', active);
if (active) el.scrollIntoView({ block: 'nearest' });
});
}
function runPanelItem(item) {
if (!item || !item.url) return;
hidePanel();
chrome.tabs.create({ url: item.url });
}
// 回车:优先执行面板选中项;面板尚未刷新(输入防抖中)则按网址/关键词直接跳转
function submitSearch() {
const q = $('searchInput').value.trim();
if (!q) return;
const item = panelQuery === q ? panelItems[panelIndex] : null;
if (item && item.kind !== 'sep') { runPanelItem(item); return; }
chrome.tabs.create({ url: looksLikeUrl(q) ? toUrl(q) : SEARCH_ENGINE_URL(q) });
}
function onSearchKeydown(e) {
const open = !$('searchPanel').hidden
&& panelQuery === $('searchInput').value.trim()
&& panelItems.length > 0;
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
if (!open) return;
e.preventDefault();
movePanel(e.key === 'ArrowDown' ? 1 : -1);
return;
}
if (e.key === 'Enter') {
e.preventDefault();
submitSearch();
return;
}
// 面板打开时 Esc 只收起面板,交给 document 的 Esc 继续清空搜索
if (e.key === 'Escape' && open) {
e.preventDefault();
e.stopPropagation();
hidePanel();
}
}
// ===================== 书签增删改(含文件夹) =====================
function collectFolders(node, path, out) {
if (!node || !node.children) return;
for (const ch of node.children) {
if (ch.children) {
out.push({ id: ch.id, title: (path.length ? path.join(' / ') + ' / ' : '') + (ch.title || '未命名') });
collectFolders(ch, path.concat(ch.title || '未命名'), out);
}
}
}
/* mode: 'add-bookmark' | 'edit-bookmark' | 'add-folder' | 'rename-folder' */
let editingId = null;
let currentMode = '';
function openModal(mode, item) {
currentMode = mode;
editingId = (mode === 'edit-bookmark' || mode === 'rename-folder') ? item.id : null;
const isFolderMode = mode === 'add-folder' || mode === 'rename-folder';
const isRename = mode === 'rename-folder';
$('bmModalTitle').textContent =
mode === 'add-bookmark' ? '新建书签' :
mode === 'edit-bookmark' ? '编辑书签' :
mode === 'rename-folder' ? '重命名文件夹' : '新建文件夹';
$('bmDeleteBtn').hidden = mode !== 'edit-bookmark';
$('bmUrl').closest('.nav-field').style.display = isFolderMode ? 'none' : '';
$('bmParent').closest('.nav-field').style.display = isRename ? 'none' : '';
const folders = [{ id: '1', title: '书签栏' }];
if (rootNode && rootNode.children) collectFolders(rootNode, [], folders);
$('bmParent').innerHTML = folders.map(f =>
'<option value="' + escapeHtml(f.id) + '">' + escapeHtml(f.title) + '</option>'
).join('');
if (mode === 'edit-bookmark') {
$('bmTitle').value = item.title || '';
$('bmUrl').value = item.url || '';
const parentId = findParentId(rootNode, item.id);
if (parentId) $('bmParent').value = parentId;
} else if (isRename) {
$('bmTitle').value = item.title || '';
} else {
$('bmTitle').value = '';
$('bmUrl').value = '';
$('bmParent').value = '1';
}
$('bmModal').hidden = false;
setTimeout(() => $('bmTitle').focus(), 50);
}
function closeModal() { $('bmModal').hidden = true; editingId = null; currentMode = ''; }
function findParentId(node, id) {
if (!node || !node.children) return null;
for (const ch of node.children) {
if (ch.id === id) return node.id;
const found = findParentId(ch, id);
if (found) return found;
}
return null;
}
// ===================== 自定义确认弹窗(替代原生 confirm) =====================
let confirmResolve = null;
function confirmDialog(msg) {
return new Promise(resolve => {
confirmResolve = resolve;
$('navConfirmMsg').textContent = msg;
$('navConfirm').hidden = false;
setTimeout(() => $('navConfirmOk').focus(), 50);
});
}
function closeConfirm(ok) {
$('navConfirm').hidden = true;
if (confirmResolve) { const r = confirmResolve; confirmResolve = null; r(ok); }
}
// ===================== 版本快照 =====================
const SNAPSHOT_REASON = {
manual: '手动备份',
'before-download': '下载前自动',
'before-restore': '回滚前自动',
'before-clear': '清空前自动'
};
function fmtSnapTime(ts) {
if (!ts) return '--';
const d = new Date(ts);
const pad = n => (n < 10 ? '0' + n : '' + n);
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
' ' + pad(d.getHours()) + ':' + pad(d.getMinutes());
}
function fmtSnapSize(size) {
if (!size) return '--';
if (size < 1024) return size + ' B';
if (size < 1024 * 1024) return Math.round(size / 1024) + ' KB';
return (size / 1024 / 1024).toFixed(1) + ' MB';
}
async function openSnapshotModal() {
$('snapshotModal').hidden = false;
await renderSnapshotList();
}
function closeSnapshotModal() {
$('snapshotModal').hidden = true;
}
async function renderSnapshotList() {
const box = $('navSnapshotList');
if (!box) return;
box.innerHTML = '<div class="nav-snapshot-empty">正在读取…</div>';
let res;
try {
res = await chrome.runtime.sendMessage({ action: 'listSnapshots' });
} catch (e) {
box.innerHTML = '<div class="nav-snapshot-empty">读取快照失败</div>';
return;
}
const list = (res && res.success && res.snapshots) || [];
$('navSnapshotCount').textContent = list.length ? '共 ' + list.length + ' 份' : '';
if (!list.length) {
box.innerHTML = '<div class="nav-snapshot-empty">暂无快照,点击右下角「立即备份」创建</div>';
return;
}
box.innerHTML = list.map((s, i) => {
const reason = SNAPSHOT_REASON[s.reason] || '备份';
return '<div class="nav-snapshot-item">' +
'<div class="nav-snapshot-main">' +
'<div class="nav-snapshot-title">' +
'<span class="nav-snapshot-badge' + (i === 0 ? ' is-latest' : '') + '">' + escapeHtml(reason) + '</span>' +
'<span class="nav-snapshot-time">' + escapeHtml(fmtSnapTime(s.time)) + '</span>' +
'</div>' +
'<div class="nav-snapshot-meta">' + (s.count || 0) + ' 条书签 · ' + fmtSnapSize(s.size) + '</div>' +
'</div>' +
'<div class="nav-snapshot-actions">' +
'<button class="nav-btn nav-btn-ghost nav-snap-act" data-snap-restore="' + escapeHtml(s.id) + '">回滚</button>' +
'<button class="nav-btn nav-btn-danger nav-snap-act" data-snap-delete="' + escapeHtml(s.id) + '">删除</button>' +
'</div>' +
'</div>';
}).join('');
}
async function createSnapshotFromNav() {
try {
const res = await chrome.runtime.sendMessage({ action: 'createSnapshot' });
if (res && res.success) {
toast('已创建快照,共 ' + (res.count || 0) + ' 条书签');
await renderSnapshotList();
} else {
toast((res && res.error) || '备份失败');
}
} catch (e) {
toast('备份失败:' + (e.message || e));
}
}
async function restoreSnapshotFromNav(id) {
const ok = await confirmDialog('确定回滚到该快照?\n当前本地书签会先自动备份,回滚不会上传到远端。');
if (!ok) return;
try {
const res = await chrome.runtime.sendMessage({ action: 'restoreSnapshot', id });
if (res && res.success) {
toast('已回滚,共 ' + (res.count || 0) + ' 条书签');
closeSnapshotModal();
await loadBookmarks();
} else {
toast((res && res.error) || '回滚失败');
}
} catch (e) {
toast('回滚失败:' + (e.message || e));
}
}
async function deleteSnapshotFromNav(id) {
const ok = await confirmDialog('确定删除该份快照?删除后无法恢复。');
if (!ok) return;
try {
const res = await chrome.runtime.sendMessage({ action: 'deleteSnapshot', id });
if (res && res.success) {
toast('已删除快照');
await renderSnapshotList();
} else {
toast((res && res.error) || '删除失败');
}
} catch (e) {
toast('删除失败:' + (e.message || e));
}
}
// 轻提示
let toastTimer = null;
function toast(msg) {
const el = $('navToast');
el.textContent = msg;
el.hidden = false;
el.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => { el.classList.remove('show'); setTimeout(() => { el.hidden = true; }, 200); }, 2000);
}
async function saveBookmark() {
const title = $('bmTitle').value.trim();
const parentId = $('bmParent').value;
if (currentMode === 'add-folder') {
if (!title) { toast('请输入文件夹名称'); return; }
try {
await chrome.bookmarks.create({ parentId, title });
toast('已创建文件夹');
closeModal();
await loadBookmarks();
} catch (err) { toast('创建失败: ' + (err.message || err)); }
return;
}
if (currentMode === 'rename-folder') {
if (!title) { toast('请输入文件夹名称'); return; }
try {
await chrome.bookmarks.update(editingId, { title });
toast('已重命名');
closeModal();
await loadBookmarks();
} catch (err) { toast('重命名失败: ' + (err.message || err)); }
return;
}
let url = $('bmUrl').value.trim();
if (!url) { toast('请输入网址'); return; }
if (!/^https?:\/\//i.test(url)) url = 'https://' + url;
try {
if (editingId) {
const currentParent = findParentId(rootNode, editingId);
if (parentId && currentParent && String(parentId) !== String(currentParent)) {
await chrome.bookmarks.move(editingId, { parentId });
}
await chrome.bookmarks.update(editingId, { title: title || domainOf(url) || '未命名书签', url });
toast('已更新书签');
} else {
await chrome.bookmarks.create({ parentId, title: title || domainOf(url) || '未命名书签', url });
toast('已新建书签');
}
closeModal();
await loadBookmarks();
} catch (err) { toast('保存失败: ' + (err.message || err)); }
}
async function deleteBookmark(id) {
try {
await chrome.bookmarks.remove(id);
toast('已删除书签');
closeModal();
await loadBookmarks();
} catch (err) { toast('删除失败: ' + (err.message || err)); }
}
async function deleteFolder(id) {
const node = findBookmarkById(rootNode, id);
const name = node ? (node.title || '未命名文件夹') : '该文件夹';
const cnt = node ? countBookmarks(node) : 0;
const ok = await confirmDialog('确定删除文件夹「' + name + '」?\n将一并删除其中的 ' + cnt + ' 个书签。');
if (!ok) return;
try {
await chrome.bookmarks.removeTree(id);
toast('已删除文件夹');
await loadBookmarks();
} catch (err) { toast('删除失败: ' + (err.message || err)); }
}
function findBookmarkById(node, id) {
if (!node) return null;
if (node.id === id) return node;
if (node.children) for (const ch of node.children) { const f = findBookmarkById(ch, id); if (f) return f; }
return null;
}
// ===================== 事件绑定 =====================
function bindEvents() {
// 搜索
$('searchInput').addEventListener('input', doSearch);
$('searchClearBtn').addEventListener('click', () => { $('searchInput').value = ''; doSearch(); $('searchInput').focus(); });
$('searchInput').addEventListener('keydown', onSearchKeydown);
// 展示方式切换
document.querySelectorAll('.nav-view-btn').forEach(btn => {
btn.addEventListener('click', () => {
const mode = btn.dataset.view === 'card' ? 'card' : 'tile';
applyViewMode(mode);
chrome.storage.local.set({ [VIEW_KEY]: mode });
});
});
// 候选面板:用 mousedown 抢在输入框失焦前执行,避免点击被 blur 吞掉
$('searchPanel').addEventListener('mousedown', e => {
const el = e.target.closest('.nav-search-item');
if (!el) return;
e.preventDefault();
runPanelItem(panelItems[Number(el.dataset.index)]);
});
// 点击搜索区以外收起候选面板
document.addEventListener('mousedown', e => {
if (!e.target.closest('.nav-search')) hidePanel();
});
// 刷新
$('refreshBtn').addEventListener('click', () => {
$('navMain').innerHTML = '<div class="nav-loading"><div class="nav-loading-spinner"></div><p>正在加载…</p></div>';
loadBookmarks().catch(showError);
});
// 检查所有链接在线状态
$('checkBtn').addEventListener('click', checkAllOnline);
// 导出/导入
$('exportBtn').addEventListener('click', exportBookmarks);
$('importBtn').addEventListener('click', () => $('importFile').click());
$('importFile').addEventListener('change', importBookmarks);
// 版本快照
$('snapshotBtn').addEventListener('click', openSnapshotModal);
$('snapshotModalClose').addEventListener('click', closeSnapshotModal);
$('snapshotModal').addEventListener('click', e => { if (e.target === $('snapshotModal')) closeSnapshotModal(); });
$('navSnapshotCreateBtn').addEventListener('click', createSnapshotFromNav);
$('navSnapshotList').addEventListener('click', async e => {
const restoreBtn = e.target.closest('[data-snap-restore]');
if (restoreBtn) { await restoreSnapshotFromNav(restoreBtn.dataset.snapRestore); return; }
const deleteBtn = e.target.closest('[data-snap-delete]');
if (deleteBtn) await deleteSnapshotFromNav(deleteBtn.dataset.snapDelete);
});
// 新建书签 / 新建文件夹
$('addBookmarkBtn').addEventListener('click', () => openModal('add-bookmark'));
$('addFolderBtn').addEventListener('click', () => openModal('add-folder'));
// 弹窗操作
$('bmModalClose').addEventListener('click', closeModal);
$('bmCancelBtn').addEventListener('click', closeModal);
$('bmSaveBtn').addEventListener('click', saveBookmark);
$('bmDeleteBtn').addEventListener('click', async () => {
if (editingId && await confirmDialog('确定删除该书签?')) deleteBookmark(editingId);
});
// 确认弹窗按钮
$('navConfirmOk').addEventListener('click', () => closeConfirm(true));
$('navConfirmCancel').addEventListener('click', () => closeConfirm(false));
$('navConfirm').addEventListener('click', e => { if (e.target === $('navConfirm')) closeConfirm(false); });
// 全部折叠 / 展开 切换按钮