-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1546 lines (1388 loc) · 47.7 KB
/
content.js
File metadata and controls
1546 lines (1388 loc) · 47.7 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
// Debug Mode
const DEBUG = true;
function debug(...args) {
if (DEBUG) {
console.log('[DifyHelper]', ...args);
}
}
// 全局变量
let resultContainer = null;
let floatingButton = null;
let selectedText = '';
let questionModal = null;
let controller = null; // 用于控制流式响应的终止
let lastMouseX = 0;
let lastMouseY = 0;
// 初始化函数
function initialize() {
debug('Initializing DifyHelper...');
try {
// 移除可能已存在的事件监听器
document.removeEventListener('mouseup', handleTextSelection);
document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('keydown', handleKeyDown);
document.removeEventListener('mousemove', handleMouseMove);
// 添加事件监听器
document.addEventListener('mouseup', handleTextSelection);
document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('mousemove', handleMouseMove);
// 清理可能存在的浮动按钮
hideFloatingButton();
debug('Initialization complete');
} catch (error) {
debug('Initialization failed:', error);
}
}
// 清理函数
function cleanup() {
debug('Event: Cleanup started');
hideFloatingButton();
debug('Event: Cleanup completed');
}
// 处理文本选择
function handleTextSelection(event) {
try {
// 如果点击的是浮动按钮或其子元素,不处理
if (event.target.closest('#dify-helper-button')) {
return;
}
// 延迟执行选中文本的处理,确保在handleClickOutside之后执行
setTimeout(() => {
const selection = window.getSelection();
const text = selection.toString().trim();
// 如果没有选中文本,隐藏按钮
if (!text) {
hideFloatingButton();
return;
}
// 使用鼠标事件的位置
const buttonSize = 24;
const horizontalSpacing = 5;
const verticalSpacing = 5;
let x = event.pageX + horizontalSpacing;
let y = event.pageY - buttonSize - verticalSpacing;
// 确保按钮在视口内
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
// 转换pageX/Y到视口相对坐标
const clientX = event.clientX;
const clientY = event.clientY;
if (clientX + buttonSize + horizontalSpacing > viewportWidth) {
x = event.pageX - buttonSize - horizontalSpacing;
}
if (clientY - buttonSize - verticalSpacing < 0) {
y = event.pageY + verticalSpacing;
}
if (clientX + buttonSize > viewportWidth - horizontalSpacing) {
x = event.pageX - buttonSize - horizontalSpacing;
}
if (clientY + buttonSize > viewportHeight - verticalSpacing) {
y = event.pageY - buttonSize - verticalSpacing;
}
selectedText = text;
if (floatingButton) {
floatingButton.style.left = `${x}px`;
floatingButton.style.top = `${y}px`;
} else {
showFloatingButton(x, y);
}
}, 0);
} catch (error) {
debug('Error in handleTextSelection:', error);
}
}
// 显示浮动按钮
function showFloatingButton(x, y) {
try {
hideFloatingButton();
floatingButton = document.createElement('div');
floatingButton.id = 'dify-helper-button';
floatingButton.style.cssText = `
position: absolute;
left: ${x}px;
top: ${y}px;
z-index: 2147483647;
background: white;
border-radius: 6px;
width: 24px;
height: 24px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s ease;
user-select: none;
pointer-events: auto;
`;
const button = document.createElement('button');
button.id = 'dify-helper-button-inner';
button.type = 'button';
button.style.cssText = `
width: 100%;
height: 100%;
border: none;
padding: 0;
margin: 0;
background: #4F46E5;
border-radius: 4px;
color: white;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s ease;
pointer-events: auto;
`;
button.innerHTML = `
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-4l-4 4-4-4z"/>
</svg>
`;
function handleClick(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
const textToShow = selectedText;
hideFloatingButton();
showQuestionModal(textToShow);
}
function handleMouseOver() {
button.style.background = '#4338CA';
floatingButton.style.transform = 'scale(1.05)';
floatingButton.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.2)';
}
function handleMouseOut() {
button.style.background = '#4F46E5';
floatingButton.style.transform = 'scale(1)';
floatingButton.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.15)';
}
button.addEventListener('click', handleClick, { capture: true });
floatingButton.addEventListener('click', handleClick, { capture: true });
button.addEventListener('mouseover', handleMouseOver);
button.addEventListener('mouseout', handleMouseOut);
floatingButton.addEventListener('mouseover', handleMouseOver);
floatingButton.addEventListener('mouseout', handleMouseOut);
floatingButton.appendChild(button);
document.body.appendChild(floatingButton);
} catch (error) {
debug('Error in showFloatingButton:', error);
}
}
// 隐藏浮动按钮
function hideFloatingButton() {
if (floatingButton && floatingButton.parentNode) {
floatingButton.parentNode.removeChild(floatingButton);
floatingButton = null;
}
}
// 处理点击外部
function handleClickOutside(event) {
// 如果点击的是浮动按钮或其子元素,不处理
if (floatingButton && (floatingButton.contains(event.target) || event.target.closest('#dify-helper-button'))) {
return;
}
// 立即隐藏按钮
hideFloatingButton();
}
// 监听来自background.js的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'showQuestionModal') {
showQuestionModal(message.text);
}
});
// 创建问题模态框
async function showQuestionModal(text) {
try {
debug('Event: Showing modal');
debug('State: Modal text:', text);
// 清理可能存在的旧模态框
const existingModal = document.querySelector('#dify-helper-modal');
if (existingModal) {
debug('State: Removing existing modal');
existingModal.parentNode.removeChild(existingModal);
}
let result;
try {
// 先获取所有可用的Token和当前选中的Token
result = await chrome.storage.sync.get(['apiUrl', 'tokens', 'selectedToken']);
} catch (error) {
debug('Error accessing chrome storage:', error);
// 创建一个简单的错误提示模态框
const errorModal = document.createElement('div');
errorModal.id = 'dify-helper-modal';
errorModal.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 2147483647;
`;
const errorContent = document.createElement('div');
errorContent.style.cssText = `
background: white;
padding: 20px;
border-radius: 8px;
max-width: 400px;
text-align: center;
`;
errorContent.innerHTML = `
<h3 style="margin: 0 0 10px; color: #DC2626;">扩展错误</h3>
<p style="margin: 0 0 15px;">扩展上下文已失效,请尝试以下操作:</p>
<ol style="text-align: left; margin: 0 0 15px; padding-left: 20px;">
<li>刷新当前页面</li>
<li>重新启用扩展</li>
<li>如果问题持续,请重启浏览器</li>
</ol>
<button id="dify-error-close" style="
padding: 8px 16px;
background: #4F46E5;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background 0.2s;
">关闭</button>
`;
errorModal.appendChild(errorContent);
document.body.appendChild(errorModal);
// 添加关闭按钮事件
const closeButton = errorContent.querySelector('#dify-error-close');
closeButton.addEventListener('mouseover', () => {
closeButton.style.background = '#4338CA';
});
closeButton.addEventListener('mouseout', () => {
closeButton.style.background = '#4F46E5';
});
closeButton.addEventListener('click', () => {
errorModal.remove();
});
// 点击背景关闭
errorModal.addEventListener('click', (e) => {
if (e.target === errorModal) {
errorModal.remove();
}
});
return;
}
const tokens = result.tokens || [];
const currentToken = result.selectedToken;
const apiUrl = result.apiUrl;
// 预先获取所有应用的名称
const appNames = new Map();
for (const token of tokens) {
try {
const response = await fetch(`${apiUrl}/info?user=extension_user`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
const data = await response.json();
appNames.set(token, data.name || '未命名应用');
} else {
appNames.set(token, '无法获取应用信息');
}
} catch (error) {
appNames.set(token, '获取应用信息失败');
}
}
// 创建一个包含所有样式的容器
const modalContainer = document.createElement('div');
modalContainer.id = 'dify-helper-modal';
modalContainer.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex !important;
align-items: center !important;
justify-content: center !important;
z-index: 2147483647;
pointer-events: auto;
`;
debug('State: Created modal container');
debug('Modal container styles:', modalContainer.style.cssText);
const modalContent = document.createElement('div');
modalContent.id = 'dify-helper-modal-content';
modalContent.style.cssText = `
background: white;
border-radius: 12px;
width: 90%;
max-width: 600px;
height: 60%;
display: flex;
flex-direction: column;
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
position: relative;
pointer-events: auto;
overflow: hidden;
`;
debug('State: Created modal content');
debug('Modal content styles:', modalContent.style.cssText);
modalContent.innerHTML = `
<div style="
display: flex;
flex-direction: column;
height: 100%;
">
<div style="
position: relative;
padding: 16px 20px;
border-bottom: 1px solid #E5E7EB;
background: #FFFFFF;
">
<div style="
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
">
<h3 style="
margin: 0;
font-size: 18px;
font-weight: 600;
color: #111827;
line-height: 1.4;
">
提问关于选中内容
</h3>
<div style="
display: flex;
align-items: center;
gap: 8px;
">
<span style="
font-size: 13px;
color: #4B5563;
font-weight: 500;
">当前应用:</span>
<div style="
position: relative;
min-width: 180px;
">
<select id="modelSelect" style="
width: 100%;
padding: 6px 28px 6px 12px;
font-size: 13px;
color: #1F2937;
border: 1px solid #D1D5DB;
border-radius: 6px;
background-color: white;
appearance: none;
cursor: pointer;
outline: none;
transition: all 0.2s;
font-weight: 500;
">
${tokens.map(token => {
const isSelected = token === currentToken;
return `<option value="${token}" ${isSelected ? 'selected' : ''}>${appNames.get(token)}</option>`;
}).join('')}
</select>
<div style="
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
pointer-events: none;
">
<svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
</svg>
</div>
</div>
</div>
</div>
<div style="
background: #F9FAFB;
border-radius: 8px;
padding: 14px 16px;
font-size: 14px;
color: #374151;
line-height: 1.6;
max-height: 100px;
overflow-y: auto;
border: 1px solid #E5E7EB;
scrollbar-width: thin;
scrollbar-color: rgba(156, 163, 175, 0.5) transparent;
&::-webkit-scrollbar {
width: 6px;
height: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background-color: rgba(156, 163, 175, 0.5);
border-radius: 3px;
}
&::-webkit-scrollbar-thumb:hover {
background-color: rgba(156, 163, 175, 0.7);
}
">
${text}
</div>
</div>
<div id="responseContainer" style="
flex: 1;
overflow-y: auto;
padding: 16px 24px;
margin: 0;
border-radius: 0;
background: #fff;
position: relative;
font-size: 14px;
line-height: 1.6;
color: #333;
word-wrap: break-word;
white-space: pre-wrap;
border-top: 1px solid #f0f0f0;
border-bottom: 1px solid #f0f0f0;
"></div>
<div style="
padding: 16px 20px;
border-top: 1px solid #E5E7EB;
background: white;
">
<div style="
margin-bottom: 12px;
display: flex;
gap: 8px;
flex-wrap: wrap;
">
<button class="quick-action-btn" data-action="解释" style="
padding: 6px 12px;
font-size: 13px;
color: #4F46E5;
background: #EEF2FF;
border: none;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
font-weight: 500;
">解释</button>
<button class="quick-action-btn" data-action="总结" style="
padding: 6px 12px;
font-size: 13px;
color: #4F46E5;
background: #EEF2FF;
border: none;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
font-weight: 500;
">总结</button>
<button class="quick-action-btn" data-action="翻译" style="
padding: 6px 12px;
font-size: 13px;
color: #4F46E5;
background: #EEF2FF;
border: none;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
font-weight: 500;
">翻译</button>
</div>
<div style="
position: relative;
display: flex;
align-items: flex-start;
">
<textarea
id="questionInput"
placeholder="输入你的问题,按Enter发送,Shift+Enter换行"
style="
width: 100%;
padding: 10px 40px 10px 14px;
border: 1px solid #D1D5DB;
border-radius: 8px;
outline: none;
font-size: 14px;
line-height: 1.6;
resize: none;
min-height: 44px;
max-height: 120px;
transition: all 0.2s;
background: #F9FAFB;
scrollbar-width: thin;
scrollbar-color: rgba(156, 163, 175, 0.5) transparent;
&::-webkit-scrollbar {
width: 6px;
height: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background-color: rgba(156, 163, 175, 0.5);
border-radius: 3px;
}
&::-webkit-scrollbar-thumb:hover {
background-color: rgba(156, 163, 175, 0.7);
}
&:focus {
border-color: #4F46E5;
background: white;
box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.1);
}
"
></textarea>
<button id="sendButton" style="
position: absolute;
right: 10px;
bottom: 10px;
padding: 4px;
background: none;
border: none;
color: #4F46E5;
cursor: pointer;
transition: all 0.2s;
line-height: 0;
border-radius: 4px;
">
<svg style="width: 20px; height: 20px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
</svg>
</button>
</div>
</div>
</div>
`;
modalContainer.appendChild(modalContent);
debug('Event: Appended modal content to container');
// 先将模态框添加到 DOM
document.body.appendChild(modalContainer);
debug('Event: Appended modal container to body');
// 获取元素引用
const questionInput = modalContainer.querySelector('#questionInput');
const sendButton = modalContainer.querySelector('#sendButton');
const responseContainer = modalContainer.querySelector('#responseContainer');
debug('State: Got modal element references', {
hasQuestionInput: !!questionInput,
hasSendButton: !!sendButton,
hasResponseContainer: !!responseContainer
});
// 确保元素都存在
if (!questionInput || !sendButton || !responseContainer) {
throw new Error('Modal elements not found');
}
// 添加输入框焦点样式
questionInput.addEventListener('focus', () => {
questionInput.style.borderColor = '#4F46E5';
});
questionInput.addEventListener('blur', () => {
questionInput.style.borderColor = '#D1D5DB';
});
// 添加按钮悬停效果
sendButton.addEventListener('mouseover', () => {
sendButton.style.color = '#4338CA';
});
sendButton.addEventListener('mouseout', () => {
sendButton.style.color = '#4F46E5';
});
// 聚焦输入框
setTimeout(() => {
questionInput.focus();
debug('Event: Focused question input');
}, 100);
// 修改回车键处理逻辑,支持Shift+Enter换行
questionInput.addEventListener('keydown', async (e) => {
if (e.key === 'Enter') {
if (e.shiftKey) {
// Shift+Enter换行,不做处理
return;
}
e.preventDefault(); // 阻止默认的换行行为
const question = questionInput.value.trim();
if (question) {
debug('Event: Enter key pressed');
handleSendMessage(text, questionInput, sendButton, responseContainer);
}
}
});
// 自动调整textarea高度
questionInput.addEventListener('input', () => {
questionInput.style.height = 'auto';
questionInput.style.height = Math.min(questionInput.scrollHeight, 120) + 'px';
});
// 点击发送按钮
sendButton.addEventListener('click', () => {
debug('Event: Send button clicked');
handleSendMessage(text, questionInput, sendButton, responseContainer);
});
// 点击背景关闭
modalContainer.addEventListener('click', (e) => {
debug('Event: Modal container clicked', {
target: e.target === modalContainer ? 'background' : 'content'
});
if (e.target === modalContainer) {
debug('Event: Modal background clicked');
closeQuestionModal();
}
});
// 阻止事件冒泡
modalContent.addEventListener('click', (e) => {
e.stopPropagation();
});
// 添加 ESC 键关闭
const handleEscKey = (e) => {
if (e.key === 'Escape') {
debug('Event: ESC key pressed');
closeQuestionModal();
}
};
document.addEventListener('keydown', handleEscKey);
// 存储事件处理函数引用,以便在关闭时移除
modalContainer._handleEscKey = handleEscKey;
// 存储模态框引用
questionModal = modalContainer;
// 添加模型选择事件监听
const modelSelect = modalContent.querySelector('#modelSelect');
if (modelSelect) {
modelSelect.addEventListener('change', async () => {
const selectedToken = modelSelect.value;
await chrome.storage.sync.set({selectedToken});
// 清除当前对话ID
currentConversationId = null;
debug('Model changed, conversation ID cleared');
});
// 添加焦点样式
modelSelect.addEventListener('focus', () => {
modelSelect.style.borderColor = '#4F46E5';
modelSelect.style.boxShadow = '0 0 0 1px #4F46E5';
});
modelSelect.addEventListener('blur', () => {
modelSelect.style.borderColor = '#D1D5DB';
modelSelect.style.boxShadow = 'none';
});
// 添加悬停样式
modelSelect.addEventListener('mouseover', () => {
if (modelSelect !== document.activeElement) {
modelSelect.style.borderColor = '#9CA3AF';
}
});
modelSelect.addEventListener('mouseout', () => {
if (modelSelect !== document.activeElement) {
modelSelect.style.borderColor = '#D1D5DB';
}
});
}
// 添加快捷操作按钮的事件监听
const quickActionButtons = modalContainer.querySelectorAll('.quick-action-btn');
quickActionButtons.forEach(button => {
// 添加悬停效果
button.addEventListener('mouseover', () => {
button.style.background = '#E0E7FF';
});
button.addEventListener('mouseout', () => {
button.style.background = '#EEF2FF';
});
// 添加点击事件
button.addEventListener('click', () => {
const action = button.getAttribute('data-action');
const actionMap = {
'解释': '请解释以下内容:',
'总结': '请总结以下内容:',
'翻译': '请将以下内容翻译成中文,如果已经是中文,则翻译成英文(只输出翻译内容,不要输出其他内容):'
};
if (questionInput && sendButton && responseContainer) {
questionInput.value = actionMap[action] || '';
handleSendMessage(text, questionInput, sendButton, responseContainer);
}
});
});
debug('Event: Modal setup complete');
} catch (error) {
debug('Error in showQuestionModal:', error);
console.error('Error in showQuestionModal:', error);
}
}
function closeQuestionModal() {
debug('Event: Closing modal');
const modalContainer = document.querySelector('#dify-helper-modal');
if (modalContainer && modalContainer.parentNode) {
debug('State: Removing modal from DOM');
// 移除 ESC 键监听器
if (modalContainer._handleEscKey) {
document.removeEventListener('keydown', modalContainer._handleEscKey);
debug('State: Removed ESC key handler');
}
modalContainer.parentNode.removeChild(modalContainer);
questionModal = null;
debug('State: Modal reference cleared');
}
}
// 显示建议问题
async function updateSuggestions(messageId) {
const suggestionsContainer = document.getElementById('suggestionsContainer');
if (!suggestionsContainer) return;
const result = await chrome.storage.sync.get(['apiUrl', 'selectedToken', 'enableSuggestions']);
if (!result.enableSuggestions) {
suggestionsContainer.classList.add('hidden');
return;
}
try {
if (!messageId) {
const response = await fetch(`${result.apiUrl}/parameters?user=extension_user`, {
headers: {
'Authorization': `Bearer ${result.selectedToken}`
}
});
if (response.ok) {
const data = await response.json();
if (data.suggested_questions?.length) {
showSuggestions(data.suggested_questions);
} else {
suggestionsContainer.classList.add('hidden');
}
}
} else {
const response = await fetch(`${result.apiUrl}/messages/${messageId}/suggested?user=extension_user`, {
headers: {
'Authorization': `Bearer ${result.selectedToken}`
}
});
if (response.ok) {
const data = await response.json();
if (data.data?.length) {
showSuggestions(data.data);
} else {
suggestionsContainer.classList.add('hidden');
}
}
}
} catch (error) {
console.error('获取建议问题失败:', error);
suggestionsContainer.classList.add('hidden');
}
}
function showSuggestions(suggestions) {
const suggestionsContainer = document.getElementById('suggestionsContainer');
if (!suggestionsContainer) return;
suggestionsContainer.innerHTML = `
<div style="font-size: 0.75rem; font-weight: 500; color: #6B7280;">建议问题:</div>
<div style="display: flex; flex-wrap: wrap; gap: 0.5rem;">
${suggestions.map(q => `
<button style="
font-size: 0.75rem;
padding: 0.25rem 0.5rem;
background: #F3F4F6;
color: #374151;
border-radius: 9999px;
border: none;
cursor: pointer;
transition: background-color 0.2s;
"
data-question="${q}"
>
${q}
</button>
`).join('')}
</div>
`;
suggestionsContainer.style.display = 'block';
// 绑定点击事件
const buttons = suggestionsContainer.querySelectorAll('button');
buttons.forEach(button => {
button.addEventListener('mouseover', () => {
button.style.background = '#E5E7EB';
});
button.addEventListener('mouseout', () => {
button.style.background = '#F3F4F6';
});
button.addEventListener('click', () => {
const question = button.getAttribute('data-question');
if (question) {
sendMessage(question);
}
});
});
}
// 在模态框内发送消息
async function sendMessageInModal(text, responseContainer, isRegenerate = false) {
const result = await chrome.storage.sync.get(['apiUrl', 'selectedToken']);
if (!result.apiUrl || !result.selectedToken) {
responseContainer.innerHTML = '<span style="color: #DC2626;">错误: 请先配置API地址和选择Token</span>';
return;
}
try {
// 清空容器
responseContainer.innerHTML = '';
// 创建回答容器
const answerContainer = document.createElement('div');
answerContainer.style.cssText = `
position: relative;
padding-bottom: 2em;
`;
responseContainer.appendChild(answerContainer);
// 显示加载状态
answerContainer.innerHTML = '正在思考...';
// 创建工具栏容器
const toolbarContainer = document.createElement('div');
toolbarContainer.style.cssText = `
position: absolute;
bottom: 0;
right: 0;
display: flex;
gap: 8px;
padding: 4px;
border-radius: 4px;
background: #F3F4F6;
opacity: 0;
transition: opacity 0.2s;
`;
// 创建工具栏按钮
const buttons = [
{
icon: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"/></svg>',
title: '复制',
onClick: (text) => {
navigator.clipboard.writeText(text).then(() => {
showTooltip(button, '已复制');
});
}
},
{
icon: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>',
title: '重新生成',
onClick: async () => {
// 如果正在生成中,先中止当前生成
if (controller) {
controller.abort();
controller = null;
}
// 获取模态框中的输入框和发送按钮
const modal = document.querySelector('#dify-helper-modal');
if (modal) {
const questionInput = modal.querySelector('#questionInput');
const sendButton = modal.querySelector('#sendButton');
const responseContainer = modal.querySelector('#responseContainer');
if (questionInput && sendButton && responseContainer) {
// 设置一个临时的问题文本,这样handleSendMessage就能正常工作
questionInput.value = '重新生成';
handleSendMessage(text, questionInput, sendButton, responseContainer);
}
}
}
}
];
buttons.forEach(({ icon, title, onClick }, index) => {
const button = document.createElement('button');
button.style.cssText = `
padding: 4px;
color: #6B7280;
background: none;
border: none;
border-radius: 4px;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
`;
button.innerHTML = icon;
button.title = title;
button.addEventListener('mouseover', () => {
button.style.color = '#374151';
button.style.background = '#E5E7EB';
});
button.addEventListener('mouseout', () => {
button.style.color = '#6B7280';
button.style.background = 'none';