-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsidepanel.js
More file actions
1407 lines (1265 loc) · 50.2 KB
/
sidepanel.js
File metadata and controls
1407 lines (1265 loc) · 50.2 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';
// ===== State =====
let items = [];
let doneItems = [];
let snapshots = [];
let workspaces = []; // { id, name, note, items: [...], createdAt }
let archivedSnapshots = []; // { id, date, label, snapshots: [...] }
let tags = [];
let settings = {
autoSnapshot: true,
snapshotInterval: 5,
};
let currentView = 'active';
let searchQuery = '';
let filterTagId = null;
let selectedTagIds = [];
let checkedIds = new Set(); // multi-select for workspace creation
// ===== DOM Refs =====
const viewTabs = document.querySelectorAll('.view-tab');
const noteInput = document.getElementById('note-input');
const pushBtn = document.getElementById('push-btn');
const pushCloseBtn = document.getElementById('push-close-btn');
const popFirstBtn = document.getElementById('pop-first-btn');
const popLastBtn = document.getElementById('pop-last-btn');
const bottomBar = document.getElementById('bottom-bar');
const listArea = document.getElementById('list-area');
const activeCount = document.getElementById('active-count');
const doneCount = document.getElementById('done-count');
const snapshotCount = document.getElementById('snapshot-count');
const workspaceCount = document.getElementById('workspace-count');
const searchInput = document.getElementById('search-input');
const searchClear = document.getElementById('search-clear');
const snapshotBtn = document.getElementById('snapshot-btn');
const settingsBtn = document.getElementById('settings-btn');
const settingsPanel = document.getElementById('settings-panel');
const autoSnapshotToggle = document.getElementById('auto-snapshot-toggle');
const snapshotIntervalSelect = document.getElementById('snapshot-interval');
const snapshotIntervalRow = document.getElementById('snapshot-interval-row');
const newTagInput = document.getElementById('new-tag-input');
const newTagColor = document.getElementById('new-tag-color');
const addTagBtn = document.getElementById('add-tag-btn');
const tagListEl = document.getElementById('tag-list');
const tagFilterEl = document.getElementById('tag-filter');
const inputTagsEl = document.getElementById('input-tags');
const inputPriority = document.getElementById('input-priority');
const pushPosition = document.getElementById('push-position');
const selectionBar = document.getElementById('selection-bar');
const selectionCountEl = document.getElementById('selection-count');
const createWorkspaceBtn = document.getElementById('create-workspace-btn');
const cancelSelectionBtn = document.getElementById('cancel-selection-btn');
const wsDialog = document.getElementById('ws-dialog');
const wsNameInput = document.getElementById('ws-name-input');
const wsNoteInput = document.getElementById('ws-note-input');
const wsConfirmBtn = document.getElementById('ws-confirm-btn');
const wsCancelBtn = document.getElementById('ws-cancel-btn');
const archiveCount = document.getElementById('archive-count');
// ===== Init =====
async function init() {
const data = await chrome.storage.local.get([
'items', 'doneItems', 'snapshots', 'workspaces', 'archivedSnapshots', 'tags', 'settings'
]);
items = data.items || [];
doneItems = data.doneItems || [];
snapshots = data.snapshots || [];
workspaces = data.workspaces || [];
archivedSnapshots = data.archivedSnapshots || [];
tags = data.tags || [];
if (data.settings) settings = { ...settings, ...data.settings };
autoSnapshotToggle.checked = settings.autoSnapshot;
snapshotIntervalSelect.value = settings.snapshotInterval;
snapshotIntervalRow.style.display = settings.autoSnapshot ? '' : 'none';
updateCounts();
renderTags();
renderTagFilter();
renderInputTags();
render();
setupAutoSnapshot();
}
// ===== Storage =====
async function save() {
await chrome.storage.local.set({ items, doneItems, snapshots, workspaces, archivedSnapshots, tags, settings });
updateCounts();
}
function updateCounts() {
activeCount.textContent = items.length;
doneCount.textContent = doneItems.length;
snapshotCount.textContent = snapshots.length;
workspaceCount.textContent = workspaces.length;
archiveCount.textContent = archivedSnapshots.reduce((s, g) => s + g.snapshots.length, 0);
}
// ===== Settings =====
settingsBtn.addEventListener('click', () => {
settingsPanel.style.display = settingsPanel.style.display === 'none' ? '' : 'none';
});
autoSnapshotToggle.addEventListener('change', async () => {
settings.autoSnapshot = autoSnapshotToggle.checked;
snapshotIntervalRow.style.display = settings.autoSnapshot ? '' : 'none';
await save();
setupAutoSnapshot();
});
snapshotIntervalSelect.addEventListener('change', async () => {
settings.snapshotInterval = parseInt(snapshotIntervalSelect.value);
await save();
});
// ===== Tags Management =====
addTagBtn.addEventListener('click', addNewTag);
newTagInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') addNewTag();
});
async function addNewTag() {
const name = newTagInput.value.trim();
if (!name) return;
if (tags.some(t => t.name === name)) return showToast('标签已存在');
tags.push({ id: genId(), name, color: newTagColor.value });
newTagInput.value = '';
await save();
renderTags();
renderTagFilter();
renderInputTags();
}
async function deleteTag(tagId) {
tags = tags.filter(t => t.id !== tagId);
// Remove from items
items.forEach(i => { if (i.tags) i.tags = i.tags.filter(t => t !== tagId); });
doneItems.forEach(i => { if (i.tags) i.tags = i.tags.filter(t => t !== tagId); });
selectedTagIds = selectedTagIds.filter(t => t !== tagId);
if (filterTagId === tagId) filterTagId = null;
await save();
renderTags();
renderTagFilter();
renderInputTags();
render();
}
function renderTags() {
tagListEl.innerHTML = '';
tags.forEach(tag => {
const el = document.createElement('span');
el.className = 'tag';
el.style.background = tag.color + '22';
el.style.color = tag.color;
el.innerHTML = `${escHtml(tag.name)}<span class="tag-remove" data-tag-del="${tag.id}">×</span>`;
tagListEl.appendChild(el);
});
tagListEl.querySelectorAll('[data-tag-del]').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
deleteTag(btn.dataset.tagDel);
});
});
}
function renderTagFilter() {
if (tags.length === 0) {
tagFilterEl.style.display = 'none';
return;
}
tagFilterEl.style.display = '';
tagFilterEl.innerHTML = '<span class="tag-filter-label">筛选:</span>';
const allBtn = document.createElement('span');
allBtn.className = `tag${!filterTagId ? ' active' : ''}`;
allBtn.style.background = 'rgba(255,255,255,0.08)';
allBtn.style.color = 'var(--text-secondary)';
allBtn.textContent = '全部';
allBtn.addEventListener('click', () => { filterTagId = null; renderTagFilter(); render(); });
tagFilterEl.appendChild(allBtn);
tags.forEach(tag => {
const el = document.createElement('span');
el.className = `tag${filterTagId === tag.id ? ' active' : ''}`;
el.style.background = tag.color + '22';
el.style.color = tag.color;
el.textContent = tag.name;
el.addEventListener('click', () => {
filterTagId = filterTagId === tag.id ? null : tag.id;
renderTagFilter();
render();
});
tagFilterEl.appendChild(el);
});
}
function renderInputTags() {
inputTagsEl.innerHTML = '';
if (tags.length === 0) return;
tags.forEach(tag => {
const el = document.createElement('span');
el.className = `tag${selectedTagIds.includes(tag.id) ? ' selected' : ''}`;
el.style.background = selectedTagIds.includes(tag.id) ? tag.color + '33' : tag.color + '11';
el.style.color = tag.color;
el.style.borderColor = selectedTagIds.includes(tag.id) ? tag.color : 'transparent';
el.textContent = tag.name;
el.addEventListener('click', () => {
if (selectedTagIds.includes(tag.id)) {
selectedTagIds = selectedTagIds.filter(t => t !== tag.id);
} else {
selectedTagIds.push(tag.id);
}
renderInputTags();
});
inputTagsEl.appendChild(el);
});
}
function getTagsHtml(tagIds) {
if (!tagIds || tagIds.length === 0) return '';
return tagIds.map(id => {
const tag = tags.find(t => t.id === id);
if (!tag) return '';
return `<span class="tag" style="background:${tag.color}22;color:${tag.color}">${escHtml(tag.name)}</span>`;
}).join('');
}
// ===== View Switching =====
viewTabs.forEach(tab => {
tab.addEventListener('click', () => {
currentView = tab.dataset.view;
viewTabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
render();
});
});
// ===== Search =====
searchInput.addEventListener('input', () => {
searchQuery = searchInput.value.trim().toLowerCase();
searchClear.style.display = searchQuery ? '' : 'none';
render();
});
searchClear.addEventListener('click', () => {
searchInput.value = '';
searchQuery = '';
searchClear.style.display = 'none';
render();
});
// ===== URL Subtitle =====
function getUrlSubtitle(url) {
try {
const u = new URL(url);
let path = u.pathname;
// Remove trailing slash
if (path.endsWith('/') && path.length > 1) path = path.slice(0, -1);
// For root paths, show host only
if (path === '/' || path === '') return u.host;
// Show host + meaningful path
const display = u.host + path;
// Add hash/search if meaningful
const extra = u.hash || (u.search ? u.search.slice(0, 30) : '');
return display + (extra ? extra : '');
} catch {
return url;
}
}
// ===== Extract Page Info via Content Script =====
async function extractPageInfo(tabId) {
try {
const results = await chrome.scripting.executeScript({
target: { tabId },
files: ['content-extract.js'],
});
if (results && results[0] && results[0].result) {
return results[0].result;
}
} catch (e) {
// Can't inject into chrome://, edge://, etc.
}
return null;
}
function buildSmartTitle(tab, pageInfo) {
const baseTitle = tab.title || tab.url;
if (!pageInfo) return { title: baseTitle, pageContext: '' };
// Pick the most descriptive title
const candidates = [
pageInfo.ogTitle,
pageInfo.h1,
pageInfo.h2 || '',
pageInfo.docTitle,
].filter(Boolean);
// Find one that's different and more descriptive than tab.title
let bestTitle = baseTitle;
for (const c of candidates) {
if (c.length > bestTitle.length && c !== baseTitle) {
bestTitle = c;
break;
}
}
// Build context snippet from first content or description
const context = pageInfo.firstContent
|| pageInfo.ogDescription
|| pageInfo.metaDescription
|| '';
return {
title: bestTitle,
pageContext: context.slice(0, 200),
};
}
// ===== Push =====
async function pushCurrentTab(closeAfter = false) {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab) return showToast('无法获取当前标签页');
// Extract page info
const pageInfo = await extractPageInfo(tab.id);
const smart = buildSmartTitle(tab, pageInfo);
const item = {
id: genId(),
url: tab.url,
title: smart.title,
customTitle: '',
pageContext: smart.pageContext,
favicon: tab.favIconUrl || '',
note: noteInput.value.trim(),
tags: [...selectedTagIds],
priority: inputPriority.value || '',
timestamp: Date.now(),
};
const pos = pushPosition.value;
if (pos === 'last') {
items.push(item);
} else {
items.unshift(item);
}
noteInput.value = '';
inputPriority.value = '';
await save();
if (currentView !== 'active') {
currentView = 'active';
viewTabs.forEach(t => t.classList.toggle('active', t.dataset.view === 'active'));
}
render();
if (closeAfter) {
await chrome.tabs.remove(tab.id);
showToast('已推入并关闭标签页');
} else {
showToast('已推入');
}
} catch (e) {
showToast('操作失败: ' + e.message);
}
}
pushBtn.addEventListener('click', () => pushCurrentTab(false));
pushCloseBtn.addEventListener('click', () => pushCurrentTab(true));
// ===== Pop =====
async function popItem(position) {
if (items.length === 0) return;
const item = position === 'first' ? items.shift() : items.pop();
item.completedAt = Date.now();
doneItems.unshift(item);
await save();
render();
await smartNavigate(item.url);
showToast(position === 'first' ? '已弹出首项' : '已弹出末项');
}
popFirstBtn.addEventListener('click', () => popItem('first'));
popLastBtn.addEventListener('click', () => popItem('last'));
async function popSpecificItem(itemId) {
const idx = items.findIndex(i => i.id === itemId);
if (idx === -1) return;
const [item] = items.splice(idx, 1);
item.completedAt = Date.now();
doneItems.unshift(item);
await save();
render();
await smartNavigate(item.url);
showToast('已弹出并跳转');
}
// ===== Restore =====
async function restoreItem(itemId) {
const idx = doneItems.findIndex(i => i.id === itemId);
if (idx === -1) return;
const [item] = doneItems.splice(idx, 1);
delete item.completedAt;
items.unshift(item);
await save();
render();
showToast('已恢复到列表');
}
// ===== Delete =====
async function deleteItem(itemId, fromDone = false) {
if (fromDone) {
doneItems = doneItems.filter(i => i.id !== itemId);
} else {
items = items.filter(i => i.id !== itemId);
}
await save();
render();
}
// ===== Smart Navigate =====
async function smartNavigate(url) {
try {
const allTabs = await chrome.tabs.query({});
const existing = allTabs.find(t => t.url === url);
if (existing) {
await chrome.tabs.update(existing.id, { active: true });
await chrome.windows.update(existing.windowId, { focused: true });
return;
}
} catch {}
chrome.tabs.create({ url });
}
// ===== Edit Note =====
function startEditNote(itemId, fromDone = false) {
const list = fromDone ? doneItems : items;
const item = list.find(i => i.id === itemId);
if (!item) return;
const noteEl = document.querySelector(`[data-note-id="${itemId}"]`);
if (!noteEl) return;
const textarea = document.createElement('textarea');
textarea.className = 'card-note-edit';
textarea.value = item.note;
textarea.rows = 2;
noteEl.replaceWith(textarea);
textarea.focus();
const commit = async () => {
item.note = textarea.value.trim();
await save();
render();
};
textarea.addEventListener('blur', commit);
textarea.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); textarea.blur(); }
if (e.key === 'Escape') render();
});
}
// ===== Edit Title =====
function startEditTitle(itemId, fromDone = false) {
const list = fromDone ? doneItems : items;
const item = list.find(i => i.id === itemId);
if (!item) return;
const titleEl = document.querySelector(`[data-title-id="${itemId}"]`);
if (!titleEl) return;
const input = document.createElement('input');
input.type = 'text';
input.className = 'card-title-edit';
input.value = item.customTitle || item.title;
input.placeholder = item.title;
titleEl.replaceWith(input);
input.focus();
input.select();
const commit = async () => {
const val = input.value.trim();
item.customTitle = (val && val !== item.title) ? val : '';
await save();
render();
};
input.addEventListener('blur', commit);
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') input.blur();
if (e.key === 'Escape') render();
});
}
// ===== Cycle Priority =====
async function cyclePriority(itemId, fromDone = false) {
const list = fromDone ? doneItems : items;
const item = list.find(i => i.id === itemId);
if (!item) return;
const cycle = ['', 'high', 'medium', 'low'];
const idx = cycle.indexOf(item.priority || '');
item.priority = cycle[(idx + 1) % cycle.length];
await save();
render();
}
// ===== Toggle Tag on Item =====
async function toggleItemTag(itemId, tagId, fromDone = false) {
const list = fromDone ? doneItems : items;
const item = list.find(i => i.id === itemId);
if (!item) return;
if (!item.tags) item.tags = [];
if (item.tags.includes(tagId)) {
item.tags = item.tags.filter(t => t !== tagId);
} else {
item.tags.push(tagId);
}
await save();
render();
}
// ===== Drag & Drop =====
let dragSrcIndex = null;
function setupDrag(card, index) {
card.setAttribute('draggable', 'true');
card.addEventListener('dragstart', (e) => {
dragSrcIndex = index;
card.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', index.toString());
});
card.addEventListener('dragend', () => {
card.classList.remove('dragging');
document.querySelectorAll('.drag-over').forEach(el => el.classList.remove('drag-over'));
dragSrcIndex = null;
});
card.addEventListener('dragover', (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
if (dragSrcIndex === null || dragSrcIndex === index) return;
card.classList.add('drag-over');
});
card.addEventListener('dragleave', () => card.classList.remove('drag-over'));
card.addEventListener('drop', async (e) => {
e.preventDefault();
card.classList.remove('drag-over');
const from = dragSrcIndex;
if (from === null || from === index) return;
const [moved] = items.splice(from, 1);
items.splice(index, 0, moved);
await save();
render();
showToast('已调整顺序');
});
}
// ===== Snapshots =====
async function takeSnapshot() {
try {
const allTabs = await chrome.tabs.query({ currentWindow: true });
const snapshot = {
id: genId(),
timestamp: Date.now(),
tabs: allTabs.map(t => ({
url: t.url,
title: t.title || t.url,
favicon: t.favIconUrl || '',
})),
};
snapshots.unshift(snapshot);
if (snapshots.length > 30) snapshots = snapshots.slice(0, 30);
await save();
if (currentView === 'snapshots') render();
else updateCounts();
showToast(`快照已保存 (${snapshot.tabs.length} 个标签页)`);
} catch (e) {
showToast('快照失败: ' + e.message);
}
}
snapshotBtn.addEventListener('click', takeSnapshot);
let autoSnapshotCleanup = null;
function setupAutoSnapshot() {
if (autoSnapshotCleanup) { autoSnapshotCleanup(); autoSnapshotCleanup = null; }
if (!settings.autoSnapshot) return;
let lastAutoSnapshot = 0;
const handler = async (windowId) => {
if (windowId === chrome.windows.WINDOW_ID_NONE) return;
const now = Date.now();
if (now - lastAutoSnapshot < settings.snapshotInterval * 60 * 1000) return;
lastAutoSnapshot = now;
try {
const allTabs = await chrome.tabs.query({ currentWindow: true });
const snapshot = {
id: genId(),
timestamp: now,
auto: true,
tabs: allTabs.map(t => ({
url: t.url,
title: t.title || t.url,
favicon: t.favIconUrl || '',
})),
};
snapshots.unshift(snapshot);
if (snapshots.length > 30) snapshots = snapshots.slice(0, 30);
await save();
} catch {}
};
chrome.windows.onFocusChanged.addListener(handler);
autoSnapshotCleanup = () => chrome.windows.onFocusChanged.removeListener(handler);
}
async function restoreSnapshot(snapshotId) {
const snap = snapshots.find(s => s.id === snapshotId);
if (!snap) return;
for (const t of snap.tabs) {
await smartNavigate(t.url);
}
showToast(`正在恢复 ${snap.tabs.length} 个标签页`);
}
async function deleteSnapshot(snapshotId) {
snapshots = snapshots.filter(s => s.id !== snapshotId);
await save();
render();
}
// ===== Archive Snapshots =====
function fmtDate(ts) {
const d = new Date(ts);
return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}
async function archiveSnapshot(snapshotId) {
const snap = snapshots.find(s => s.id === snapshotId);
if (!snap) return;
snapshots = snapshots.filter(s => s.id !== snapshotId);
const dateKey = fmtDate(snap.timestamp);
let group = archivedSnapshots.find(g => g.date === dateKey);
if (!group) {
group = { id: genId(), date: dateKey, label: dateKey, snapshots: [] };
archivedSnapshots.push(group);
archivedSnapshots.sort((a, b) => b.date.localeCompare(a.date));
}
group.snapshots.unshift(snap);
await save();
render();
showToast(`快照已归档到 ${dateKey}`);
}
async function archiveAllSnapshots() {
if (snapshots.length === 0) return;
for (const snap of snapshots) {
const dateKey = fmtDate(snap.timestamp);
let group = archivedSnapshots.find(g => g.date === dateKey);
if (!group) {
group = { id: genId(), date: dateKey, label: dateKey, snapshots: [] };
archivedSnapshots.push(group);
}
group.snapshots.unshift(snap);
}
archivedSnapshots.sort((a, b) => b.date.localeCompare(a.date));
const count = snapshots.length;
snapshots = [];
await save();
render();
showToast(`已归档 ${count} 条快照`);
}
async function unarchiveSnapshot(groupDate, snapshotId) {
const group = archivedSnapshots.find(g => g.date === groupDate);
if (!group) return;
const idx = group.snapshots.findIndex(s => s.id === snapshotId);
if (idx === -1) return;
const [snap] = group.snapshots.splice(idx, 1);
if (group.snapshots.length === 0) {
archivedSnapshots = archivedSnapshots.filter(g => g.date !== groupDate);
}
snapshots.unshift(snap);
await save();
render();
showToast('已取消归档');
}
async function deleteArchivedSnapshot(groupDate, snapshotId) {
const group = archivedSnapshots.find(g => g.date === groupDate);
if (!group) return;
group.snapshots = group.snapshots.filter(s => s.id !== snapshotId);
if (group.snapshots.length === 0) {
archivedSnapshots = archivedSnapshots.filter(g => g.date !== groupDate);
}
await save();
render();
}
async function deleteArchiveGroup(groupDate) {
archivedSnapshots = archivedSnapshots.filter(g => g.date !== groupDate);
await save();
render();
}
function exportArchive() {
const data = {
exportedAt: new Date().toISOString(),
version: 1,
archivedSnapshots,
snapshots,
};
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `stackue-snapshots-${fmtDate(Date.now())}.json`;
a.click();
URL.revokeObjectURL(url);
showToast('已导出快照');
}
function importArchive() {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
try {
const text = await file.text();
const data = JSON.parse(text);
if (!data.version) throw new Error('无效的文件格式');
let imported = 0;
if (data.archivedSnapshots) {
for (const group of data.archivedSnapshots) {
let existing = archivedSnapshots.find(g => g.date === group.date);
if (!existing) {
existing = { id: genId(), date: group.date, label: group.label || group.date, snapshots: [] };
archivedSnapshots.push(existing);
}
for (const snap of group.snapshots) {
if (!existing.snapshots.some(s => s.id === snap.id)) {
existing.snapshots.push(snap);
imported++;
}
}
}
archivedSnapshots.sort((a, b) => b.date.localeCompare(a.date));
}
if (data.snapshots) {
for (const snap of data.snapshots) {
if (!snapshots.some(s => s.id === snap.id)) {
snapshots.push(snap);
imported++;
}
}
}
await save();
render();
showToast(`已导入 ${imported} 条快照`);
} catch (err) {
showToast('导入失败: ' + err.message);
}
});
input.click();
}
// ===== Selection / Checkbox =====
function updateSelectionBar() {
const count = checkedIds.size;
if (count > 0) {
selectionBar.style.display = '';
selectionCountEl.textContent = `已选 ${count} 项`;
bottomBar.style.display = 'none';
} else {
selectionBar.style.display = 'none';
bottomBar.style.display = currentView === 'active' && items.length > 0 ? '' : 'none';
}
}
function toggleCheck(itemId) {
if (checkedIds.has(itemId)) checkedIds.delete(itemId);
else checkedIds.add(itemId);
updateSelectionBar();
// Update checkbox visual without full re-render
const cb = document.querySelector(`[data-check="${itemId}"]`);
if (cb) cb.classList.toggle('checked', checkedIds.has(itemId));
}
cancelSelectionBtn.addEventListener('click', () => {
checkedIds.clear();
updateSelectionBar();
render();
});
createWorkspaceBtn.addEventListener('click', () => {
if (checkedIds.size === 0) return;
wsNameInput.value = '';
wsNoteInput.value = '';
wsDialog.style.display = '';
wsNameInput.focus();
});
wsCancelBtn.addEventListener('click', () => { wsDialog.style.display = 'none'; });
wsConfirmBtn.addEventListener('click', async () => {
const name = wsNameInput.value.trim();
if (!name) return showToast('请输入工作区名称');
// Extract checked items from active list
const wsItems = items.filter(i => checkedIds.has(i.id));
items = items.filter(i => !checkedIds.has(i.id));
workspaces.unshift({
id: genId(),
name,
note: wsNoteInput.value.trim(),
items: wsItems,
createdAt: Date.now(),
});
checkedIds.clear();
wsDialog.style.display = 'none';
await save();
updateSelectionBar();
currentView = 'workspaces';
viewTabs.forEach(t => t.classList.toggle('active', t.dataset.view === 'workspaces'));
render();
showToast(`工作区「${name}」已创建 (${wsItems.length} 项)`);
});
// ===== Workspace Actions =====
async function restoreWorkspaceAllTabs(wsId) {
const ws = workspaces.find(w => w.id === wsId);
if (!ws) return;
for (const item of ws.items) {
await smartNavigate(item.url);
}
showToast(`正在恢复「${ws.name}」的 ${ws.items.length} 个标签页`);
}
async function suspendWorkspace(wsId) {
const ws = workspaces.find(w => w.id === wsId);
if (!ws) return;
const allTabs = await chrome.tabs.query({});
let closed = 0;
for (const item of ws.items) {
const tab = allTabs.find(t => t.url === item.url);
if (tab) {
try { await chrome.tabs.remove(tab.id); closed++; } catch {}
}
}
showToast(`已关闭「${ws.name}」的 ${closed} 个标签页`);
}
async function dissolveWorkspace(wsId) {
const ws = workspaces.find(w => w.id === wsId);
if (!ws) return;
// Move items back to active list
items.unshift(...ws.items);
workspaces = workspaces.filter(w => w.id !== wsId);
await save();
render();
showToast(`「${ws.name}」已解散,${ws.items.length} 项已退回待处理`);
}
async function deleteWorkspace(wsId) {
workspaces = workspaces.filter(w => w.id !== wsId);
await save();
render();
}
function startEditWsNote(wsId) {
const ws = workspaces.find(w => w.id === wsId);
if (!ws) return;
const el = document.querySelector(`[data-ws-note="${wsId}"]`);
if (!el) return;
const textarea = document.createElement('textarea');
textarea.className = 'card-note-edit';
textarea.value = ws.note;
textarea.rows = 2;
el.replaceWith(textarea);
textarea.focus();
const commit = async () => {
ws.note = textarea.value.trim();
await save();
render();
};
textarea.addEventListener('blur', commit);
textarea.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); textarea.blur(); }
if (e.key === 'Escape') render();
});
}
// ===== Render =====
function render() {
listArea.innerHTML = '';
updateSelectionBar();
if (currentView === 'active') renderActiveList();
else if (currentView === 'workspaces') renderWorkspaces();
else if (currentView === 'done') renderDoneList();
else if (currentView === 'snapshots') renderSnapshots();
else if (currentView === 'archive') renderArchive();
}
function filterItems(list) {
let result = list;
if (filterTagId) {
result = result.filter(i => i.tags && i.tags.includes(filterTagId));
}
if (searchQuery) {
result = result.filter(i =>
(i.title && i.title.toLowerCase().includes(searchQuery)) ||
(i.customTitle && i.customTitle.toLowerCase().includes(searchQuery)) ||
(i.note && i.note.toLowerCase().includes(searchQuery)) ||
(i.url && i.url.toLowerCase().includes(searchQuery))
);
}
return result;
}
function displayTitle(item) {
return item.customTitle || item.title;
}
function renderActiveList() {
const filtered = filterItems(items);
if (filtered.length === 0) {
listArea.innerHTML = `
<div class="empty-state">
<div class="empty-icon">${searchQuery || filterTagId ? '🔎' : '📚'}</div>
<p>${searchQuery || filterTagId ? '未找到匹配项' : '列表是空的'}</p>
<p class="empty-hint">${searchQuery || filterTagId ? '试试其他关键词或标签' : '点击上方按钮保存当前标签页'}</p>
</div>`;
return;
}
filtered.forEach((item) => {
const realIndex = items.indexOf(item);
const isFirst = realIndex === 0;
const isLast = realIndex === items.length - 1;
let posLabel = '';
if (isFirst && items.length > 1) posLabel = 'FIRST';
else if (isLast && items.length > 1) posLabel = 'LAST';
const prioClass = item.priority ? ` priority-${item.priority}` : '';
const prioIcon = item.priority === 'high' ? '🔴' : item.priority === 'medium' ? '🟠' : item.priority === 'low' ? '🔵' : '⚪';
const card = document.createElement('div');
card.className = `card${prioClass}`;
card.dataset.index = realIndex;
const contextHtml = item.pageContext
? `<div class="card-context">${escHtml(item.pageContext)}</div>` : '';
card.innerHTML = `
${posLabel ? `<div class="position-label">${posLabel}</div>` : ''}
<div class="card-header">
<span class="card-checkbox${checkedIds.has(item.id) ? ' checked' : ''}" data-check="${item.id}"></span>
<span class="card-index">${realIndex + 1}</span>
${item.favicon ? `<img class="card-favicon" src="${escAttr(item.favicon)}" onerror="this.style.display='none'">` : ''}
<div class="card-title-group">
<span class="card-title" data-title-id="${item.id}" data-url="${escAttr(item.url)}" title="双击编辑标题">${escHtml(displayTitle(item))}</span>
<div class="card-subtitle">${escHtml(getUrlSubtitle(item.url))}</div>
</div>
</div>
${contextHtml}
<div class="card-note" data-note-id="${item.id}">${escHtml(item.note)}</div>
${item.tags && item.tags.length ? `<div class="card-tags">${getTagsHtml(item.tags)}</div>` : ''}
<div class="card-meta">
<span class="card-time">${fmtTime(item.timestamp)}</span>
<div class="card-actions">
<button class="card-action-btn labeled" title="切换优先级" data-prio="${item.id}">优先级</button>
<button class="card-action-btn labeled navigate" title="跳转到页面" data-url="${escAttr(item.url)}">跳转</button>
<button class="card-action-btn labeled" title="弹出并跳转" data-pop="${item.id}">弹出</button>
<button class="card-action-btn labeled" title="编辑备注" data-edit="${item.id}">备注</button>
<button class="card-action-btn labeled delete" title="删除" data-del="${item.id}">删除</button>
</div>
</div>`;
if (!searchQuery && !filterTagId) setupDrag(card, realIndex);
listArea.appendChild(card);