-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathbookmarkProfile.js
More file actions
2037 lines (1769 loc) · 79.3 KB
/
Copy pathbookmarkProfile.js
File metadata and controls
2037 lines (1769 loc) · 79.3 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
// 在文件开头导入 html2canvas
import html2canvas from './html2canvas.min.js';
console.log('BookmarkProfile module loaded');
// 添加获取存储的昵称函数
async function getNickname() {
const result = await chrome.storage.local.get('bookmarkProfileNickname');
return result.bookmarkProfileNickname;
}
// 添加设置昵称函数
async function setNickname(nickname) {
await chrome.storage.local.set({ 'bookmarkProfileNickname': nickname });
}
// 修改 DOMContentLoaded 事件处理
document.addEventListener('DOMContentLoaded', async () => {
try {
// 初始化本地化文本
document.querySelectorAll('[data-i18n]').forEach(element => {
const message = element.getAttribute('data-i18n');
const localizedText = chrome.i18n.getMessage(message);
if (localizedText) {
element.textContent = localizedText;
}
});
// 检查是否已有昵称
const nickname = await getNickname();
if (!nickname) {
// 如果没有昵称,显示输入对话框
showNicknameModal();
} else {
// 如果有昵称,更新标题并初始化
updateProfileTitle(nickname);
await initBookmarkProfile();
}
// 初始化分享功能
await initShareFeature();
} catch (error) {
console.error('Error during initialization:', error);
}
});
// 修改显示昵称输入对话框函数
function showNicknameModal(isFirstTime = true) { // 添加参数标识是否首次设置
const modalOverlay = document.querySelector('.modal-overlay');
const nicknameInput = modalOverlay.querySelector('.nickname-input');
const confirmButton = modalOverlay.querySelector('.confirm');
const cancelButton = modalOverlay.querySelector('.cancel');
const modalTitle = modalOverlay.querySelector('.modal-title');
// 根据是否首次设置显示不同的标题
if (modalTitle) {
modalTitle.textContent = getMessage(isFirstTime ? 'shareModalTitle' : 'editNicknameTitle');
}
// 显示模态框
modalOverlay.style.display = 'flex';
// 如果是编辑模式,填入当前昵称
if (!isFirstTime) {
getNickname().then(currentNickname => {
if (nicknameInput && currentNickname) {
nicknameInput.value = currentNickname;
// 选中文本以方便修改
nicknameInput.select();
}
});
}
// 根据是否首次设置来显示/隐藏取消按钮
if (cancelButton) {
cancelButton.style.display = isFirstTime ? 'none' : 'block';
}
// 取消按钮处理
const handleCancel = () => {
modalOverlay.style.display = 'none';
nicknameInput.value = '';
};
// 确认按钮处理
const handleConfirm = async () => {
const nickname = nicknameInput.value.trim();
if (!nickname) {
alert(getMessage('pleaseEnterNickname'));
return;
}
try {
// 保存昵称
await setNickname(nickname);
// 更新标题
updateProfileTitle(nickname);
if (isFirstTime) {
await initBookmarkProfile();
}
modalOverlay.style.display = 'none';
} catch (error) {
console.error('Error saving nickname:', error);
alert(getMessage('nicknameError'));
}
};
// 移除旧的事件监听器(如果有的话)
confirmButton?.removeEventListener('click', handleConfirm);
cancelButton?.removeEventListener('click', handleCancel);
// 添加新的事件监听器
confirmButton?.addEventListener('click', handleConfirm);
cancelButton?.addEventListener('click', handleCancel);
// 添加 ESC 键关闭功能(仅在非首次设置时)
const handleEscape = (e) => {
if (e.key === 'Escape' && !isFirstTime) {
handleCancel();
}
};
document.addEventListener('keydown', handleEscape);
// 点击遮罩层关闭(仅在非首次设置时)
modalOverlay.addEventListener('click', (e) => {
if (e.target === modalOverlay && !isFirstTime) {
handleCancel();
}
});
}
// 添加修改昵称的功能
function addEditNicknameFeature() {
const profileTitle = document.querySelector('.profile-title h2');
if (!profileTitle) return;
// 添加编辑图标
const editIcon = document.createElement('span');
editIcon.innerHTML = '✎'; // 使用编辑图标
editIcon.className = 'edit-nickname-icon';
editIcon.style.cursor = 'pointer';
editIcon.style.marginLeft = '8px';
editIcon.style.fontSize = '14px';
editIcon.style.opacity = '0.5';
editIcon.title = getMessage('editNickname');
// 鼠标悬停效果
editIcon.addEventListener('mouseenter', () => editIcon.style.opacity = '1');
editIcon.addEventListener('mouseleave', () => editIcon.style.opacity = '0.5');
// 点击编辑
editIcon.addEventListener('click', () => {
showNicknameModal(false); // 显示带取消按钮的模态框
});
profileTitle.appendChild(editIcon);
}
// 修改 DOMContentLoaded 事件处理
document.addEventListener('DOMContentLoaded', async () => {
try {
// 初始化本地化文本
document.querySelectorAll('[data-i18n]').forEach(element => {
const message = element.getAttribute('data-i18n');
const localizedText = chrome.i18n.getMessage(message);
if (localizedText) {
element.textContent = localizedText;
}
});
// 检查是否已有昵称
const nickname = await getNickname();
if (!nickname) {
// 如果没有昵称,显示输入对话框(首次设置)
showNicknameModal(true);
} else {
// 如果有昵称,更新标题并初始化
updateProfileTitle(nickname);
await initBookmarkProfile();
// 添加编辑昵称功能
addEditNicknameFeature();
}
// 初始化分享功能
await initShareFeature();
} catch (error) {
console.error('Error during initialization:', error);
}
});
// 修改更新标题函数
function updateProfileTitle(nickname) {
const profileTitle = document.querySelector('.profile-title h2');
if (!profileTitle) return;
const nicknameSpan = profileTitle.querySelector('.nickname') || document.createElement('span');
const profileTextSpan = profileTitle.querySelector('.profile-text') || document.createElement('span');
if (!nicknameSpan.classList.contains('nickname')) {
nicknameSpan.classList.add('nickname');
profileTitle.insertBefore(nicknameSpan, profileTitle.firstChild);
}
if (!profileTextSpan.classList.contains('profile-text')) {
profileTextSpan.classList.add('profile-text');
profileTitle.appendChild(profileTextSpan);
}
// 使用本地化模板来设置内容
const localizedTitle = getMessage('bookmarkProfileTitle', [nickname]);
const parts = localizedTitle.split(nickname);
// 设置内容
nicknameSpan.textContent = nickname;
profileTextSpan.textContent = parts[1] || '的书签画像';
// 只保留必要的样式设置
nicknameSpan.style.cursor = 'pointer';
nicknameSpan.title = getMessage('editNickname');
// 添加点击事件(仅在昵称部分)
nicknameSpan.addEventListener('click', () => {
showNicknameModal(false);
});
// 添加悬停效果(仅在昵称部分)
nicknameSpan.addEventListener('mouseenter', () => {
nicknameSpan.style.color = '#10b981';
});
nicknameSpan.addEventListener('mouseleave', () => {
nicknameSpan.style.color = '#1d1d1f';
});
}
// 添加获取本地化消息的辅助函数
function getMessage(messageName, substitutions = null) {
return chrome.i18n.getMessage(messageName, substitutions);
}
// 添加书签画像初始化函数
async function initBookmarkProfile() {
const profileEl = document.querySelector('.bookmark-profile');
if (!profileEl) return;
try {
// 获取书签树
const tree = await chrome.bookmarks.getTree();
// 显示画像卡片
profileEl.style.display = 'block';
// 初始化日期范围
await updateProfileDateRange(tree[0]);
// 初始化基础数据
const stats = await calculateBookmarkStats(tree[0]);
// 生成���签画像
await generateBookmarkProfile(tree[0]);
// 更新域名分析
await updateDomainAnalysis(profileEl, stats);
// 添加趋势图渲染
await renderTrendChart(tree[0]);
} catch (error) {
console.error('Error initializing bookmark profile:', error);
profileEl.style.display = 'none';
}
}
// 更新日期范围显示
async function updateProfileDateRange(rootNode) {
const dateEl = document.querySelector('.profile-date');
if (!dateEl) return;
try {
const dates = await getBookmarkDateRange(rootNode);
const startDate = new Date(dates.oldest).toISOString().split('T')[0].replace(/-/g, '.');
const endDate = new Date(dates.newest).toISOString().split('T')[0].replace(/-/g, '.');
dateEl.textContent = `${startDate}-${endDate}`;
} catch (error) {
console.error('Error updating date range:', error);
dateEl.textContent = '';
}
}
// 获取书签的日期范围
async function getBookmarkDateRange(node) {
let oldest = Date.now();
let newest = 0;
function traverse(node) {
if (node.dateAdded) {
oldest = Math.min(oldest, node.dateAdded);
newest = Math.max(newest, node.dateAdded);
}
if (node.children) {
node.children.forEach(traverse);
}
}
traverse(node);
return { oldest, newest };
}
// 获取按年份分组的书签数据
async function getBookmarksByYear(rootNode) {
const bookmarksByYear = new Map();
function traverse(node) {
if (node.dateAdded) {
const year = new Date(node.dateAdded).getFullYear();
bookmarksByYear.set(year, (bookmarksByYear.get(year) || 0) + 1);
}
if (node.children) {
node.children.forEach(traverse);
}
}
traverse(rootNode);
return new Map([...bookmarksByYear.entries()].sort((a, b) => a[0] - b[0]));
}
// 渲染趋势图
async function renderTrendChart(rootNode) {
const chartContainer = document.querySelector('.chart-container');
if (!chartContainer) return;
// 获取书签数据并按年份分组
const bookmarksByYear = await getBookmarksByYear(rootNode);
// 创建容器布局
chartContainer.style.display = 'flex';
chartContainer.style.alignItems = 'stretch';
chartContainer.innerHTML = '';
// 创建趋势图 SVG 容器
const trendSvgContainer = document.createElement('div');
trendSvgContainer.style.flex = '1';
const trendSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
trendSvg.setAttribute('width', '100%');
trendSvg.setAttribute('height', '100%');
trendSvg.style.overflow = 'visible';
trendSvgContainer.appendChild(trendSvg);
// 创建Y轴 SVG 容器
const yAxisSvgContainer = document.createElement('div');
yAxisSvgContainer.style.width = '60px';
const yAxisSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
yAxisSvg.setAttribute('width', '100%');
yAxisSvg.setAttribute('height', '100%');
yAxisSvg.style.overflow = 'visible';
yAxisSvgContainer.appendChild(yAxisSvg);
// 添加到主容器
chartContainer.appendChild(trendSvgContainer);
chartContainer.appendChild(yAxisSvgContainer);
// 绘制趋势图和Y轴
drawTrendLine(trendSvg, bookmarksByYear);
drawYAxis(yAxisSvg, bookmarksByYear);
}
// 绘制趋势线
function drawTrendLine(svg, data) {
const width = svg.clientWidth;
const height = svg.clientHeight;
const padding = {
left: 0,
right: 20,
top: 20,
bottom: 40
};
// 计算数据范围
const years = Array.from(data.keys());
const counts = Array.from(data.values());
const maxCount = Math.max(...counts);
const minCount = Math.min(...counts);
const yAxisMax = Math.ceil(maxCount * 1.1);
// 创建比例尺
const xScale = (width - padding.right) / (years.length - 1);
const yScale = (height - (padding.top + padding.bottom)) / (yAxisMax - minCount);
// 计算年份标签的显示间隔
const maxLabels = 10;
const yearInterval = Math.ceil(years.length / maxLabels);
// 清空现有内容
svg.innerHTML = '';
// 创建渐变
const gradient = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient');
gradient.setAttribute('id', 'line-gradient');
gradient.setAttribute('gradientUnits', 'userSpaceOnUse');
gradient.setAttribute('x1', '0');
gradient.setAttribute('y1', '0');
gradient.setAttribute('x2', '0');
gradient.setAttribute('y2', height);
const stop1 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
stop1.setAttribute('offset', '0%');
stop1.setAttribute('stop-color', '#10b981'); // Updated color
const stop2 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
stop2.setAttribute('offset', '100%');
stop2.setAttribute('stop-color', '#10b981'); // Updated color
gradient.appendChild(stop1);
gradient.appendChild(stop2);
svg.appendChild(gradient);
// 添加X轴年份标签和参考线
years.forEach((year, index) => {
if (index === 0 || index === years.length - 1 || index % yearInterval === 0) {
const x = index * xScale;
// 添加年份标签
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', x);
text.setAttribute('y', height - padding.bottom / 2);
text.setAttribute('text-anchor', 'middle');
text.setAttribute('font-size', '12');
text.setAttribute('fill', '#86868b');
text.textContent = year;
if (yearInterval === 1 && years.length > maxLabels) {
text.setAttribute('transform', `rotate(45, ${x}, ${height - padding.bottom / 2})`);
text.setAttribute('y', height - padding.bottom / 4);
}
svg.appendChild(text);
// 添加参考线
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', x);
line.setAttribute('x2', x);
line.setAttribute('y1', padding.top);
line.setAttribute('y2', height - padding.bottom);
line.setAttribute('stroke', '#f5f5f7');
line.setAttribute('stroke-width', '1');
line.setAttribute('stroke-dasharray', '4,4');
svg.appendChild(line);
}
});
// 生成路径数据
let pathData = '';
Array.from(data.entries()).forEach(([year, count], index) => {
const x = index * xScale;
const y = height - (padding.bottom + (count - minCount) * yScale);
pathData += (index === 0 ? 'M' : 'L') + `${x},${y}`;
});
// 创建路径元素
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', pathData);
path.setAttribute('stroke', 'url(#line-gradient)');
path.setAttribute('stroke-width', '3');
path.setAttribute('fill', 'none');
path.setAttribute('stroke-linecap', 'round');
path.setAttribute('stroke-linejoin', 'round');
path.style.strokeDasharray = path.getTotalLength();
path.style.strokeDashoffset = path.getTotalLength();
path.style.animation = 'draw 1.5s ease forwards';
svg.appendChild(path);
// 添加数据点
Array.from(data.entries()).forEach(([year, count], index) => {
const x = index * xScale;
const y = height - (padding.bottom + (count - minCount) * yScale);
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', x);
circle.setAttribute('cy', y);
circle.setAttribute('r', '4');
circle.setAttribute('fill', 'white');
circle.setAttribute('stroke', '#10b981');
circle.setAttribute('stroke-width', '2');
circle.addEventListener('mouseover', (e) => {
showTooltip(e, `${year}: ${count} bookmarks`);
circle.setAttribute('r', '6');
});
circle.addEventListener('mouseout', () => {
hideTooltip();
circle.setAttribute('r', '4');
});
svg.appendChild(circle);
});
}
// 绘制Y轴
function drawYAxis(svg, data) {
const width = svg.clientWidth;
const height = svg.clientHeight;
const padding = {
top: 20,
bottom: 40
};
// 计算数据范围
const counts = Array.from(data.values());
const maxCount = Math.max(...counts);
const minCount = Math.min(...counts);
const yAxisMax = Math.ceil(maxCount * 1.1);
// 创建比例尺
const yScale = (height - (padding.top + padding.bottom)) / (yAxisMax - minCount);
// 清空现有内容
svg.innerHTML = '';
// 添加Y轴刻度
const yAxisSteps = 5;
for (let i = 0; i <= yAxisSteps; i++) {
const value = Math.round(minCount + (yAxisMax - minCount) * (i / yAxisSteps));
const y = height - (padding.bottom + (value - minCount) * yScale);
// 添加刻度线
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', 0);
line.setAttribute('x2', 5);
line.setAttribute('y1', y);
line.setAttribute('y2', y);
line.setAttribute('stroke', '#86868b');
line.setAttribute('stroke-width', '1');
svg.appendChild(line);
// 添加刻度值
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', 8);
text.setAttribute('y', y + 4);
text.setAttribute('text-anchor', 'start');
text.setAttribute('font-size', '12');
text.setAttribute('fill', '#86868b');
text.textContent = value;
svg.appendChild(text);
}
}
// 工具提示函数
function showTooltip(event, text) {
let tooltip = document.getElementById('chart-tooltip');
if (!tooltip) {
tooltip = document.createElement('div');
tooltip.id = 'chart-tooltip';
document.body.appendChild(tooltip);
}
tooltip.textContent = text;
tooltip.style.display = 'block';
tooltip.style.left = (event.pageX + 10) + 'px';
tooltip.style.top = (event.pageY - 25) + 'px';
}
function hideTooltip() {
const tooltip = document.getElementById('chart-tooltip');
if (tooltip) {
tooltip.style.display = 'none';
}
}
// 添加书签画像生成函数
async function generateBookmarkProfile(rootNode) {
try {
const profileEl = document.querySelector('.bookmark-profile');
if (!profileEl) return;
// 获取书签统计数据
const stats = await calculateBookmarkStats(rootNode);
console.log('Generated stats:', stats);
// 计算等级
const level = calculateCollectorLevel(stats);
console.log('Calculated level:', level);
// 计算各项得分 - 移到这里,在使用前先计算
const scores = calculateDetailedScores(stats);
console.log('Calculated scores:', scores);
// 更新等级显示
const levelEl = profileEl.querySelector('.level');
if (levelEl) {
if (!isNaN(level) && level > 0) {
levelEl.textContent = `Lv.${level}`;
// 添加等级计算逻辑提示
const tooltip = document.createElement('div');
tooltip.className = 'level-tooltip';
// 获取当前语言
const currentLang = chrome.i18n.getUILanguage().startsWith('zh') ? 'zh' : 'en';
// 构建提示内容
const tooltipContent = {
zh: `
<div class="tooltip-title">等级计算依据:</div>
<div class="score-details">
<div class="score-item">
<span class="score-label">书签总数:</span>
<span class="score-value">${scores.bookmarkScore}分</span>
<span class="score-calc">(${stats.totalBookmarks}个 ÷ 100)</span>
</div>
<div class="score-item">
<span class="score-label">收藏时间:</span>
<span class="score-value">${scores.timeScore}分</span>
<span class="score-calc">(${stats.timeStats.durationDays}天 ÷ 30)</span>
</div>
<div class="score-item">
<span class="score-label">组织评分:</span>
<span class="score-value">${scores.orgScore}分</span>
<span class="score-calc">(${stats.organizationScore} ÷ 2)</span>
</div>
<div class="score-item">
<span class="score-label">HTTPS比例:</span>
<span class="score-value">${scores.httpsScore}分</span>
<span class="score-calc">(${Math.round(scores.httpsRatio * 100)}% × 5)</span>
</div>
<div class="score-item">
<span class="score-label">域名多样性:</span>
<span class="score-value">${scores.domainScore}分</span>
<span class="score-calc">(${stats.uniqueDomains.size}个 ÷ 50)</span>
</div>
</div>
<div class="total-score">
总分:${scores.totalScore}分
</div>
<div class="tooltip-note">
最终等级 = log2(${scores.totalScore} + 16) + 1 = ${level}
</div>
`,
en: `
<div class="tooltip-title">Level Calculation:</div>
<div class="score-details">
<div class="score-item">
<span class="score-label">Total Bookmarks:</span>
<span class="score-value">${scores.bookmarkScore} pts</span>
<span class="score-calc">(${stats.totalBookmarks} ÷ 100)</span>
</div>
<div class="score-item">
<span class="score-label">Collection Time:</span>
<span class="score-value">${scores.timeScore} pts</span>
<span class="score-calc">(${stats.timeStats.durationDays} days ÷ 30)</span>
</div>
<div class="score-item">
<span class="score-label">Organization:</span>
<span class="score-value">${scores.orgScore} pts</span>
<span class="score-calc">(${stats.organizationScore} ÷ 2)</span>
</div>
<div class="score-item">
<span class="score-label">HTTPS Ratio:</span>
<span class="score-value">${scores.httpsScore} pts</span>
<span class="score-calc">(${Math.round(scores.httpsRatio * 100)}% × 5)</span>
</div>
<div class="score-item">
<span class="score-label">Domain Diversity:</span>
<span class="score-value">${scores.domainScore} pts</span>
<span class="score-calc">(${stats.uniqueDomains.size} ÷ 50)</span>
</div>
</div>
<div class="total-score">
Total Score: ${scores.totalScore} pts
</div>
<div class="tooltip-note">
Final Level = log2(${scores.totalScore} + 16) + 1 = ${level}
</div>
`
};
tooltip.innerHTML = tooltipContent[currentLang];
levelEl.appendChild(tooltip);
} else {
levelEl.textContent = 'Lv.1';
}
}
// 更新收藏者称号
const collectorEl = profileEl.querySelector('.collector');
if (collectorEl) {
// 获取当前语言
const currentLang = chrome.i18n.getUILanguage().startsWith('zh') ? 'zh' : 'en';
// 确保我们有有效的等级值,如果 level 未定义或无效,则默认为 1
const validLevel = (level && !isNaN(level) && level > 0) ? level : 1;
// 获取对应等级的称号
const title = COLLECTOR_TITLES[validLevel] || COLLECTOR_TITLES[1];
collectorEl.textContent = title[currentLang];
// 添加收藏者称号计算提示
const tooltip = document.createElement('div');
tooltip.className = 'collector-tooltip';
// 计算下一级所需总分
const nextLevelScore = Math.pow(2, validLevel - 1) + 15;
// 计算分数差值
const scoreDiff = nextLevelScore - scores.totalScore;
// 构建提示内容
const tooltipContent = {
zh: `
<div class="tooltip-title">收藏者称号计算:</div>
<div class="title-list">
${Object.entries(COLLECTOR_TITLES).map(([lvl, titles]) => {
const requiredScore = Math.pow(2, lvl - 1) + 15;
return `
<div class="title-item ${lvl == validLevel ? 'current' : ''}">
<span class="title-level">Lv.${lvl}</span>
<span class="title-name">${titles.zh}</span>
<span class="title-score">${requiredScore}分</span>
</div>
`;
}).join('')}
</div>
<div class="calculation-formula">
<div>称号等级计算公式:</div>
<div>所需分数 = 2^(等级-1) + 15</div>
<div>例如:Lv.6需要 2^5 + 15 = 47分</div>
</div>
`,
en: `
<div class="tooltip-title">Collector Title Calculation:</div>
<div class="title-list">
${Object.entries(COLLECTOR_TITLES).map(([lvl, titles]) => {
const requiredScore = Math.pow(2, lvl - 1) + 15;
return `
<div class="title-item ${lvl == validLevel ? 'current' : ''}">
<span class="title-level">Lv.${lvl}</span>
<span class="title-name">${titles.en}</span>
<span class="title-score">${requiredScore} pts</span>
</div>
`;
}).join('')}
</div>
<div class="calculation-formula">
<div>Title Level Calculation Formula:</div>
<div>Required Score = 2^(level-1) + 15</div>
<div>Example: Lv.6 requires 2^5 + 15 = 47 pts</div>
</div>
`
};
tooltip.innerHTML = tooltipContent[currentLang];
collectorEl.appendChild(tooltip);
}
// 更新基础统计数据
const overviewStats = profileEl.querySelector('.overview-stats');
if (overviewStats) {
overviewStats.innerHTML = `
<div class="stat-item">
<div class="stat-label">${getMessage('totalBookmarksLabel')}</div>
<div class="stat-value">${stats.totalBookmarks}</div>
</div>
<div class="stat-item">
<div class="stat-label">${getMessage('foldersLabel')}</div>
<div class="stat-value">${stats.totalFolders}</div>
</div>
<div class="stat-item">
<div class="stat-label">${getMessage('collectionDaysLabel')}</div>
<div class="stat-value">${stats.timeStats.durationDays || 0}</div>
</div>
`;
}
// 更新统计卡片
await updateStatsCards(profileEl, {
...stats,
largestFolder: {
title: stats.largestFolder.title,
count: stats.largestFolder.count + ' bookmarks' // 添加 "bookmarks" 文本
},
timeStats: {
...stats.timeStats,
oldest: new Date(stats.timeStats.oldest),
newest: new Date(stats.timeStats.newest)
}
});
// 更新域名分析
await updateDomainAnalysis(profileEl, stats);
// 更新分类标签
updateCategoryTags(profileEl, stats);
} catch (error) {
console.error('Error generating profile:', error);
throw error;
}
}
// 添加详细分数计算函数
function calculateDetailedScores(stats) {
// 书签总数得分
const bookmarkScore = Math.floor(Number(stats.totalBookmarks) / 100);
// 收藏时间得分
const timeScore = Math.floor(Number(stats.timeStats.durationDays) / 30);
// 组织度得分 - 修改除数为2而不是20,这样0-10分的组织度可以得到0-5分的等级得分
const orgScore = Math.floor(Number(stats.organizationScore) / 2);
// HTTPS比例得分
const httpsRatio = Number(stats.protocolStats?.https) /
(Number(stats.protocolStats?.https) + Number(stats.protocolStats?.http) || 1);
const httpsScore = Math.floor(httpsRatio * 5);
// 域名���样性得分
const domainScore = Math.floor(Number(stats.uniqueDomains?.size) / 50);
// 计算总分
const totalScore = bookmarkScore + timeScore + orgScore + httpsScore + domainScore;
return {
bookmarkScore,
timeScore,
orgScore,
httpsScore,
httpsRatio,
domainScore,
totalScore
};
}
// 添加特殊文件夹判断函数
function isSpecialFolder(id) {
const specialIds = ['0', '1', '2', '3']; // 根文件夹、书签栏、其他书签、移动设备书签
return specialIds.includes(id);
}
// 修改 CONFIG 对象,与 index.js 保持一致
const CONFIG = {
validProtocols: ['chrome:', 'chrome-extension:', 'file:', 'javascript:', 'data:', 'about:', 'edge:', 'brave:']
};
// 添加书签统计计算函数
async function calculateBookmarkStats(rootNode) {
const stats = {
totalBookmarks: 0,
totalFolders: 0,
maxDepth: 0,
timeStats: {
oldest: null,
newest: null,
durationDays: 0,
peakDate: null,
peakCount: 0
},
largestFolder: {
title: '',
count: 0
},
emptyFolders: 0,
domains: new Map(),
categories: new Map(),
avgBookmarksPerFolder: 0,
organizationScore: 0,
keywords: new Map(),
uniqueDomains: new Set(),
protocolStats: {
http: 0,
https: 0
},
oldestDomain: {
domain: '',
age: 0
},
oldestBookmark: null,
newestBookmark: null,
duplicateUrls: {
urlCounts: new Map(), // 存储URL及其出现次数
count: 0, // 重复的URL数量
percentage: 0 // 重复URL占比
}
};
// 添加 bookmarksByDate Map
const bookmarksByDate = new Map();
// 使用与 index.js 相同的计数方法
async function countValidBookmarks(node) {
let count = 0;
if (node.children) {
for (const child of node.children) {
if (child.url) {
// 只有当 URL 不在有效协议列表中时才计入总数
if (!CONFIG.validProtocols.some(protocol => child.url.startsWith(protocol))) {
count++;
}
} else {
count += await countValidBookmarks(child);
}
}
}
return count;
}
// 设置总书签数
stats.totalBookmarks = await countValidBookmarks(rootNode);
function traverse(node, depth = 0) {
if (!node) return;
if (node.children) {
// 只有非特殊文件夹才计入统计
if (node.id && !isSpecialFolder(node.id)) {
stats.totalFolders++;
stats.maxDepth = Math.max(stats.maxDepth, depth);
// 修改:计算当前文件夹中的书签数量
let folderBookmarks = 0;
let hasSubfolders = false;
node.children.forEach(child => {
if (child.url) {
folderBookmarks++;
} else if (child.children) {
hasSubfolders = true;
}
});
// 更新最大文件夹统计
if (folderBookmarks > stats.largestFolder.count) {
stats.largestFolder = {
title: node.title || 'Unnamed Folder',
count: folderBookmarks
};
}
// 更新空文件夹计数
if (folderBookmarks === 0 && !hasSubfolders) {
stats.emptyFolders++;
}
}
node.children.forEach(child => traverse(child, depth + 1));
}
if (node.url) {
// 只有当 URL 不在有效协议列表中时才计入总数
if (!CONFIG.validProtocols.some(protocol => node.url.startsWith(protocol))) {
// 添加日期验证
let dateAdded;
try {
// 确保 dateAdded 是有效的时间戳
if (node.dateAdded && !isNaN(node.dateAdded)) {
dateAdded = new Date(node.dateAdded);
// 验证日期是否有效
if (dateAdded.toString() === 'Invalid Date') {
dateAdded = new Date(); // 使用当前日期作为后备
}
} else {
dateAdded = new Date(); // 使用当前日期作为后备
}
// 更新时间统计
if (!stats.timeStats.oldest || dateAdded < stats.timeStats.oldest) {
stats.timeStats.oldest = dateAdded;
stats.oldestBookmark = {
url: node.url,
title: node.title,
dateAdded: dateAdded
};
}
if (!stats.timeStats.newest || dateAdded > stats.timeStats.newest) {
stats.timeStats.newest = dateAdded;
stats.newestBookmark = {
url: node.url,
title: node.title,
dateAdded: dateAdded
};
}
// 统计每日书签数量
try {
const dateKey = dateAdded.toISOString().split('T')[0];
bookmarksByDate.set(dateKey, (bookmarksByDate.get(dateKey) || 0) + 1);
} catch (e) {
console.warn('Error creating date key for bookmark:', e);
}
} catch (e) {
console.warn('Error processing date for bookmark:', node.url, e);
}
// 统计域名和协议
try {
const url = new URL(node.url);