-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
6348 lines (5533 loc) · 213 KB
/
content.js
File metadata and controls
6348 lines (5533 loc) · 213 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
// 截圖翻譯器內容腳本
console.log('Content script loading...');
// 內置翻譯表(content script 無法訪問 popup 的 i18n.js)
// 使用 window 避免與頁面腳本衝突
window.qt_contentTranslations = {
'zh-CN': {
'quick.btn.translate': '翻译',
'quick.panel.title': '快速翻译',
'quick.panel.original': '原文',
'quick.panel.translated': '译文',
'quick.btn.copy': '复制',
'quick.btn.save': '收藏',
'quick.msg.copied': '已复制',
'quick.msg.saved': '已收藏',
'quick.msg.translating': '翻译中...',
'quick.msg.capturing': '正在截取区域...',
'quick.msg.translatingInProgress': '正在翻译...',
'quick.msg.ocr': '正在截图识别...',
'quick.hint.hover': '悬停翻译',
'quick.hint.dragToSelect': '拖拽选择要翻译的区域,或点击使用默认区域,按 ESC 取消',
'quick.hint.smartMode': '智能翻译模式\n自动检测语言 → 中文\n拖拽选择要翻译的区域,按 ESC 取消',
'quick.hint.clickToCopy': '点击复制各引擎结果',
'quick.hint.multiSuccess': '{success}个成功,{error}个失败',
'quick.hint.allFailed': '所有引擎均失败',
'quick.error.noText': '未识别到文字',
'quick.error.screenshotFailed': '截图失败',
'quick.error.processFailed': '处理失败',
'quick.error.ocrNoText': '图片中没有找到可识别的文字,请尝试选择包含清晰文字的区域',
'quick.result.title': '翻译结果(可拖动)',
'quick.result.recognized': '识别文字',
'quick.result.translated': '翻译结果',
'engine.google': 'Google 翻译',
'engine.microsoft': 'Microsoft',
'engine.llm': '自定义 LLM',
'engine.glm': 'GLM 大模型',
'engine.backup': '由 {service} 提供'
},
'zh-TW': {
'quick.btn.translate': '翻譯',
'quick.panel.title': '快速翻譯',
'quick.panel.original': '原文',
'quick.panel.translated': '譯文',
'quick.btn.copy': '複製',
'quick.btn.save': '收藏',
'quick.msg.copied': '已複製',
'quick.msg.saved': '已收藏',
'quick.msg.translating': '翻譯中...',
'quick.msg.capturing': '正在截取區域...',
'quick.msg.translatingInProgress': '正在翻譯...',
'quick.msg.ocr': '正在截圖識別...',
'quick.hint.hover': '懸停翻譯',
'quick.hint.dragToSelect': '拖拽選擇要翻譯的區域,或點擊使用預設區域,按 ESC 取消',
'quick.hint.smartMode': '智慧翻譯模式\n自動偵測語言 → 中文\n拖拽選擇要翻譯的區域,按 ESC 取消',
'quick.hint.clickToCopy': '點擊複製各引擎結果',
'quick.hint.multiSuccess': '{success}個成功,{error}個失敗',
'quick.hint.allFailed': '所有引擎均失敗',
'quick.error.noText': '未識別到文字',
'quick.error.screenshotFailed': '截圖失敗',
'quick.error.processFailed': '處理失敗',
'quick.error.ocrNoText': '圖片中沒有找到可識別的文字,請嘗試選擇包含清晰文字的區域',
'quick.result.title': '翻譯結果(可拖動)',
'quick.result.recognized': '識別文字',
'quick.result.translated': '翻譯結果',
'engine.google': 'Google 翻譯',
'engine.microsoft': 'Microsoft',
'engine.llm': '自訂 LLM',
'engine.glm': 'GLM 大模型',
'engine.backup': '由 {service} 提供'
},
'en': {
'quick.btn.translate': 'Translate',
'quick.panel.title': 'Quick Translate',
'quick.panel.original': 'Original',
'quick.panel.translated': 'Translation',
'quick.btn.copy': 'Copy',
'quick.btn.save': 'Save',
'quick.msg.copied': 'Copied',
'quick.msg.saved': 'Saved',
'quick.msg.translating': 'Translating...',
'quick.msg.capturing': 'Capturing area...',
'quick.msg.translatingInProgress': 'Translating...',
'quick.msg.ocr': 'Recognizing text...',
'quick.hint.hover': 'Hover Translate',
'quick.hint.dragToSelect': 'Drag to select translation area, or click to use default area. Press ESC to cancel.',
'quick.hint.smartMode': 'Smart Translation Mode\nAuto-detect language → Chinese\nDrag to select area, press ESC to cancel',
'quick.hint.clickToCopy': 'Click to copy engine results',
'quick.hint.multiSuccess': '{success} succeeded, {error} failed',
'quick.hint.allFailed': 'All engines failed',
'quick.error.noText': 'No text recognized',
'quick.error.screenshotFailed': 'Screenshot failed',
'quick.error.processFailed': 'Processing failed',
'quick.error.ocrNoText': 'No recognizable text found in image. Try selecting an area with clear text.',
'quick.result.title': 'Translation Result (Draggable)',
'quick.result.recognized': 'Recognized Text',
'quick.result.translated': 'Translation',
'engine.google': 'Google Translate',
'engine.microsoft': 'Microsoft',
'engine.llm': 'Custom LLM',
'engine.glm': 'GLM',
'engine.backup': 'Provided by {service}'
},
'ja': {
'quick.btn.translate': '翻訳',
'quick.panel.title': 'クイック翻訳',
'quick.panel.original': '原文',
'quick.panel.translated': '訳文',
'quick.btn.copy': 'コピー',
'quick.btn.save': '保存',
'quick.msg.copied': 'コピーしました',
'quick.msg.saved': '保存しました',
'quick.msg.translating': '翻訳中...',
'quick.msg.capturing': '領域をキャプチャ中...',
'quick.msg.translatingInProgress': '翻訳中...',
'quick.msg.ocr': 'テキストを認識中...',
'quick.hint.hover': 'ホバー翻訳',
'quick.hint.dragToSelect': 'ドラッグして翻訳領域を選択、またはクリックしてデフォルト領域を使用。ESCでキャンセル。',
'quick.hint.smartMode': 'スマート翻訳モード\n言語自動検出 → 中国語\nドラッグして領域を選択、ESCでキャンセル',
'quick.hint.clickToCopy': 'クリックして各エンジンの結果をコピー',
'quick.hint.multiSuccess': '{success}個成功、{error}個失敗',
'quick.hint.allFailed': 'すべてのエンジンが失敗',
'quick.error.noText': 'テキストが認識されませんでした',
'quick.error.screenshotFailed': 'スクリーンショットの取得に失敗',
'quick.error.processFailed': '処理に失敗',
'quick.error.ocrNoText': '画像内に認識可能なテキストが見つかりませんでした。鮮明なテキストが含まれる領域を選択してください。',
'quick.result.title': '翻訳結果(ドラッグ可能)',
'quick.result.recognized': '認識されたテキスト',
'quick.result.translated': '翻訳結果',
'engine.google': 'Google翻訳',
'engine.microsoft': 'Microsoft',
'engine.llm': 'カスタムLLM',
'engine.glm': 'GLM',
'engine.backup': '{service}提供服务'
},
'ko': {
'quick.btn.translate': '번역',
'quick.panel.title': '빠른 번역',
'quick.panel.original': '원문',
'quick.panel.translated': '번역',
'quick.btn.copy': '복사',
'quick.btn.save': '저장',
'quick.msg.copied': '복사됨',
'quick.msg.saved': '저장됨',
'quick.msg.translating': '번역 중...',
'quick.msg.capturing': '영역 캡처 중...',
'quick.msg.translatingInProgress': '번역 중...',
'quick.msg.ocr': '텍스트 인식 중...',
'quick.hint.hover': '호버 번역',
'quick.hint.dragToSelect': '드래그하여 번역 영역 선택 또는 클릭하여 기본 영역 사용. ESC로 취소.',
'quick.hint.smartMode': '스마트 번역 모드\n언어 자동 감지 → 중국어\n드래그하여 영역 선택, ESC로 취소',
'quick.hint.clickToCopy': '클릭하여 각 엔진 결과 복사',
'quick.hint.multiSuccess': '{success}개 성공, {error}개 실패',
'quick.hint.allFailed': '모든 엔진 실패',
'quick.error.noText': '텍스트가 인식되지 않았습니다',
'quick.error.screenshotFailed': '스크린샷 실패',
'quick.error.processFailed': '처리 실패',
'quick.error.ocrNoText': '이미지에서 인식 가능한 텍스트를 찾을 수 없습니다. 선명한 텍스트가 포함된 영역을 선택하세요.',
'quick.result.title': '번역 결과 (드래그 가능)',
'quick.result.recognized': '인식된 텍스트',
'quick.result.translated': '번역 결과',
'engine.google': 'Google 번역',
'engine.microsoft': 'Microsoft',
'engine.llm': '사용자 정의 LLM',
'engine.glm': 'GLM',
'engine.backup': '{service}提供服务'
}
};
// 防止重複聲明
if (typeof window.ScreenshotCapture === 'undefined') {
class ScreenshotCapture {
constructor() {
this.overlay = null;
this.selectionBox = null;
this.instructionText = null;
this.startX = 0;
this.startY = 0;
this.isSelecting = false;
this.lang = 'en'; // UI语言
this.setupMessageListeners();
this.loadUserLanguage();
}
// 从 background 获取用户界面语言
async loadUserLanguage() {
return new Promise((resolve) => {
chrome.runtime.sendMessage({ action: 'getSettings' }, (response) => {
if (response && response.success && response.settings && response.settings.uiLanguage) {
this.lang = response.settings.uiLanguage;
} else {
this.detectBrowserLanguage();
}
resolve();
});
});
}
// 检测浏览器语言
detectBrowserLanguage() {
const browserLang = navigator.language || navigator.userLanguage || 'en';
const langMap = {
'zh-CN': 'zh-CN', 'zh-TW': 'zh-TW', 'zh-HK': 'zh-TW',
'en': 'en', 'en-US': 'en', 'en-GB': 'en',
'ja': 'ja', 'ja-JP': 'ja',
'ko': 'ko', 'ko-KR': 'ko'
};
const prefix = browserLang.split('-')[0].toLowerCase();
this.lang = langMap[browserLang] || langMap[prefix] || 'en';
}
// 获取翻译
t(key) {
const trans = window.qt_contentTranslations;
if (trans[this.lang] && trans[this.lang][key]) {
return trans[this.lang][key];
}
if (trans['en'][key]) {
return trans['en'][key];
}
return key;
}
setupMessageListeners() {
this.messageListener = (request, sender, sendResponse) => {
this.handleMessage(request, sender, sendResponse);
return true;
};
chrome.runtime.onMessage.addListener(this.messageListener);
}
handleMessage(request, sender, sendResponse) {
console.log('Content script received message:', request.action);
try {
switch (request.action) {
case 'initCapture':
console.log('Content: Initializing capture...');
this.initCapture(request.smartMode, request.userSettings);
sendResponse({ success: true });
break;
case 'showResult':
console.log('Content: Showing result...');
this.showTranslationResult(request);
sendResponse({ success: true });
break;
case 'showError':
console.log('Content: Showing error...');
this.showError(request.error);
sendResponse({ success: true });
break;
case 'openFloatPanel':
// 转发给 float-panel (float-panel.js 已加载)
if (window.floatPanel) {
window.floatPanel.init();
}
sendResponse({ success: true });
break;
case 'languageChanged':
console.log('Content: language changed to', request.language);
this.lang = request.language;
sendResponse({ success: true });
break;
default:
console.warn('Content: Unknown action:', request.action);
sendResponse({ error: 'Unknown action' });
}
} catch (error) {
console.error('Content: Error handling message:', error);
sendResponse({ error: error.message });
}
}
initCapture(smartMode = false, userSettings = null) {
console.log('Content: initCapture called with smartMode:', smartMode);
// 保存智能模式设置
this.isSmartMode = smartMode;
this.smartUserSettings = userSettings;
// 清理現有覆蓋層
this.cleanupOverlay();
console.log('Content: Creating new overlay...');
this.createOverlay();
}
createOverlay() {
console.log('Content: Creating overlay elements...');
// 創建主覆蓋層
this.overlay = document.createElement('div');
this.overlay.id = 'screenshot-overlay';
// 強制設置樣式
this.overlay.style.cssText = `
position: fixed !important;
top: 0 !important;
left: 0 !important;
width: 100vw !important;
height: 100vh !important;
background-color: rgba(0, 0, 0, 0.7) !important;
cursor: crosshair !important;
z-index: 2147483647 !important;
user-select: none !important;
display: block !important;
visibility: visible !important;
opacity: 1 !important;
font-family: Arial, sans-serif !important;
`;
// 創建選擇框
this.selectionBox = document.createElement('div');
this.selectionBox.style.cssText = `
position: absolute !important;
border: 2px solid #4285f4 !important;
background-color: rgba(66, 133, 244, 0.1) !important;
display: none !important;
pointer-events: none !important;
`;
// 創建指導文字
this.instructionText = document.createElement('div');
// 根据智能模式设置不同的提示文字
let instructionText = this.t('quick.hint.dragToSelect');
let backgroundColor = 'rgba(0, 0, 0, 0.8)';
if (this.isSmartMode && this.smartUserSettings) {
instructionText = this.t('quick.hint.smartMode');
backgroundColor = 'rgba(52, 168, 83, 0.9)';
}
this.instructionText.textContent = instructionText;
this.instructionText.style.cssText = `
position: absolute !important;
top: 50% !important;
left: 50% !important;
transform: translate(-50%, -50%) !important;
color: white !important;
font-size: 18px !important;
font-weight: 500 !important;
text-align: center !important;
background-color: ${backgroundColor} !important;
padding: 16px 24px !important;
border-radius: 8px !important;
pointer-events: none !important;
max-width: 400px !important;
line-height: 1.4 !important;
z-index: 2147483648 !important;
white-space: pre-line !important;
`;
// 組裝元素
this.overlay.appendChild(this.selectionBox);
this.overlay.appendChild(this.instructionText);
console.log('Content: Appending overlay to body...');
document.body.appendChild(this.overlay);
// 綁定事件
this.overlay.addEventListener('mousedown', (e) => this.startSelection(e));
this.overlay.addEventListener('mousemove', (e) => this.updateSelection(e));
this.overlay.addEventListener('mouseup', (e) => this.endSelection(e));
// 鼠標移動時隱藏指導文字
this.overlay.addEventListener('mousemove', (e) => {
if (!this.isSelecting && this.instructionText && this.instructionText.style.display !== 'none') {
// 如果鼠標移動距離足夠,隱藏指導文字
const rect = this.instructionText.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const distance = Math.sqrt(Math.pow(e.clientX - centerX, 2) + Math.pow(e.clientY - centerY, 2));
if (distance > 100) { // 距離中心100px時隱藏
this.instructionText.style.opacity = '0.3';
} else {
this.instructionText.style.opacity = '1';
}
}
});
// 添加鍵盤事件
document.addEventListener('keydown', (e) => this.handleKeyDown(e));
// 防止頁面滾動
document.body.style.overflow = 'hidden';
console.log('Content: Overlay created successfully');
}
getLanguageName(langCode) {
const languageNames = {
'zh-CN': '简体中文',
'zh-TW': '繁体中文',
'zh': '中文',
'en': '英文',
'ja': '日文',
'ko': '韩文',
'fr': '法文',
'de': '德文',
'es': '西班牙文'
};
return languageNames[langCode] || langCode;
}
handleKeyDown(e) {
if (e.key === 'Escape') {
this.cancelCapture();
}
}
startSelection(e) {
e.preventDefault();
console.log('Content: Starting selection');
// 隱藏指導文字,避免阻擋選擇
if (this.instructionText) {
this.instructionText.style.display = 'none';
}
this.isSelecting = true;
this.startX = e.clientX;
this.startY = e.clientY;
this.selectionBox.style.left = this.startX + 'px';
this.selectionBox.style.top = this.startY + 'px';
this.selectionBox.style.width = '0px';
this.selectionBox.style.height = '0px';
this.selectionBox.style.display = 'block';
}
updateSelection(e) {
if (!this.isSelecting) return;
const currentX = e.clientX;
const currentY = e.clientY;
const left = Math.min(this.startX, currentX);
const top = Math.min(this.startY, currentY);
const width = Math.abs(currentX - this.startX);
const height = Math.abs(currentY - this.startY);
this.selectionBox.style.left = left + 'px';
this.selectionBox.style.top = top + 'px';
this.selectionBox.style.width = width + 'px';
this.selectionBox.style.height = height + 'px';
}
endSelection(e) {
console.log('Content: endSelection called, isSelecting:', this.isSelecting);
if (!this.isSelecting) {
// 單擊模式 - 創建默認區域
console.log('Content: Single click mode');
this.createDefaultSelection(e.clientX, e.clientY);
return;
}
this.isSelecting = false;
console.log('Content: Selection ended');
const rect = this.selectionBox.getBoundingClientRect();
console.log('Content: Selection rect:', rect);
if (rect.width < 10 || rect.height < 10) {
// 太小的選擇,創建默認區域
console.log('Content: Selection too small, using default');
this.createDefaultSelection(e.clientX, e.clientY);
return;
}
console.log('Content: Processing selection...');
this.processSelection(rect);
}
createDefaultSelection(x, y) {
console.log('Content: Creating default selection');
const defaultWidth = 200;
const defaultHeight = 100;
const left = Math.max(0, x - defaultWidth / 2);
const top = Math.max(0, y - defaultHeight / 2);
const rect = {
left: left,
top: top,
width: defaultWidth,
height: defaultHeight
};
this.processSelection(rect);
}
processSelection(rect) {
console.log('Content: Processing selection:', rect);
// 顯示處理狀態
if (this.instructionText) {
this.instructionText.textContent = this.t('quick.msg.capturing');
this.instructionText.style.backgroundColor = 'rgba(66, 133, 244, 0.9)';
this.instructionText.style.display = 'block';
}
// 先嘗試提取選中區域的文字
const selectedText = this.extractTextFromArea(rect);
if (selectedText && selectedText.trim()) {
console.log('Content: Extracted text:', selectedText);
if (this.instructionText) {
this.instructionText.textContent = this.t('quick.msg.translatingInProgress');
}
// 進行真實翻譯處理
setTimeout(async () => {
console.log('Content: About to translate text');
try {
const translatedText = await this.translateText(selectedText);
console.log('Content: Translation completed:', translatedText);
this.showTranslationResult({
originalText: selectedText,
translatedText: translatedText,
confidence: 0.95
});
} catch (error) {
console.error('Content: Translation failed:', error);
this.showTranslationResult({
originalText: selectedText,
translatedText: `翻譯失敗: ${error.message}`,
confidence: 0.0
});
}
}, 800);
} else {
console.log('Content: No text found, using screenshot method');
if (this.instructionText) {
this.instructionText.textContent = this.t('quick.msg.ocr');
}
// 使用截圖方法
this.captureScreenshot(rect);
}
}
extractTextFromArea(rect) {
try {
console.log('Content: Extracting text from precise area:', rect);
// 使用精確的區域文字提取
const extractedText = this.getPreciseTextFromArea(rect);
console.log('Content: Extracted text:', extractedText);
return extractedText;
} catch (error) {
console.error('Error extracting text:', error);
return '';
}
}
getPreciseTextFromArea(rect) {
try {
// 創建一個虛擬的選擇框來精確匹配用戶選擇的區域
const tolerance = 5; // 5像素的容差
// 獲取所有文字節點及其位置信息
const textNodes = this.getAllTextNodes();
const selectedTexts = [];
for (const textNode of textNodes) {
// 跳過我們自己的覆蓋層
if (this.isInOverlay(textNode)) {
continue;
}
// 檢查文字節點是否在選中區域內
const nodeRects = this.getTextNodeRects(textNode);
for (const nodeRect of nodeRects) {
if (this.isRectInSelectedArea(nodeRect, rect, tolerance)) {
const text = textNode.textContent;
if (text && text.trim()) {
selectedTexts.push({
text: text,
top: nodeRect.top,
left: nodeRect.left,
bottom: nodeRect.bottom
});
}
break; // 找到一個匹配的就跳出
}
}
}
// 如果沒有找到文字節點,嘗試元素級別的檢查
if (selectedTexts.length === 0) {
return this.getTextFromElementsInArea(rect);
}
// 按位置排序並保留換行結構
selectedTexts.sort((a, b) => {
// 先按Y坐標排序(上到下)
const yDiff = a.top - b.top;
if (Math.abs(yDiff) > 10) { // 如果Y坐標差距大於10px,認為是不同行
return yDiff;
}
// 同一行內按X坐標排序(左到右)
return a.left - b.left;
});
// 組合文字,保留換行
const lines = [];
let currentLine = [];
let lastBottom = -1;
for (const item of selectedTexts) {
// 如果是新行(Y坐標差距較大)
if (lastBottom >= 0 && item.top > lastBottom + 10) {
if (currentLine.length > 0) {
lines.push(currentLine.join(' ').trim());
currentLine = [];
}
}
currentLine.push(item.text.trim());
lastBottom = item.bottom;
}
// 添加最後一行
if (currentLine.length > 0) {
lines.push(currentLine.join(' ').trim());
}
// 用換行符連接各行
const result = lines.join('\n').trim();
console.log('Content: Found precise text with formatting:', result);
return result;
} catch (error) {
console.error('Error in getPreciseTextFromArea:', error);
return '';
}
}
getAllTextNodes() {
const textNodes = [];
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
{
acceptNode: (node) => {
// 只接受有實際內容的文字節點
if (node.textContent.trim().length > 0) {
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_REJECT;
}
}
);
let node;
while (node = walker.nextNode()) {
textNodes.push(node);
}
return textNodes;
}
getTextNodeRects(textNode) {
try {
const range = document.createRange();
range.selectNodeContents(textNode);
// 獲取文字節點的所有矩形(可能跨行)
const rects = range.getClientRects();
return Array.from(rects);
} catch (error) {
return [];
}
}
isRectInSelectedArea(nodeRect, selectedRect, tolerance = 5) {
// 檢查文字矩形是否與選中區域重疊
const overlap = !(
nodeRect.right < selectedRect.left - tolerance ||
nodeRect.left > selectedRect.left + selectedRect.width + tolerance ||
nodeRect.bottom < selectedRect.top - tolerance ||
nodeRect.top > selectedRect.top + selectedRect.height + tolerance
);
return overlap;
}
isInOverlay(node) {
let parent = node.parentNode;
while (parent) {
if (parent === this.overlay ||
parent === this.selectionBox ||
parent === this.instructionText ||
(parent.className && typeof parent.className === 'string' && parent.className.includes('screenshot')) ||
(parent.className && parent.className.toString && parent.className.toString().includes('screenshot')) ||
(parent.id && parent.id.includes('screenshot'))) {
return true;
}
parent = parent.parentNode;
}
return false;
}
getTextFromElementsInArea(rect) {
try {
console.log('Content: Fallback to element-based text extraction');
// 在選中區域的中心點檢測元素
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const elements = document.elementsFromPoint(centerX, centerY);
for (const element of elements) {
if (this.isInOverlay(element)) {
continue;
}
const elementRect = element.getBoundingClientRect();
// 檢查元素是否主要在選中區域內
if (this.isElementMainlyInArea(elementRect, rect)) {
const text = this.getCleanElementText(element);
if (text && text.length < 300) { // 限制長度
console.log('Content: Found element text:', text);
return text;
}
}
}
return '';
} catch (error) {
console.error('Error in getTextFromElementsInArea:', error);
return '';
}
}
isElementMainlyInArea(elementRect, selectedRect) {
// 計算重疊面積
const overlapLeft = Math.max(elementRect.left, selectedRect.left);
const overlapRight = Math.min(elementRect.right, selectedRect.left + selectedRect.width);
const overlapTop = Math.max(elementRect.top, selectedRect.top);
const overlapBottom = Math.min(elementRect.bottom, selectedRect.top + selectedRect.height);
if (overlapLeft >= overlapRight || overlapTop >= overlapBottom) {
return false; // 沒有重疊
}
const overlapArea = (overlapRight - overlapLeft) * (overlapBottom - overlapTop);
const elementArea = elementRect.width * elementRect.height;
// 如果重疊面積超過元素面積的50%,認為元素主要在選中區域內
return overlapArea / elementArea > 0.5;
}
getCleanElementText(element) {
try {
// 獲取元素的直接文字內容,避免獲取子元素的內容
let text = '';
for (const child of element.childNodes) {
if (child.nodeType === Node.TEXT_NODE) {
text += child.textContent;
}
}
// 如果沒有直接文字內容,獲取元素的文字內容但限制長度
if (!text.trim()) {
text = element.textContent || element.innerText || '';
}
return text.trim();
} catch (error) {
return '';
}
}
getCompleteTextFromArea(rect) {
try {
console.log('Content: Getting complete text from area...');
// 獲取所有與選擇區域重疊的文字元素
const allTextElements = this.getAllTextElementsInArea(rect);
if (allTextElements.length === 0) {
console.log('Content: No text elements found in area');
return '';
}
console.log(`Content: Found ${allTextElements.length} text elements in area`);
// 按位置排序元素(從上到下,從左到右)
allTextElements.sort((a, b) => {
const rectA = a.element.getBoundingClientRect();
const rectB = b.element.getBoundingClientRect();
// 首先按Y坐標排序(上到下)
if (Math.abs(rectA.top - rectB.top) > 10) {
return rectA.top - rectB.top;
}
// 如果Y坐標相近,按X坐標排序(左到右)
return rectA.left - rectB.left;
});
// 組合所有文字
const textParts = [];
let lastBottom = -1;
for (const item of allTextElements) {
const text = item.text;
const rect = item.element.getBoundingClientRect();
if (text && text.trim()) {
// 如果是新行(Y坐標差距較大),添加空格分隔
if (lastBottom >= 0 && rect.top > lastBottom + 5) {
textParts.push(' ');
}
textParts.push(text.trim());
lastBottom = rect.bottom;
}
}
const combinedText = textParts.join(' ').replace(/\s+/g, ' ').trim();
console.log('Content: Combined text:', combinedText.substring(0, 200));
return combinedText;
} catch (error) {
console.error('Error getting complete text from area:', error);
return '';
}
}
getAllTextElementsInArea(rect) {
const textElements = [];
console.log('Content: Searching for text elements in selection area:', rect);
// 使用更精確的選擇器,優先選擇較小的文字元素
const selectors = [
// 優先級1: 小型文字元素
'span', 'a', 'button', 'strong', 'em', 'b', 'i', 'code',
'input[type="button"]', 'input[type="submit"]', 'input[type="reset"]',
'[role="button"]', 'label',
// 優先級2: 中型文字元素
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'li', 'td', 'th',
// 優先級3: 大型容器元素(更嚴格的條件)
'div', 'section', 'article', 'pre'
];
for (const selector of selectors) {
const elements = document.querySelectorAll(selector);
for (const element of elements) {
if (this.isOurElement(element)) continue;
const elementRect = element.getBoundingClientRect();
// 更嚴格的重疊檢查
const overlapInfo = this.calculateDetailedOverlap(elementRect, rect);
if (overlapInfo.hasOverlap) {
const text = this.getElementText(element);
if (text && text.trim() && text.length >= 1) {
// 對於大型容器元素,要求更高的重疊比例
const isLargeContainer = ['div', 'section', 'article'].includes(element.tagName.toLowerCase());
const minOverlapRatio = isLargeContainer ? 0.7 : 0.3; // 大容器需要70%重疊,小元素30%即可
if (overlapInfo.overlapRatio >= minOverlapRatio) {
textElements.push({
element: element,
text: text,
overlapRatio: overlapInfo.overlapRatio,
overlapArea: overlapInfo.overlapArea,
tagName: element.tagName.toLowerCase(),
rect: elementRect,
isLargeContainer: isLargeContainer,
priority: this.getElementPriority(element, overlapInfo)
});
console.log(`Content: Found text element: ${element.tagName} with ${Math.round(overlapInfo.overlapRatio * 100)}% overlap, text: "${text.substring(0, 50)}"`);
}
}
}
}
}
// 按優先級和重疊度排序
textElements.sort((a, b) => {
// 首先按優先級排序
if (a.priority !== b.priority) {
return b.priority - a.priority;
}
// 然後按重疊比例排序
return b.overlapRatio - a.overlapRatio;
});
// 智能去重 - 避免選擇包含其他元素的大容器
const filteredElements = this.filterNestedElements(textElements);
console.log(`Content: After filtering: ${filteredElements.length} elements selected`);
return filteredElements;
}
calculateDetailedOverlap(elementRect, selectionRect) {
const left = Math.max(elementRect.left, selectionRect.left);
const right = Math.min(elementRect.right, selectionRect.left + selectionRect.width);
const top = Math.max(elementRect.top, selectionRect.top);
const bottom = Math.min(elementRect.bottom, selectionRect.top + selectionRect.height);
const hasOverlap = left < right && top < bottom;
if (!hasOverlap) {
return { hasOverlap: false, overlapArea: 0, overlapRatio: 0 };
}
const overlapArea = (right - left) * (bottom - top);
const elementArea = elementRect.width * elementRect.height;
const selectionArea = selectionRect.width * selectionRect.height;
// 計算重疊比例(相對於較小的區域)
const overlapRatio = overlapArea / Math.min(elementArea, selectionArea);
return {
hasOverlap: true,
overlapArea: overlapArea,
overlapRatio: overlapRatio,
elementArea: elementArea,
selectionArea: selectionArea
};
}
getElementPriority(element, overlapInfo) {
const tagName = element.tagName.toLowerCase();
let priority = 0;
// 基礎優先級
if (['button', 'a', 'input'].includes(tagName)) {
priority += 100; // 交互元素最高優先級
} else if (['span', 'strong', 'em', 'b', 'i', 'code'].includes(tagName)) {
priority += 80; // 行內文字元素
} else if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tagName)) {
priority += 70; // 標題元素
} else if (['p', 'li', 'td', 'th', 'label'].includes(tagName)) {
priority += 60; // 段落和列表元素
} else if (['div', 'section', 'article'].includes(tagName)) {
priority += 20; // 容器元素優先級較低
}
// 重疊度加分
priority += overlapInfo.overlapRatio * 50;
// 元素大小加分(較小的元素優先級更高)
const elementArea = overlapInfo.elementArea;
if (elementArea < 10000) { // 小於100x100px
priority += 30;
} else if (elementArea < 50000) { // 小於200x250px
priority += 15;
}
return priority;
}
filterNestedElements(textElements) {
const filtered = [];
for (const item of textElements) {
let isNested = false;
// 檢查是否被其他元素包含
for (const other of textElements) {
if (item === other) continue;
// 如果當前元素被另一個元素包含,且另一個元素的文字包含當前元素的文字
if (this.isElementContainedIn(item.element, other.element) &&
other.text.includes(item.text) &&
other.text.length > item.text.length * 1.5) {
isNested = true;
console.log(`Content: Element ${item.tagName} is nested in ${other.tagName}, skipping`);
break;
}
}
if (!isNested) {
filtered.push(item);
}
}
// 限制返回的元素數量,避免選擇過多內容