-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.js
More file actions
1374 lines (1374 loc) · 55.1 KB
/
Copy pathdashboard.js
File metadata and controls
1374 lines (1374 loc) · 55.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let allArticles = [];
let filteredArticles = [];
let currentSort = 'savedAt-desc';
let selectedArticleIds = new Set();
let currentFilter = 'all';
let currentFilterValue = '';
let confirmModalResolve = null;
let importModalResolve = null;
document.addEventListener('DOMContentLoaded', async () => {
await loadArticles();
setupEventListeners();
setupModalListeners();
});
async function loadArticles() {
const result = await chrome.storage.local.get(['savedArticles']);
allArticles = result.savedArticles || [];
filteredArticles = [...allArticles];
calculateStatistics();
sortArticles();
renderArticles();
updateFilterValueOptions();
renderTagsCloud();
renderAuthorsCloud();
}
function calculateStatistics() {
const total = allArticles.length;
const expired = allArticles.filter(a => isExpiredArticle(a)).length;
const authors = new Set(allArticles.map(a => a.author).filter(Boolean));
const uniqueAuthors = authors.size;
const tags = new Set(allArticles.flatMap(a => a.tags || []).filter(Boolean));
const uniqueTags = tags.size;
document.getElementById('totalSavedCount').textContent = total;
document.getElementById('totalExpiredCount').textContent = expired;
document.getElementById('uniqueAuthorsCount').textContent = uniqueAuthors;
document.getElementById('uniqueTagsCount').textContent = uniqueTags;
if (expired > 0) {
document.getElementById('totalExpiredCount').classList.add('danger-text');
} else {
document.getElementById('totalExpiredCount').classList.remove('danger-text');
}
}
function renderTagsCloud() {
const cloudContainer = document.getElementById('tagsCloud');
if (!cloudContainer) return;
cloudContainer.innerHTML = '';
const tagCounts = {};
allArticles.flatMap(a => a.tags || []).filter(Boolean).forEach(tag => {
tagCounts[tag] = (tagCounts[tag] || 0) + 1;
});
const sortedTags = Object.entries(tagCounts)
.sort((a, b) => b[1] - a[1])
.slice(0, 15);
if (sortedTags.length === 0) {
cloudContainer.innerHTML = '<span style="font-size: 12px; color: var(--text-secondary);">暫無標籤</span>';
return;
}
sortedTags.forEach(([tag, count]) => {
const badge = document.createElement('span');
badge.className = 'tag-badge';
if (currentFilter === 'tag' && currentFilterValue === tag) {
badge.classList.add('active');
}
badge.textContent = `#${tag} (${count})`;
badge.addEventListener('click', () => {
if (currentFilter === 'tag' && currentFilterValue === tag) {
currentFilter = 'all';
currentFilterValue = '';
document.getElementById('filterSelect').value = 'all';
} else {
currentFilter = 'tag';
currentFilterValue = tag;
document.getElementById('filterSelect').value = 'tag';
}
updateFilterValueOptions();
const filterValSelect = document.getElementById('filterValueSelect');
if (filterValSelect) filterValSelect.value = currentFilterValue;
applyFilters();
});
cloudContainer.appendChild(badge);
});
}
function renderAuthorsCloud() {
const cloudContainer = document.getElementById('authorsCloud');
if (!cloudContainer) return;
cloudContainer.innerHTML = '';
const authorCounts = {};
allArticles.map(a => a.author).filter(Boolean).forEach(author => {
authorCounts[author] = (authorCounts[author] || 0) + 1;
});
const sortedAuthors = Object.entries(authorCounts)
.sort((a, b) => b[1] - a[1])
.slice(0, 15);
if (sortedAuthors.length === 0) {
cloudContainer.innerHTML = '<span style="font-size: 12px; color: var(--text-secondary);">暫無作者</span>';
return;
}
sortedAuthors.forEach(([author, count]) => {
const badge = document.createElement('span');
badge.className = 'tag-badge';
if (currentFilter === 'author' && currentFilterValue === author) {
badge.classList.add('active');
}
badge.textContent = `${author} (${count})`;
badge.addEventListener('click', () => {
if (currentFilter === 'author' && currentFilterValue === author) {
currentFilter = 'all';
currentFilterValue = '';
document.getElementById('filterSelect').value = 'all';
} else {
currentFilter = 'author';
currentFilterValue = author;
document.getElementById('filterSelect').value = 'author';
}
updateFilterValueOptions();
const filterValSelect = document.getElementById('filterValueSelect');
if (filterValSelect) filterValSelect.value = currentFilterValue;
applyFilters();
});
cloudContainer.appendChild(badge);
});
}
function setupEventListeners() {
document.getElementById('searchInput').addEventListener('input', () => {
applyFilters();
});
document.getElementById('sortSelect').addEventListener('change', (e) => {
currentSort = e.target.value;
sortArticles();
renderArticles();
});
const filterSelect = document.getElementById('filterSelect');
filterSelect.addEventListener('change', (e) => {
currentFilter = e.target.value;
currentFilterValue = '';
updateFilterValueOptions();
applyFilters();
});
const filterValueSelect = document.getElementById('filterValueSelect');
filterValueSelect.addEventListener('change', (e) => {
currentFilterValue = e.target.value;
applyFilters();
});
const selectAllCheckbox = document.getElementById('selectAllCheckbox');
selectAllCheckbox.addEventListener('change', (e) => {
toggleSelectAll(e.target.checked);
});
document.getElementById('exportBtn').addEventListener('click', exportAllEmbedCodes);
document.getElementById('exportFeaturedBtn').addEventListener('click', exportFeaturedData);
document.getElementById('exportFullBtn').addEventListener('click', exportFullData);
document.getElementById('importBtn').addEventListener('click', () => {
document.getElementById('importFileInput').click();
});
document.getElementById('importFileInput').addEventListener('change', handleImportFile);
document.getElementById('updateTimestampsBtn').addEventListener('click', updateAllTimestamps);
document.getElementById('clearBtn').addEventListener('click', clearAllArticles);
document.getElementById('batchCopyEmbedBtn').addEventListener('click', batchCopyEmbedCodes);
document.getElementById('batchDeleteBtn').addEventListener('click', batchDeleteArticles);
}
function setupModalListeners() {
document.getElementById('modalCloseBtn').addEventListener('click', () => {
closeConfirmModal(false);
});
document.getElementById('modalCancelBtn').addEventListener('click', () => {
closeConfirmModal(false);
});
document.getElementById('modalConfirmBtn').addEventListener('click', () => {
closeConfirmModal(true);
});
document.getElementById('importModalCloseBtn').addEventListener('click', () => {
closeImportModal(null);
});
document.getElementById('importModalCancelBtn').addEventListener('click', () => {
closeImportModal(null);
});
document.getElementById('importModeMerge').addEventListener('click', () => {
closeImportModal('merge');
});
document.getElementById('importModeOverwrite').addEventListener('click', () => {
closeImportModal('overwrite');
});
}
function showConfirm(title, message) {
document.getElementById('modalTitle').textContent = title;
document.getElementById('modalMessage').textContent = message;
document.getElementById('confirmModal').classList.add('active');
return new Promise((resolve) => {
confirmModalResolve = resolve;
});
}
function closeConfirmModal(result) {
document.getElementById('confirmModal').classList.remove('active');
if (confirmModalResolve) {
confirmModalResolve(result);
confirmModalResolve = null;
}
}
function showImportModal(count) {
document.getElementById('importModalMessage').textContent = `偵測到檔案中含有 ${count} 筆文章資料。請選擇匯入模式:`;
document.getElementById('importModal').classList.add('active');
return new Promise((resolve) => {
importModalResolve = resolve;
});
}
function closeImportModal(mode) {
document.getElementById('importModal').classList.remove('active');
if (importModalResolve) {
importModalResolve(mode);
importModalResolve = null;
}
}
function updateFilterValueOptions() {
const container = document.getElementById('filterValueContainer');
const select = document.getElementById('filterValueSelect');
if (!container || !select) return;
select.innerHTML = '<option value="">全部</option>';
let values = [];
switch (currentFilter) {
case 'author':
values = [...new Set(allArticles.map(a => a.author).filter(Boolean))];
values.sort((a, b) => a.localeCompare(b, 'zh-TW'));
break;
case 'tag':
values = [...new Set(allArticles.flatMap(a => a.tags || []).filter(Boolean))];
values.sort((a, b) => a.localeCompare(b, 'zh-TW'));
break;
default:
container.style.display = 'none';
return;
}
if (values.length > 0) {
container.style.display = 'flex';
values.forEach(val => {
const opt = document.createElement('option');
opt.value = val;
opt.textContent = val;
if (val === currentFilterValue) {
opt.selected = true;
}
select.appendChild(opt);
});
} else {
container.style.display = 'none';
}
}
function applyFilters() {
const searchTerm = document.getElementById('searchInput').value.trim().toLowerCase();
filteredArticles = allArticles.filter(article => {
if (!matchesFilter(article)) return false;
if (searchTerm) {
const contentMatch = (article.content || '').toLowerCase().includes(searchTerm);
const authorMatch = (article.author || '').toLowerCase().includes(searchTerm);
const tagsMatch = (article.tags || []).some(tag => (tag || '').toLowerCase().includes(searchTerm));
const codeMatch = (article.codeBlocks || []).some(block =>
(block.code || '').toLowerCase().includes(searchTerm) ||
(block.language || '').toLowerCase().includes(searchTerm)
);
const embedMatch = (article.embedCode || '').toLowerCase().includes(searchTerm);
return contentMatch || authorMatch || tagsMatch || codeMatch || embedMatch;
}
return true;
});
sortArticles();
renderArticles();
renderTagsCloud();
renderAuthorsCloud();
}
function matchesFilter(article) {
switch (currentFilter) {
case 'all':
return true;
case 'author':
if (!currentFilterValue) return true;
return (article.author || '').toLowerCase() === currentFilterValue.toLowerCase();
case 'tag':
if (!currentFilterValue) return true;
return (article.tags || []).some(tag =>
(tag || '').toLowerCase() === currentFilterValue.toLowerCase()
);
case 'noTimestamp':
if (!article.timestamp) return true;
if (!article.timestampTitle) {
const timestamp = new Date(article.timestamp).getTime();
const savedAt = new Date(article.savedAt).getTime();
if (Math.abs(timestamp - savedAt) < 60000) return true;
}
return false;
case 'expired':
return isExpiredArticle(article);
default:
return true;
}
}
function sortArticles() {
const [field, order] = currentSort.split('-');
filteredArticles.sort((a, b) => {
let valA, valB;
const parseDate = (dStr) => {
if (!dStr) return 0;
const parsed = new Date(dStr).getTime();
return isNaN(parsed) ? 0 : parsed;
};
switch (field) {
case 'savedAt':
valA = parseDate(a.savedAt);
valB = parseDate(b.savedAt);
break;
case 'timestamp':
valA = parseDate(a.timestamp);
valB = parseDate(b.timestamp);
break;
case 'author':
valA = (a.author || '').toLowerCase();
valB = (b.author || '').toLowerCase();
break;
case 'codeCount':
valA = a.codeCount ?? (a.codeBlocks || []).length;
valB = b.codeCount ?? (b.codeBlocks || []).length;
break;
default:
valA = parseDate(a.savedAt);
valB = parseDate(b.savedAt);
}
if (typeof valA === 'string' && typeof valB === 'string') {
const cmp = valA.localeCompare(valB, 'zh-TW');
return order === 'asc' ? cmp : -cmp;
}
return order === 'asc' ? valA - valB : valB - valA;
});
}
function renderArticles() {
const container = document.getElementById('articlesContainer');
if (!container) return;
container.innerHTML = '';
if (filteredArticles.length === 0) {
const empty = document.createElement('div');
empty.className = 'empty-state';
empty.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="empty-icon"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>
<p class="empty-title">${allArticles.length === 0 ? '尚未儲存任何程式碼' : '找不到符合的貼文'}</p>
<p class="empty-description">${allArticles.length === 0 ? '請在 Threads 上有程式碼的貼文旁,點選「取得內嵌程式碼」,擴充功能會自動儲存至此面板。' : '請嘗試更換篩選條件或搜尋關鍵字。'}</p>
`;
container.appendChild(empty);
updateSelectionUI();
return;
}
filteredArticles.forEach(article => {
const card = document.createElement('div');
card.className = 'article-card';
if (selectedArticleIds.has(article.id)) {
card.classList.add('selected');
}
card.dataset.id = article.id;
const chkLabel = document.createElement('label');
chkLabel.className = 'checkbox-container card-checkbox';
const chkInput = document.createElement('input');
chkInput.type = 'checkbox';
chkInput.className = 'article-checkbox';
chkInput.checked = selectedArticleIds.has(article.id);
chkInput.dataset.articleId = article.id;
const chkMark = document.createElement('span');
chkMark.className = 'checkmark';
chkLabel.appendChild(chkInput);
chkLabel.appendChild(chkMark);
card.appendChild(chkLabel);
const wrapper = document.createElement('div');
wrapper.className = 'card-content-wrapper';
const header = document.createElement('div');
header.className = 'card-header';
const authorEl = document.createElement('span');
authorEl.className = 'author';
authorEl.textContent = article.author || '未填寫作者';
const timeInfo = document.createElement('div');
timeInfo.className = 'time-info';
const timePost = document.createElement('div');
timePost.title = article.timestampTitle || article.timestamp || '';
timePost.textContent = '發文:' + (article.timestampTitle ? article.timestampTitle : formatTime(article.timestamp));
const timeSaved = document.createElement('div');
timeSaved.title = article.savedAt || '';
timeSaved.textContent = '儲存:' + formatTime(article.savedAt);
timeInfo.appendChild(timePost);
timeInfo.appendChild(timeSaved);
header.appendChild(authorEl);
header.appendChild(timeInfo);
wrapper.appendChild(header);
const bodyEl = document.createElement('div');
bodyEl.className = 'card-body';
const rawContent = article.content || '';
if (rawContent.length > 150) {
const shortText = rawContent.substring(0, 150);
const spanText = document.createElement('span');
spanText.className = 'text-chunk';
spanText.textContent = shortText + '...';
bodyEl.appendChild(spanText);
const expandBtn = document.createElement('button');
expandBtn.className = 'expand-text-btn';
expandBtn.textContent = '展開';
expandBtn.addEventListener('click', () => {
if (expandBtn.textContent === '展開') {
spanText.textContent = rawContent;
expandBtn.textContent = '收起';
} else {
spanText.textContent = shortText + '...';
expandBtn.textContent = '展開';
}
});
bodyEl.appendChild(expandBtn);
} else {
bodyEl.textContent = rawContent || '無內文說明';
}
wrapper.appendChild(bodyEl);
if (isExpiredArticle(article)) {
const badge = document.createElement('div');
badge.className = 'status-badge expired';
badge.textContent = `已失效 (${article.expiredReason || '無法解析'})`;
wrapper.appendChild(badge);
}
if (article.tags && article.tags.length > 0) {
const tagsContainer = document.createElement('div');
tagsContainer.className = 'card-tags';
article.tags.forEach(tag => {
const tagEl = document.createElement('span');
tagEl.className = 'card-tag';
tagEl.textContent = '#' + tag;
tagEl.addEventListener('click', (e) => {
e.stopPropagation();
currentFilter = 'tag';
currentFilterValue = tag;
document.getElementById('filterSelect').value = 'tag';
updateFilterValueOptions();
const filterValSelect = document.getElementById('filterValueSelect');
if (filterValSelect) filterValSelect.value = tag;
applyFilters();
});
tagsContainer.appendChild(tagEl);
});
wrapper.appendChild(tagsContainer);
}
if (article.embedCode) {
const embedSec = document.createElement('div');
embedSec.className = 'embed-section';
const toggleBtn = document.createElement('button');
toggleBtn.className = 'embed-toggle';
toggleBtn.innerHTML = `
<span>內嵌 JavaScript 原始碼</span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
`;
const embedContent = document.createElement('div');
embedContent.className = 'embed-content';
const preEl = document.createElement('pre');
preEl.textContent = article.embedCode;
embedContent.appendChild(preEl);
toggleBtn.addEventListener('click', () => {
toggleBtn.classList.toggle('active');
embedContent.classList.toggle('active');
});
embedSec.appendChild(toggleBtn);
embedSec.appendChild(embedContent);
wrapper.appendChild(embedSec);
}
if (article.codeBlocks && article.codeBlocks.length > 0) {
const blocksContainer = document.createElement('div');
blocksContainer.className = 'code-blocks';
article.codeBlocks.forEach((block, index) => {
const blockEl = document.createElement('div');
blockEl.className = 'code-block';
const blockHeader = document.createElement('div');
blockHeader.className = 'code-header';
const langLabel = document.createElement('span');
langLabel.className = 'code-lang';
langLabel.textContent = block.language || 'code';
const copyBtn = document.createElement('button');
copyBtn.className = 'code-copy-btn';
copyBtn.textContent = '複製程式碼';
copyBtn.addEventListener('click', () => {
copyTextToClipboard(block.code, '程式碼已複製');
});
blockHeader.appendChild(langLabel);
blockHeader.appendChild(copyBtn);
const blockContent = document.createElement('div');
blockContent.className = 'code-content';
const blockPre = document.createElement('pre');
const blockCode = document.createElement('code');
blockCode.textContent = block.code || '';
blockPre.appendChild(blockCode);
blockContent.appendChild(blockPre);
blockEl.appendChild(blockHeader);
blockEl.appendChild(blockContent);
blocksContainer.appendChild(blockEl);
});
wrapper.appendChild(blocksContainer);
}
const actions = document.createElement('div');
actions.className = 'card-actions';
const viewBtn = document.createElement('a');
viewBtn.className = 'card-action-btn primary';
viewBtn.href = sanitizeUrl(article.postLink || '#');
viewBtn.target = '_blank';
viewBtn.rel = 'noopener noreferrer';
viewBtn.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
查看原文
`;
actions.appendChild(viewBtn);
if (article.embedCode) {
const copyEmbedBtn = document.createElement('button');
copyEmbedBtn.className = 'card-action-btn';
copyEmbedBtn.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
複製內嵌代碼
`;
copyEmbedBtn.addEventListener('click', () => {
copyTextToClipboard(article.embedCode, '內嵌代碼已複製');
});
actions.appendChild(copyEmbedBtn);
}
const deleteBtn = document.createElement('button');
deleteBtn.className = 'card-action-btn danger';
deleteBtn.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" 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"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>
刪除
`;
deleteBtn.addEventListener('click', () => {
deleteArticle(article.id);
});
actions.appendChild(deleteBtn);
wrapper.appendChild(actions);
card.appendChild(wrapper);
container.appendChild(card);
});
container.querySelectorAll('.article-checkbox').forEach(chk => {
chk.addEventListener('change', (e) => {
const id = e.target.dataset.articleId;
const card = e.target.closest('.article-card');
if (e.target.checked) {
selectedArticleIds.add(id);
card.classList.add('selected');
} else {
selectedArticleIds.delete(id);
card.classList.remove('selected');
}
updateSelectionUI();
});
});
updateSelectionUI();
}
function updateSelectionUI() {
const selectAll = document.getElementById('selectAllCheckbox');
const batchActions = document.getElementById('batchActionsContainer');
const selInfo = document.getElementById('selectionInfo');
if (selectedArticleIds.size > 0) {
selInfo.textContent = `已選取 ${selectedArticleIds.size} 篇`;
selInfo.style.display = 'inline';
batchActions.style.opacity = '1';
batchActions.style.pointerEvents = 'auto';
} else {
selInfo.style.display = 'none';
batchActions.style.opacity = '0.5';
batchActions.style.pointerEvents = 'none';
}
if (selectAll && filteredArticles.length > 0) {
const allChecked = filteredArticles.every(a => selectedArticleIds.has(a.id));
const someChecked = filteredArticles.some(a => selectedArticleIds.has(a.id));
selectAll.checked = allChecked;
selectAll.indeterminate = someChecked && !allChecked;
}
}
function toggleSelectAll(checked) {
if (checked) {
filteredArticles.forEach(a => selectedArticleIds.add(a.id));
} else {
filteredArticles.forEach(a => selectedArticleIds.delete(a.id));
}
renderArticles();
}
async function copyTextToClipboard(text, successMessage) {
try {
await navigator.clipboard.writeText(text);
showToast(successMessage);
} catch (err) {
console.error('複製失敗:', err);
showToast('複製失敗,瀏覽器權限受限');
}
}
function showToast(message) {
const container = document.getElementById('toastContainer');
if (!container) return;
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = message;
container.appendChild(toast);
setTimeout(() => {
toast.classList.add('fade-out');
toast.addEventListener('animationend', () => {
toast.remove();
});
}, 2500);
}
async function refreshEmbedCode(articleId) {
const article = allArticles.find(a => a.id === articleId);
if (!article || !article.postLink) {
showToast('找不到文章連結');
return;
}
showToast('正在重新生成嵌入代碼...');
const newEmbed = buildThreadsEmbedCode(article.postLink);
if (!newEmbed) {
showToast('生成失敗');
return;
}
article.embedCode = newEmbed;
article.lastUpdated = new Date().toISOString();
await chrome.storage.local.set({ savedArticles: allArticles });
showToast('嵌入代碼已重新生成');
calculateStatistics();
renderArticles();
}
async function batchRegenEmbedCodes() {
const targets = allArticles.filter(a => selectedArticleIds.has(a.id) && a.postLink);
if (targets.length === 0) return;
const confirmed = await showConfirm(
'批次重新生成確認',
`您確定要為已選取的 ${targets.length} 篇文章重新生成內嵌程式碼嗎?`
);
if (!confirmed) return;
showToast(`正在重新生成 ${targets.length} 篇文章的嵌入代碼...`);
let successCount = 0;
targets.forEach(article => {
const newEmbed = buildThreadsEmbedCode(article.postLink);
if (newEmbed) {
article.embedCode = newEmbed;
article.lastUpdated = new Date().toISOString();
successCount++;
}
});
await chrome.storage.local.set({ savedArticles: allArticles });
selectedArticleIds.clear();
calculateStatistics();
renderArticles();
showToast(`完成!成功重新生成 ${successCount} 篇`);
}
async function batchCopyEmbedCodes() {
const targets = allArticles.filter(a => selectedArticleIds.has(a.id) && a.embedCode);
if (targets.length === 0) {
showToast('選取文章中不包含任何內嵌程式碼');
return;
}
const codes = targets.map(article => {
let blockquoteOnly = article.embedCode;
let previous;
do {
previous = blockquoteOnly;
blockquoteOnly = blockquoteOnly.replace(/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>/gi, '');
} while (blockquoteOnly !== previous);
blockquoteOnly = blockquoteOnly.trim();
return blockquoteOnly;
}).join('\n\n');
await copyTextToClipboard(codes, `已批次複製 ${targets.length} 篇內嵌程式碼`);
}
async function deleteArticle(articleId) {
const article = allArticles.find(a => a.id === articleId);
const authorName = article ? article.author : '此貼文';
const confirmed = await showConfirm(
'刪除貼文確認',
`您確定要刪除由 ${authorName} 發布的儲存程式碼嗎?此動作將無法還原。`
);
if (!confirmed) return;
allArticles = allArticles.filter(a => a.id !== articleId);
await chrome.storage.local.set({ savedArticles: allArticles });
selectedArticleIds.delete(articleId);
applyFilters();
calculateStatistics();
showToast('已刪除貼文');
}
async function batchDeleteArticles() {
if (selectedArticleIds.size === 0) return;
const count = selectedArticleIds.size;
const confirmed = await showConfirm(
'批次刪除確認',
`您確定要完全刪除已選取的 ${count} 篇文章嗎?此動作將無法還原!`
);
if (!confirmed) return;
allArticles = allArticles.filter(a => !selectedArticleIds.has(a.id));
await chrome.storage.local.set({ savedArticles: allArticles });
selectedArticleIds.clear();
applyFilters();
calculateStatistics();
showToast(`已批次刪除 ${count} 篇文章`);
}
async function clearAllArticles() {
if (allArticles.length === 0) {
showToast('目前無任何文章資料');
return;
}
const confirmed = await showConfirm(
'清除全部資料',
`【警告】您確定要清除目前儲存的所有 ${allArticles.length} 篇資料嗎?此操作將會完全清空擴充功能資料庫,且無法還原!`
);
if (!confirmed) return;
allArticles = [];
filteredArticles = [];
selectedArticleIds.clear();
await chrome.storage.local.set({ savedArticles: [] });
applyFilters();
calculateStatistics();
showToast('資料庫已清空');
}
async function refreshAllEmbedCodes() {
const confirmed = await showConfirm(
'重新生成全部',
`您確定要為目前已儲存的 ${allArticles.length} 篇貼文重新生成嵌入程式碼嗎?`
);
if (!confirmed) return;
showToast('正在重新生成全部嵌入代碼...');
let successCount = 0;
allArticles.forEach(article => {
if (article.postLink) {
const newEmbed = buildThreadsEmbedCode(article.postLink);
if (newEmbed) {
article.embedCode = newEmbed;
article.lastUpdated = new Date().toISOString();
successCount++;
}
}
});
await chrome.storage.local.set({ savedArticles: allArticles });
renderArticles();
showToast(`完成!成功重新生成 ${successCount} 篇`);
}
async function updateAllTimestamps() {
const baseArticles = selectedArticleIds.size > 0
? allArticles.filter(a => selectedArticleIds.has(a.id))
: allArticles;
if (baseArticles.length === 0) {
showToast('沒有文章可以更新');
return;
}
const articlesNeedingUpdate = baseArticles.filter(a => a.postLink);
if (articlesNeedingUpdate.length === 0) {
showToast('沒有有效的文章連結');
return;
}
const isBatch = selectedArticleIds.size > 0;
const confirmed = await showConfirm(
'更新貼文資料',
`確定要更新${isBatch ? '已選取的' : '全部'} ${articlesNeedingUpdate.length} 篇文章的精確發文時間和內文嗎?\n\n系統將會依序開啟背景分頁抓取 Threads 貼文,可能需要一些時間。抓取完畢後分頁將自動關閉。`
);
if (!confirmed) return;
showToast(`正在背景更新資料... (0/${articlesNeedingUpdate.length})`);
let successCount = 0;
let failCount = 0;
let currentIndex = 0;
const maxConcurrency = 3;
const tasks = [...articlesNeedingUpdate];
const runWorker = async () => {
while (tasks.length > 0) {
const article = tasks.shift();
if (!article) break;
let localIndex = 0;
try {
const postInfo = await fetchPostInfoViaTab(article.postLink);
currentIndex++;
localIndex = currentIndex;
if (postInfo) {
if (postInfo.status === 'expired') {
markArticleAsExpired(article, postInfo.reason);
failCount++;
} else {
clearArticleExpiredStatus(article);
if (postInfo.datetime) {
article.timestamp = postInfo.datetime;
article.timestampTitle = postInfo.title || '';
}
if (typeof postInfo.content === 'string' && !postInfo.content.includes('加入 Threads 即可分享意見')) {
article.content = postInfo.content;
}
if (Array.isArray(postInfo.tags)) {
article.tags = postInfo.tags;
}
article.timestampUpdatedAt = new Date().toISOString();
successCount++;
}
} else {
failCount++;
}
} catch (err) {
console.error('[Dashboard] 擷取錯誤:', err);
failCount++;
}
showToast(`更新進度: ${localIndex}/${articlesNeedingUpdate.length} (成功: ${successCount})`);
}
};
const workers = [];
for (let i = 0; i < Math.min(maxConcurrency, articlesNeedingUpdate.length); i++) {
workers.push(runWorker());
}
await Promise.all(workers);
await chrome.storage.local.set({ savedArticles: allArticles });
selectedArticleIds.clear();
calculateStatistics();
applyFilters();
showToast(`資料更新完成!成功: ${successCount}, 失敗/失效: ${failCount}`);
}
async function fetchPostInfoViaTab(postLink) {
let tab = null;
try {
const safeUrl = sanitizeUrl(postLink);
if (safeUrl === '#') return null;
tab = await chrome.tabs.create({
url: safeUrl,
active: false
});
await waitForTabLoad(tab.id);
const loadedTab = await chrome.tabs.get(tab.id);
if (!isSameThreadsPostLink(safeUrl, loadedTab?.url || '')) {
await chrome.tabs.remove(tab.id);
return {
status: 'expired',
reason: 'redirected'
};
}
const results = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: extractPostInfoFromPage,
args: [safeUrl]
});
await chrome.tabs.remove(tab.id);
if (results && results[0] && results[0].result) {
return results[0].result;
}
return null;
} catch (err) {
console.error('[Dashboard] fetchPostInfoViaTab 錯誤:', err);
if (tab && tab.id) {
try {
await chrome.tabs.remove(tab.id);
} catch (e) { }
}
return null;
}
}
function waitForTabLoad(tabId) {
return new Promise((resolve) => {
const timeout = setTimeout(() => {
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}, 8000);
const listener = (updatedTabId, changeInfo) => {
if (updatedTabId === tabId && changeInfo.status === 'complete') {
clearTimeout(timeout);
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
};
chrome.tabs.onUpdated.addListener(listener);
});
}
async function extractPostInfoFromPage(requestedPostLink = '') {
function createExpiredPostResult(reason) {
return {
status: 'expired',
reason,
datetime: '',
title: '',
content: ''
};
}
function findPostElementFromPostLink(postLink) {
const match = postLink.match(/\/(post|t)\/([^\/\?]+)/i);
if (!match) return null;
const postId = match[2];
const links = Array.from(document.querySelectorAll(`a[href*="/post/${postId}"], a[href*="/t/${postId}"]`));
for (const link of links) {
const pressable = link.closest('[data-pressable-container]');
if (pressable) return pressable;
}
const timeEl = document.querySelector('time[datetime]');
if (timeEl) {
const pressable = timeEl.closest('[data-pressable-container]');
if (pressable) return pressable;
}
return null;
}
function isLikelyThreadsFallbackDescription(text) {
const normalizedText = String(text).replace(/\s+/g, ' ').trim();
return [
/\d[\d,.]*\s*(?:萬|千)?次?瀏覽/i,
/^回覆[\s\S]*[…\.]{1,3}$/i,
/^尚無回覆$/i,
/^查看動態$/i,
/^更多$/i,
/^返回$/i,
/^直欄標題$/i,
/^附加影音內容$/i,
/^新增 GIF$/i,
/^展開撰寫工具$/i,
/^分享$/i,
/^轉發$/i,
/^讚$/i,
/^為你推薦$/,
/^新串文$/,
/^搜尋$/,
/^動態$/,
/^個人檔案$/,
/^聯邦宇宙$/,
/^洞察報告$/,
/^已儲存$/,
/^追蹤中$/,
/^附帶原始貼文的回覆內容$/,
/\d[\d,.]*\s*位粉絲\s*•\s*\d[\d,.]*\s*則串文/i,
/\d[\d,.]*\s*followers\s*•\s*\d[\d,.]*\s*threads/i,
/查看\s*@.+\s*參與的最新對話/i,
/See\s*what\s*@.+\s*is\s*saying\s*on\s*Threads/i,
/在貼文中提及\s*@meta\.ai\s*,即可在這裡獲得解答/i,
].some(pattern => pattern.test(normalizedText));
}
return new Promise((resolve) => {
const maxWaitMs = 4000;
const startTime = Date.now();
const check = () => {
const requestedPostElement = requestedPostLink ? findPostElementFromPostLink(requestedPostLink) : null;
if (requestedPostLink && !requestedPostElement) {
return false;
}
const sourceRoot = requestedPostElement || document;
let datetime = null;
let title = '';
let content = '';
const timeElement = requestedPostElement?.querySelector('time[datetime]') || null;
if (timeElement) {
datetime = timeElement.getAttribute('datetime');
title = timeElement.getAttribute('title') || '';
}
if (!datetime) {
const metaTime = document.querySelector('meta[property="article:published_time"]');
if (metaTime) {
datetime = metaTime.getAttribute('content');
}
}
if (!datetime) {
const scripts = document.querySelectorAll('script[type="application/ld+json"]');
for (const script of scripts) {
try {
const jsonData = JSON.parse(script.textContent);
if (jsonData.datePublished) {
datetime = jsonData.datePublished;
break;
}
} catch (e) { }
}
}
if (!content) {
const contentSpans = sourceRoot.querySelectorAll('span[class*="xo1l8bm"][dir="auto"] > span');
if (contentSpans.length > 0) {
content = Array.from(contentSpans)
.filter(span => !span.closest('h1'))
.filter(span => !span.closest('button'))
.filter(span => !span.closest('[role="button"]'))
.filter(span => !span.closest('[contenteditable="true"]'))
.filter(span => {
if (span.closest('.x6s0dn4.xmixu3c.x78zum5.xsag5q8.x1y1aw1k')) return false;
let parent = span.parentElement;
while (parent && parent !== sourceRoot) {
const text = parent.textContent;
if (text.includes('在貼文中提及') && text.includes('@meta.ai') && text.includes('即可在這裡獲得解答')) {
return false;
}
parent = parent.parentElement;
}
return true;
})
.map(span => (span.innerText || span.textContent || '').replace(/\s+/g, ' ').trim())
.filter(text => text && !isLikelyThreadsFallbackDescription(text))
.filter((text, index, array) => array.indexOf(text) === index)
.join('\n');
}
}
if (!content) {
const xi7Spans = sourceRoot.querySelectorAll('span[class*="xi7mnp6"][dir="auto"] > span');
if (xi7Spans.length > 0) {
content = Array.from(xi7Spans)
.filter(span => !span.closest('h1'))
.filter(span => !span.closest('button'))
.filter(span => !span.closest('[role="button"]'))
.filter(span => !span.closest('[contenteditable="true"]'))
.filter(span => {
if (span.closest('.x6s0dn4.xmixu3c.x78zum5.xsag5q8.x1y1aw1k')) return false;
let parent = span.parentElement;
while (parent && parent !== sourceRoot) {
const text = parent.textContent;
if (text.includes('在貼文中提及') && text.includes('@meta.ai') && text.includes('即可在這裡獲得解答')) {
return false;
}
parent = parent.parentElement;
}
return true;
})
.map(span => (span.innerText || span.textContent || '').replace(/\s+/g, ' ').trim())
.filter(text => text && !isLikelyThreadsFallbackDescription(text))
.filter((text, index, array) => array.indexOf(text) === index)
.join('\n');