-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent_copy.js
More file actions
6620 lines (5768 loc) · 277 KB
/
content_copy.js
File metadata and controls
6620 lines (5768 loc) · 277 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
// DeepRead 深度阅读助手 - 内容脚本
// 负责在页面上创建 UI并处理交互
// 加载 LLM API 脚本
// (function loadLLMScript() {
// const script = document.createElement('script');
// script.src = chrome.runtime.getURL('extensions/llm-api.js');
// script.onload = function() {
// console.log('LLM API 脚本加载成功');
// };
// document.head.appendChild(script);
// })();
// 添加调试信息
console.log('DeepRead content script loaded!');
// 检测是否在Chrome扩展环境中
const isExtensionEnvironment = typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.id;
// gemini-2.5-flash-lite gemini-flash-lite-latest gemini-3-flash-preview
const MODEL_ID = 'gemini-3-flash-preview'
const PROVIDER = 'google'
const default_bot_language = '中文'
const greetingMessage = '您好!我是DeepRead助手。您可以向我提问有关本页面内容的问题,我将尽力为您解答。';
const pageSummaryFallback = '抱歉,我暂时无法分析页面内容。请稍后再试。';
const conceptExplanationFallback = '的解释暂时无法获取。请稍后再试。';
const chatResponseFallback = '关于您的问题,我暂时无法回答。请稍后再试。';
const imageGenerationFallback = '生成图像失败,请稍后再试。';
// 获取当前页面URL
const currentUrl = window.location.href;
// API_URL = `https://openrouter.ai/api/v1/chat/completions`;
const API_BASE_URL = `https://generativelanguage.googleapis.com/v1beta/models/`;
// 页面分析状态
let pageAnalyzed = false; // 标记页面是否已经分析过
let pageTitle = document.title;
let pageContent = ''; // 存储页面内容
let pageSummary = ''; // 存储页面摘要
let pageKeyTerms = []; // 存储页面关键概念
let pageKeyParagraphs = []; // 存储页面关键段落
// 追加导入去重:本标签页内避免重复追加同一份导出
let importedExportIds = new Set();
// 聊天历史
let chatHistory = [];
const CHAT_PERSIST_ENABLED = true;
let deepreadTabId = null;
const TAB_CHAT_KEY_PREFIX = 'deepread_chat_history_tab_';
// 概念查询历史
let conceptHistory = [];
let currentConceptIndex = -1; // 当前浏览的概念索引
let highlightHistory = []; // 用户划线历史(独立于 conceptHistory)
let lastSelectionRange = null;
let lastSelectionParagraphId = null;
let lastSelectionOffsets = null;
let selectedHighlightId = null;
function isDeepReadMinimapPinned(){
try{
return localStorage.getItem('deepread_minimap_pinned') === '1';
}catch{
return false;
}
}
function exportChatHistoryForImport() {
try {
if (!chatHistory || chatHistory.length === 0) {
alert('当前没有可复制的对话内容。');
return;
}
const exportData = {
schema: 'deepread.chat.export.v1',
exportId: generateUniqueId(),
exportedAt: Date.now(),
source: {
url: currentUrl || window.location.href,
title: document.title || '',
},
messages: chatHistory.map((item) => ({
id: item.messageId || generateUniqueId(),
role: item.role === 'user' ? 'user' : 'assistant',
content: String(item.rawMessage || item.message || '').trim(),
})),
};
const jsonText = JSON.stringify(exportData);
navigator.clipboard.writeText(jsonText)
.then(() => {
alert('已复制可导入对话到剪贴板。');
})
.catch((err) => {
console.error('复制失败:', err);
alert('复制失败,请手动复制。');
});
} catch (error) {
console.error('复制可导入对话时出错:', error);
alert('复制对话时出错,请稍后重试。');
}
}
async function appendImportedChatFromClipboard() {
try {
const text = await navigator.clipboard.readText();
if (!text || !text.trim()) {
alert('剪贴板为空,无法导入。');
return;
}
let data;
try {
data = JSON.parse(text);
} catch (e) {
alert('剪贴板内容不是有效 JSON,无法导入。');
return;
}
if (!data || data.schema !== 'deepread.chat.export.v1') {
alert('剪贴板内容不是 DeepRead 可导入对话格式。');
return;
}
if (!Array.isArray(data.messages) || data.messages.length === 0) {
alert('导入内容中没有 messages。');
return;
}
const exportId = String(data.exportId || '');
if (exportId && importedExportIds.has(exportId)) {
alert('该对话已在本标签页导入过,已跳过。');
return;
}
const sourceTitle = (data.source && data.source.title) ? String(data.source.title) : '';
const sourceUrl = (data.source && data.source.url) ? String(data.source.url) : '';
const timeStr = new Date().toLocaleString();
const header = `【合并对话】来源:《${sourceTitle || '未命名页面'}》\nURL: ${sourceUrl || '未知'}\n导入时间: ${timeStr}\n(以下为该页面的完整历史对话,原样追加)`;
addChatMessage(header, 'assistant', false, true);
data.messages.forEach((m) => {
const role = (m && m.role === 'user') ? 'user' : 'assistant';
const content = (m && typeof m.content === 'string') ? m.content : '';
addChatMessage(content, role, false, true, [], content);
});
if (exportId) importedExportIds.add(exportId);
alert('对话已追加导入。');
} catch (error) {
console.error('追加导入对话时出错:', error);
alert('导入失败:可能缺少剪贴板权限或格式不正确。');
}
}
async function ensurePageAnalyzedHydratedForExplain(){
try{
if (pageAnalyzed) return true;
if (!window.cacheManager || typeof window.cacheManager.loadPageContent !== 'function') return false;
const url = window.location.href;
const cachedPageContent = await window.cacheManager.loadPageContent(url);
if (!cachedPageContent) return false;
const nextPageContent = cachedPageContent.content || '';
const nextPageSummary = cachedPageContent.summary || '';
const nextPageKeyTerms = cachedPageContent.keyTerms || [];
const nextPageKeyParagraphs = cachedPageContent.keyParagraphs || [];
const contentValid = nextPageContent
&& nextPageContent.length > 0
&& nextPageSummary
&& nextPageSummary.length > 0
&& nextPageSummary != pageSummaryFallback
&& nextPageKeyTerms
&& nextPageKeyTerms.length > 0
&& nextPageKeyParagraphs
&& nextPageKeyParagraphs.length > 0;
if (!contentValid) return false;
pageContent = nextPageContent;
pageSummary = nextPageSummary;
pageKeyTerms = nextPageKeyTerms;
pageKeyParagraphs = nextPageKeyParagraphs;
pageAnalyzed = true;
try{
await window.cacheManager.savePageAnalyzedStatus(url, true);
}catch{}
return true;
}catch(err){
console.warn('DeepRead: ensurePageAnalyzedHydratedForExplain 失败:', err);
return false;
}
}
function setDeepReadMinimapPinned(v){
try{
localStorage.setItem('deepread_minimap_pinned', v ? '1' : '0');
}catch{}
}
function hideDeepReadMinimapPinned(){
const minimap = document.getElementById('deepread-minimap');
if (!minimap) return;
minimap.classList.add('deepread-hidden');
setDeepReadMinimapPinned(false);
}
function showDeepReadMinimapPinned(restore = true){
const minimap = ensureDeepReadMinimap();
if (!minimap) return null;
minimap.classList.remove('deepread-hidden');
setDeepReadMinimapPinned(true);
if (restore){
restoreHighlightsFromCacheAndRender().catch(err => console.warn('恢复划线失败:', err));
}
return minimap;
}
function findParagraphEl(pid){
if (!pid) return null;
try{
const direct = document.getElementById(pid);
if (direct) return direct;
const esc = (typeof CSS !== 'undefined' && CSS.escape) ? CSS.escape(pid) : String(pid).replace(/"/g, '\\"');
const byData = document.querySelector(`[data-dr-paragraph-id="${esc}"]`);
if (byData) return byData;
}catch{}
return null;
}
function updateMinimapUIIfVisible({ previewText = '', previewHid = null } = {}){
const minimap = document.getElementById('deepread-minimap') || null;
if (!minimap || minimap.classList.contains('deepread-hidden')) return;
try{
renderHighlightMinimapDots();
updateDeepReadMinimapViewport();
if (previewHid){
setHighlightPreviewText(previewText || '', previewHid);
}
}catch(err){
console.warn('DeepRead: 刷新 minimap 失败:', err);
}
}
async function ensureParagraphIdsReadyForHighlights(highlights){
// 只有当 highlight 使用 paragraph-* 体系时才需要(否则一般是网页原生 id,可直接定位)
const hs = Array.isArray(highlights) ? highlights : [];
const needsParagraphIds = hs.some(h => h && typeof h.paragraphId === 'string' && h.paragraphId.startsWith('paragraph-'));
if (!needsParagraphIds) return;
// 如果已经有段落标记(存在任意 data-dr-paragraph-id="paragraph-0"),则认为已就绪
if (document.querySelector('[data-dr-paragraph-id^="paragraph-"]')) return;
// 避免重复执行导致卡顿
if (window.__deepreadParagraphIdsReady) return;
if (window.__deepreadParagraphIdsPromise) {
try { await window.__deepreadParagraphIdsPromise; } catch {}
return;
}
window.__deepreadParagraphIdsPromise = (async () => {
try{
await addParagraphIds();
window.__deepreadParagraphIdsReady = true;
} finally {
window.__deepreadParagraphIdsPromise = null;
}
})();
try{
await window.__deepreadParagraphIdsPromise;
}catch(err){
console.warn('DeepRead: 自动补段落ID失败(用于恢复划线):', err);
}
}
// 当页面加载完成后初始化 2秒
window.addEventListener('load', function() {
// 在Chrome扩展环境中,等待一小段时间再初始化,确保页面完全加载
setTimeout(init, 2000);
});
// 添加清除缓存的快捷键函数
function setupClearCacheShortcut() {
document.addEventListener('keydown', async function(event) {
// Alt+Shift+C 组合键清除缓存
if (event.altKey && event.shiftKey && event.key === 'C') {
console.log('检测到清除缓存快捷键 Alt+Shift+C');
try {
if (window.cacheManager && window.cacheManager.clearAllCache) {
const result = await window.cacheManager.clearAllCache();
if (result) {
console.log('缓存已成功清除');
alert('缓存已成功清除,请刷新页面以应用更改。');
// 重置状态
pageAnalyzed = false;
pageSummary = '';
pageKeyTerms = [];
pageKeyParagraphs = [];
chatHistory = [];
conceptHistory = [];
currentConceptIndex = -1;
} else {
console.error('清除缓存失败');
alert('清除缓存失败,请查看控制台了解详情。');
}
} else {
console.error('缓存管理器不可用或缺少clearAllCache函数');
alert('缓存管理器不可用,请刷新页面后重试。');
}
} catch (error) {
console.error('清除缓存时出错:', error);
alert('清除缓存时出错: ' + error.message);
}
}
});
console.log('DeepRead: 已设置清除缓存快捷键 Alt+Shift+C');
}
// Highlight 控制函数
function normalizeRangeOffsets(a, b){
const s = Math.min(a, b);
const e = Math.max(a, b);
return { start: s, end: e };
}
function generateHighlightId(){
return `hl_${Date.now()}_${Math.random().toString(16).slice(2)}`;
}
function unwrapSpan(el){
if (!el) return;
const text = document.createTextNode(el.textContent || '');
el.replaceWith(text);
}
function getUserHighlightElById(hid){
if (!hid) return null;
return document.querySelector(`.deepread-user-highlight[data-hid="${hid}"]`);
}
function isEditableTarget(target){
if (!target) return false;
const el = target.nodeType === Node.ELEMENT_NODE ? target : target.parentElement;
if (!el) return false;
if (el.isContentEditable) return true;
const tag = (el.tagName || '').toUpperCase();
return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
}
function setSelectedHighlightId(hid){
selectedHighlightId = hid || null;
document.querySelectorAll('.deepread-user-highlight.deepread-user-highlight-selected').forEach(el => {
el.classList.remove('deepread-user-highlight-selected');
});
if (selectedHighlightId){
const el = getUserHighlightElById(selectedHighlightId);
if (el) el.classList.add('deepread-user-highlight-selected');
}
}
function showFloatActionsForExistingHighlight({ x, y, highlight, paragraphId } = {}){
try{
const existingButtons = document.querySelectorAll('.deepread-float-button');
existingButtons.forEach(button => {
try{ if (document.body.contains(button)) document.body.removeChild(button); }catch{}
});
const floatButton = document.createElement('div');
floatButton.className = 'deepread-float-button';
floatButton.title = 'DeepRead';
floatButton.innerHTML = `
<button class="deepread-float-action deepread-float-highlight" type="button" title="划线">划线</button>
<button class="deepread-float-action deepread-float-explain" type="button" title="解释">解释</button>
`;
floatButton.style.left = (Number(x || 0) + 10) + 'px';
floatButton.style.top = (Number(y || 0) + 10) + 'px';
floatButton.addEventListener('mousedown', function(e) {
e.stopPropagation();
});
const btnHighlight = floatButton.querySelector('.deepread-float-highlight');
const btnExplain = floatButton.querySelector('.deepread-float-explain');
if (btnHighlight){
// 对“已存在的划线”再次点击划线按钮:无动作(仅关闭浮窗)
btnHighlight.addEventListener('click', function(e){
e.stopPropagation();
e.preventDefault();
try{ floatButton.remove(); }catch{}
});
}
if (btnExplain){
btnExplain.addEventListener('click', function(e){
e.stopPropagation();
e.preventDefault();
try{ floatButton.remove(); }catch{}
const text = String((highlight && highlight.text) || '').trim();
if (!text) return;
const anchorData = { paragraphId: paragraphId || (highlight && highlight.paragraphId) };
if (highlight && typeof highlight.start === 'number' && typeof highlight.end === 'number'){
anchorData.start = highlight.start;
anchorData.end = highlight.end;
anchorData.text = highlight.text;
}
openDeepReadWithConcept(text, anchorData);
});
}
document.body.appendChild(floatButton);
}catch(err){
console.warn('DeepRead: showFloatActionsForExistingHighlight failed:', err);
}
}
function showDeepReadToast(text, type = 'info'){
try{
const toast = document.createElement('div');
toast.textContent = String(text || '');
toast.style.position = 'fixed';
toast.style.top = '18px';
toast.style.left = '50%';
toast.style.transform = 'translateX(-50%)';
toast.style.backgroundColor = type === 'success' ? 'rgba(33, 150, 243, 0.92)' : (type === 'error' ? 'rgba(244, 67, 54, 0.92)' : 'rgba(0, 0, 0, 0.78)');
toast.style.color = 'white';
toast.style.padding = '8px 14px';
toast.style.borderRadius = '10px';
toast.style.zIndex = '10000';
toast.style.maxWidth = '80vw';
toast.style.fontSize = '12px';
toast.style.lineHeight = '1.3';
document.body.appendChild(toast);
setTimeout(() => {
try{ toast.remove(); }catch{}
}, 1600);
}catch{}
}
// 发送笔记到飞书
function getDeepReadFeishuWebhookUrl(){
try{
return (localStorage.getItem('deepread_feishu_webhook_url') || '').trim();
}catch{
return '';
}
}
async function copyHighlightToClipboard(highlight){
if (!highlight) {
showDeepReadToast('没有可复制的划线内容', 'error');
return;
}
const text = String(highlight.text || '').trim();
try{
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(text);
} else {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.left = '-9999px';
ta.style.top = '-9999px';
document.body.appendChild(ta);
ta.focus();
ta.select();
document.execCommand('copy');
ta.remove();
}
showDeepReadToast('已复制', 'success');
} catch (err) {
console.warn('DeepRead: 复制失败:', err);
showDeepReadToast('复制失败', 'error');
}
}
async function sendHighlightToFeishu(highlight){
const webhookUrl = getDeepReadFeishuWebhookUrl();
if (!webhookUrl){
showDeepReadToast('请先配置 deepread_feishu_webhook_url', 'error');
return;
}
if (!highlight || !highlight.text){
showDeepReadToast('没有可发送的划线内容', 'error');
return;
}
const title = (document && document.title) ? document.title : '';
const url = window.location.href;
const ideaText = String(highlight.text || '').trim();
const payload = { title, idea: ideaText, url };
try{
const resp = await chrome.runtime.sendMessage({
action: 'deepread_send_feishu_webhook',
webhookUrl,
payload
});
if (!resp || !resp.ok) throw new Error(resp && resp.error ? resp.error : 'unknown');
showDeepReadToast('已发送', 'success');
}catch(err){
console.warn('DeepRead: 发送到飞书失败:', err);
showDeepReadToast('发送失败', 'error');
}
}
function bindUserHighlightSelectionAndDelete(){
document.addEventListener('click', (e) => {
const target = e.target;
const sp = target && target.closest ? target.closest('.deepread-user-highlight[data-hid]') : null;
if (!sp) return;
const hid = sp.getAttribute('data-hid');
if (!hid) return;
setSelectedHighlightId(hid);
const h = (Array.isArray(highlightHistory) ? highlightHistory : []).find(x => x && x.id === hid);
setHighlightPreviewText((h && h.text) ? h.text : (sp.textContent || ''), hid);
// 点击已划线文本时,弹出“划线/解释”按钮,方便直接解释
showFloatActionsForExistingHighlight({
x: e.pageX,
y: e.pageY,
highlight: h || { id: hid, paragraphId: sp.getAttribute('data-pid') || null, text: sp.textContent || '' },
paragraphId: (h && h.paragraphId) ? h.paragraphId : (sp.getAttribute('data-pid') || null)
});
e.preventDefault();
e.stopPropagation();
}, true);
document.addEventListener('click', async (e) => {
const sendBtn = e.target && e.target.closest ? e.target.closest('#deepreadMinimapActions .deepread-minimap-send') : null;
if (sendBtn){
const box = document.getElementById('deepreadMinimapPreview');
const hid = box ? (box.getAttribute('data-hid') || '') : '';
if (hid){
const h = (Array.isArray(highlightHistory) ? highlightHistory : []).find(x => x && x.id === hid);
await sendHighlightToFeishu(h);
}
e.preventDefault();
e.stopPropagation();
return;
}
const copyBtn = e.target && e.target.closest ? e.target.closest('#deepreadMinimapActions .deepread-minimap-copy') : null;
if (copyBtn){
const box = document.getElementById('deepreadMinimapPreview');
const hid = box ? (box.getAttribute('data-hid') || '') : '';
if (hid){
const h = (Array.isArray(highlightHistory) ? highlightHistory : []).find(x => x && x.id === hid);
await copyHighlightToClipboard(h);
}
e.preventDefault();
e.stopPropagation();
return;
}
});
document.addEventListener('keydown', async (e) => {
if (e.key !== 'Backspace' && e.key !== 'Delete') return;
if (!selectedHighlightId) return;
if (isEditableTarget(e.target)) return;
await deleteHighlightById(selectedHighlightId);
e.preventDefault();
e.stopPropagation();
});
}
function setHighlightPreview(text, hid){
const el = document.getElementById('deepreadMinimapPreview');
if (!el) return;
const safeText = (text || '').toString();
const hasId = !!hid;
el.setAttribute('data-hid', hasId ? String(hid) : '');
el.innerHTML = `
<div class="deepread-minimap-preview-text"></div>
`;
const textEl = el.querySelector('.deepread-minimap-preview-text');
if (textEl) textEl.textContent = safeText;
const sendBtn = document.querySelector('#deepreadMinimapActions .deepread-minimap-send');
const copyBtn = document.querySelector('#deepreadMinimapActions .deepread-minimap-copy');
if (sendBtn) sendBtn.disabled = !hasId;
if (copyBtn) copyBtn.disabled = !hasId;
}
async function deleteHighlightById(hid){
if (!hid) return;
const span = getUserHighlightElById(hid);
if (span) unwrapSpan(span);
highlightHistory = Array.isArray(highlightHistory) ? highlightHistory : [];
highlightHistory = highlightHistory.filter(h => h && h.id !== hid);
try{
await saveHighlightsToCache();
}catch(err){
console.warn('删除划线缓存失败:', err);
}
setSelectedHighlightId(null);
setHighlightPreview('', null);
updateMinimapUIIfVisible();
}
function wrapHighlightInParagraph(paragraphEl, highlight){
if (!paragraphEl || !highlight) return null;
if (typeof highlight.start !== 'number' || typeof highlight.end !== 'number') return null;
const fullTextLen = (paragraphEl.textContent || '').length;
const s = Math.max(0, Math.min(fullTextLen, highlight.start));
const e = Math.max(0, Math.min(fullTextLen, highlight.end));
if (e <= s) return null;
// 覆盖策略:移除与 [s,e) 有重叠的旧划线
const spans = Array.from(paragraphEl.querySelectorAll('.deepread-user-highlight[data-hid]'));
for (const sp of spans){
const spStart = Number(sp.getAttribute('data-start'));
const spEnd = Number(sp.getAttribute('data-end'));
if (!Number.isFinite(spStart) || !Number.isFinite(spEnd)) continue;
const overlap = !(e <= spStart || s >= spEnd);
if (overlap) unwrapSpan(sp);
}
const startLoc = nodeAtOffset(paragraphEl, s);
const endLoc = nodeAtOffset(paragraphEl, e);
if (!startLoc || !endLoc) return null;
const range = document.createRange();
range.setStart(startLoc.node, startLoc.offset);
range.setEnd(endLoc.node, endLoc.offset);
const selectedText = (range.toString() || '').trim();
if (!selectedText) return null;
const span = document.createElement('span');
span.className = 'deepread-user-highlight';
span.setAttribute('data-hid', highlight.id);
span.setAttribute('data-pid', highlight.paragraphId);
span.setAttribute('data-start', String(s));
span.setAttribute('data-end', String(e));
const frag = range.extractContents();
span.appendChild(frag);
range.insertNode(span);
return span;
}
async function saveHighlightsToCache(){
if (!window.cacheManager || !window.cacheManager.saveHighlights) return;
const url = window.location.href;
await window.cacheManager.saveHighlights(url, highlightHistory || []);
}
function buildHighlightsExportText(){
const title = (document && document.title) ? String(document.title).trim() : '';
const url = window.location.href;
const highlights = (Array.isArray(highlightHistory) ? highlightHistory : [])
.filter(h => h && typeof h.text === 'string' && h.text.trim())
.map(h => h.text.trim());
const parts = [];
if (title) parts.push(title);
parts.push(url);
parts.push('');
parts.push(...highlights);
return parts.join('\n\n');
}
function downloadTextFile(filename, text){
const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(() => {
try{ URL.revokeObjectURL(a.href); }catch{}
try{ a.remove(); }catch{}
}, 0);
}
async function deleteAllHighlights(){
const ids = (Array.isArray(highlightHistory) ? highlightHistory : []).map(h => h && h.id).filter(Boolean);
for (const hid of ids){
const span = getUserHighlightElById(hid);
if (span) unwrapSpan(span);
}
highlightHistory = [];
selectedHighlightId = null;
try{
await saveHighlightsToCache();
}catch(err){
console.warn('清空划线缓存失败:', err);
}
updateMinimapUIIfVisible({ previewText: '', previewHid: '' });
}
async function loadHighlightsFromCache(){
if (!window.cacheManager || !window.cacheManager.loadHighlights) return [];
const url = window.location.href;
return await window.cacheManager.loadHighlights(url);
}
function clearTransientConceptHighlight(){
document.querySelectorAll('.deepread-precise-highlight').forEach(el => {
unwrapSpan(el);
});
document.querySelectorAll('.deepread-highlight').forEach(el => {
el.classList.remove('deepread-highlight');
});
}
function setHighlightPreviewText(text, hid){
setHighlightPreview(text, hid);
}
function renderHighlightMinimapDots(){
const minimap = document.getElementById('deepread-minimap');
if (!minimap || minimap.classList.contains('deepread-hidden')) return;
const bar = minimap.querySelector('#deepreadMinimapBar');
const countEl = minimap.querySelector('#deepreadMinimapCount');
const exportBtn = minimap.querySelector('#deepreadMinimapExport');
if (!bar) return;
bar.querySelectorAll('.deepread-minimap-dot').forEach(d => d.remove());
const highlights = Array.isArray(highlightHistory) ? highlightHistory : [];
if (countEl) countEl.textContent = String(highlights.length);
if (exportBtn) exportBtn.disabled = highlights.length === 0;
const docH = Math.max(1, document.documentElement.scrollHeight);
const barH = bar.getBoundingClientRect().height || 1;
const topPad = 10;
const bottomPad = 14;
const usableH = Math.max(1, barH - topPad - bottomPad);
for (const h of highlights){
if (!h || !h.paragraphId) continue;
const el = findParagraphEl(h.paragraphId);
if (!el) continue;
const top = el.getBoundingClientRect().top + window.scrollY;
const ratio = Math.max(0, Math.min(1, top / docH));
const topPx = Math.round(topPad + ratio * usableH);
const dot = document.createElement('div');
dot.className = 'deepread-minimap-dot';
dot.setAttribute('data-hid', h.id);
dot.style.background = 'rgba(76, 175, 80, 0.95)';
dot.style.top = `${Math.max(topPad, Math.min(barH - bottomPad, topPx))}px`;
// hover: 仅预览,不跳转
dot.addEventListener('mouseenter', () => {
setHighlightPreviewText(h.text || '', h.id);
});
dot.addEventListener('mouseleave', () => {
if (selectedHighlightId){
const cur = (Array.isArray(highlightHistory) ? highlightHistory : []).find(x => x && x.id === selectedHighlightId);
setHighlightPreviewText((cur && cur.text) ? cur.text : '', selectedHighlightId);
} else {
setHighlightPreviewText('', '');
}
});
dot.addEventListener('click', () => {
const target = findParagraphEl(h.paragraphId);
if (target){
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
setSelectedHighlightId(h.id);
setHighlightPreviewText(h.text || '', h.id);
clearTransientConceptHighlight();
});
bar.appendChild(dot);
}
}
async function restoreHighlightsFromCacheAndRender(){
// 1) load cache -> memory
const cached = await loadHighlightsFromCache();
if (Array.isArray(cached)) highlightHistory = cached;
// 1.5) 确保 paragraph-* 体系可定位(在不打开右侧面板时也能恢复高亮/dots)
await ensureParagraphIdsReadyForHighlights(highlightHistory);
// 2) restore DOM wraps
for (const h of (highlightHistory || [])){
if (!h || !h.id || !h.paragraphId) continue;
if (getUserHighlightElById(h.id)) continue; // avoid double wrap
const paragraphEl = findParagraphEl(h.paragraphId);
if (!paragraphEl) continue;
try{
wrapHighlightInParagraph(paragraphEl, h);
}catch(err){
console.warn('恢复单条划线失败:', h && h.id, err);
}
}
renderHighlightMinimapDots();
updateDeepReadMinimapViewport();
}
// Highlight 控制函数结束
// 初始化 注意:不要再这个init方法里自动展开面板,
// 这会导致打开新页面或页面刷新时,助手(作为chrome插件)自动打开,对用户体验不好
// 只有用户主动点击助手进行操作时,才打开面板,
// 具体方法是:if (isExtensionEnvironment) { chrome.runtime.onMessage.addListener
async function init() {
console.log('DeepRead 初始化中...');
// 设置清除缓存的快捷键
setupClearCacheShortcut();
// 绑定划线选中/删除(防止重复绑定)
if (!window.__deepreadUserHighlightDeleteBound){
try{
bindUserHighlightSelectionAndDelete();
window.__deepreadUserHighlightDeleteBound = true;
}catch(err){
console.warn('DeepRead: 绑定划线删除事件失败:', err);
}
}
if (!window.__deepreadSelectionListenerBound){
try{
addTextSelectionListener();
window.__deepreadSelectionListenerBound = true;
}catch(err){
console.warn('DeepRead: 绑定文本选择浮窗失败:', err);
}
}
// 从缓存加载数据
if (window.cacheManager) {
try {
// 获取当前页面URL
const currentUrl = window.location.href;
// 加载概念查询历史
const cachedConceptHistory = await window.cacheManager.loadConceptHistory();
if (cachedConceptHistory && cachedConceptHistory.length > 0) {
conceptHistory = cachedConceptHistory;
currentConceptIndex = await window.cacheManager.getCurrentConceptIndex();
debugLog(`从缓存加载了 ${conceptHistory.length} 条概念查询记录,当前索引: ${currentConceptIndex}`);
}
// 加载聊天历史
if (CHAT_PERSIST_ENABLED) {
const cachedChatHistory = await loadTabChatHistory();
if (cachedChatHistory && cachedChatHistory.length > 0) {
chatHistory = cachedChatHistory;
debugLog(`从缓存加载了 ${chatHistory.length} 条聊天记录`);
}
}
// 加载用户划线(仅加载到内存;恢复 DOM 在面板打开时执行)
const cachedHighlights = await window.cacheManager.loadHighlights(currentUrl);
if (cachedHighlights && cachedHighlights.length > 0) {
highlightHistory = cachedHighlights;
debugLog(`从缓存加载了 ${highlightHistory.length} 条划线记录`);
}
// 左侧 minimap 一旦打开后常驻:若之前 pinned,则页面刷新后自动恢复显示
if (isDeepReadMinimapPinned()){
showDeepReadMinimapPinned(true);
}
// 加载页面内容
const cachedPageContent = await window.cacheManager.loadPageContent(currentUrl);
if (cachedPageContent) {
// 更新页面内容变量
pageContent = cachedPageContent.content || '';
pageSummary = cachedPageContent.summary || '';
pageKeyTerms = cachedPageContent.keyTerms || [];
pageKeyParagraphs = cachedPageContent.keyParagraphs || [];
// 加载当前页面的分析状态
// pageAnalyzed = await window.cacheManager.loadPageAnalyzedStatus(currentUrl);
// console.log('当前页面分析状态:', pageAnalyzed);
// 检查缓存内容是否有效
const contentValid = pageContent
&& pageContent.length > 0
&& pageSummary
&& pageSummary.length > 0
&& pageSummary != pageSummaryFallback
&& pageKeyTerms
&& pageKeyTerms.length > 0
&& pageKeyParagraphs
&& pageKeyParagraphs.length > 0;
// 如果缓存内容有效,更新页面分析状态
if (contentValid) {
// 更新内存中的状态
pageAnalyzed = true;
// 同时更新缓存中的状态
await window.cacheManager.savePageAnalyzedStatus(currentUrl, true);
console.log('缓存内容有效,设置pageAnalyzed = true');
console.log('摘要长度:', pageSummary.length, '关键概念数量:', pageKeyTerms.length, '关键段落数量:', pageKeyParagraphs.length);
} else {
// 如果缓存内容无效,确保页面分析状态为false
pageAnalyzed = false;
await window.cacheManager.savePageAnalyzedStatus(currentUrl, false);
console.log('缓存内容无效: "', pageSummary, '", 设置pageAnalyzed = false');
}
} else {
console.log('没有找到当前页面的缓存内容');
// 确保页面分析状态为false
pageAnalyzed = false;
await window.cacheManager.savePageAnalyzedStatus(currentUrl, false);
}
} catch (error) {
console.error('从缓存加载数据时出错:', error);
// 出错时确保页面分析状态为false
pageAnalyzed = false;
try {
await window.cacheManager.savePageAnalyzedStatus(currentUrl, false);
} catch (e) {
console.error('保存页面分析状态时出错:', e);
}
}
}
}
// 如果在Chrome扩展环境中,添加消息监听器
// 这段代码是扩展功能的重要组成部分,它连接了扩展的弹出界面和内容脚本,使用户能够通过点击扩展图标和按钮来控制DeepRead功能。
if (isExtensionEnvironment) {
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log('Content script received message:', request);
if (request.action === 'startReading') {
console.log('收到startReading消息');
// 检查页面是否已经分析过
if (pageAnalyzed) {
console.log('页面已经分析过,直接显示结果');
// 确保面板存在
if (!document.getElementById('deepread-container')) {
createDeepReadPanel();
// addParagraphIds();
addTextSelectionListener();
}
// 显示面板
toggleDeepReadPanel();
// popup “开始深度阅读”明确要求打开 minimap(即使用户之前关闭过)
showDeepReadMinimapPinned(true);
addParagraphIds();
// 再次从缓存加载页面内容
window.cacheManager.loadPageContent(currentUrl)
.then(cachedPageContent => {
if (cachedPageContent && cachedPageContent.summary && cachedPageContent.keyTerms) {
console.log('加载全文分析缓存,关键概念数量:', cachedPageContent.keyTerms.length);
// 更新全局变量
pageSummary = cachedPageContent.summary;
pageKeyTerms = cachedPageContent.keyTerms;
pageKeyParagraphs = cachedPageContent.keyParagraphs;
} else {
console.log('缓存加载失败或缓存内容不完整,使用当前内存中的数据');
}
// 全文分析结果
showAnalysisResults({
summary: pageSummary,
keyTerms: pageKeyTerms,
keyParagraphs: pageKeyParagraphs
});
})
.catch(error => {
console.error('加载缓存内容失败:', error);
// 出错时使用当前内存中的数据
showAnalysisResults({
summary: pageSummary,
keyTerms: pageKeyTerms,
keyParagraphs: pageKeyParagraphs
});
});
sendResponse({status: 'success', message: '从缓存恢复分析结果'});
} else {
console.log('页面没有分析过,Starting deep reading...');
// 创建面板,让用户预览内容并手动确认分析
createDeepReadPanel();
// 添加文本选择事件监听
addTextSelectionListener();
// 显示面板