-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsidebar.js
1097 lines (966 loc) · 39.2 KB
/
sidebar.js
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
import { setTheme } from './src/utils/theme.js';
import { handleImageDrop } from './src/utils/image.js';
import { loadChatHistory } from './src/utils/chat-history.js';
import { callAPI, processImageTags } from './src/services/chat.js';
import { processMessageContent } from './src/utils/message-utils.js';
import { appendMessage, updateAIMessage } from './src/handlers/message-handler.js';
import { renderAPICards, createCardCallbacks, selectCard } from './src/components/api-card/index.js';
import { adjustTextareaHeight, showImagePreview, hideImagePreview, createImageTag } from './src/utils/ui.js';
import { showContextMenu, hideContextMenu, copyMessageContent } from './src/components/context-menu/index.js';
import { storageAdapter, syncStorageAdapter, browserAdapter, isExtensionEnvironment } from './src/utils/storage-adapter.js';
document.addEventListener('DOMContentLoaded', async () => {
const chatContainer = document.getElementById('chat-container');
const messageInput = document.getElementById('message-input');
const contextMenu = document.getElementById('context-menu');
const copyMessageButton = document.getElementById('copy-message');
const copyCodeButton = document.getElementById('copy-code');
const stopUpdateButton = document.getElementById('stop-update');
const settingsButton = document.getElementById('settings-button');
const settingsMenu = document.getElementById('settings-menu');
const feedbackButton = document.getElementById('feedback-button');
const previewModal = document.querySelector('.image-preview-modal');
const previewImage = previewModal.querySelector('img');
let currentMessageElement = null;
let currentCodeElement = null;
let currentController = null; // 用于存储当前的 AbortController
// 创建UI工具配置
const uiConfig = {
textarea: {
maxHeight: 200
},
imagePreview: {
previewModal,
previewImage
},
imageTag: {
onImageClick: (base64Data) => {
showImagePreview({
base64Data,
config: uiConfig.imagePreview
});
},
onDeleteClick: (container) => {
container.remove();
messageInput.dispatchEvent(new Event('input'));
}
}
};
// 添加反馈按钮点击事件
feedbackButton.addEventListener('click', () => {
const newIssueUrl = 'https://github.com/yym68686/Cerebr/issues/new';
window.open(newIssueUrl, '_blank');
settingsMenu.classList.remove('visible'); // 使用 classList 来正确切换菜单状态
});
// 添加点击事件监听器,让点击侧边栏时自动聚焦到输入框
document.body.addEventListener('click', (e) => {
// 如果有文本被选中,不要触发输入框聚焦
if (window.getSelection().toString()) {
return;
}
// 排除点击设置按钮、设置菜单、上下文菜单的情况
if (!settingsButton.contains(e.target) &&
!settingsMenu.contains(e.target) &&
!contextMenu.contains(e.target)) {
messageInput.focus();
}
});
// 聊天历史记录变量
let chatHistory = [];
// 修改保存聊天历史记录的函数
async function saveChatHistory() {
try {
// 在保存之前处理消息格式
const processedHistory = chatHistory.map(msg => processMessageContent(msg, processImageTags));
await storageAdapter.set({ chatHistory: processedHistory });
} catch (error) {
console.error('保存聊天历史记录失败:', error);
}
}
async function getChatHistoryFromStorage() {
try {
const result = await storageAdapter.get('chatHistory');
return result.chatHistory || [];
} catch (error) {
console.error('从存储中获取聊天历史记录失败:', error);
return [];
}
}
// 创建AI消息更新配置
const updateAIMessageConfig = {
onSaveHistory: (text) => {
if (chatHistory.length > 0) {
chatHistory[chatHistory.length - 1].content = text;
saveChatHistory();
}
}
};
// 创建消息处理配置
const messageHandlerConfig = {
onSaveHistory: (message) => {
chatHistory.push(message);
saveChatHistory();
},
onShowImagePreview: showImagePreview,
onUpdateAIMessage: (text) => {
updateAIMessage({
text,
chatContainer,
config: updateAIMessageConfig,
messageHandlerConfig
});
},
imagePreviewConfig: uiConfig.imagePreview
};
// 在事件监听器中使用新的函数
browserAdapter.onTabActivated(async (activeInfo) => {
console.log('标签页切换:', activeInfo);
chatHistory = await loadChatHistory({
chatContainer,
processMessageContent,
processImageTags,
createImageTag,
appendMessage,
messageHandlerConfig,
uiConfig,
getChatHistory: getChatHistoryFromStorage
});
await loadWebpageSwitch('标签页切换');
});
// 初始加载历史记录
chatHistory = await loadChatHistory({
chatContainer,
processMessageContent,
processImageTags,
createImageTag,
appendMessage,
messageHandlerConfig,
uiConfig,
getChatHistory: getChatHistoryFromStorage
});
// 网答功能
const webpageSwitch = document.getElementById('webpage-switch');
const webpageQAContainer = document.getElementById('webpage-qa');
// 如果不是扩展环境,隐藏网页问答功能
if (!isExtensionEnvironment) {
webpageQAContainer.style.display = 'none';
}
let pageContent = null;
// 获取网页内容
async function getPageContent() {
try {
console.log('getPageContent 发送获取网页内容请求');
const response = await browserAdapter.sendMessage({
type: 'GET_PAGE_CONTENT_FROM_SIDEBAR'
});
return response;
} catch (error) {
console.error('获取网页内容失败:', error);
return null;
}
}
// 修改 loadWebpageSwitch 函数
async function loadWebpageSwitch(call_name = 'loadWebpageSwitch') {
console.log(`loadWebpageSwitch 从 ${call_name} 调用`);
try {
const domain = await getCurrentDomain();
console.log('刷新后 网页问答 获取当前域名:', domain);
if (!domain) return;
const result = await storageAdapter.get('webpageSwitchDomains');
const domains = result.webpageSwitchDomains || {};
console.log('刷新后 网页问答存储中获取域名:', domains);
// 只在开关状态不一致时才更新
if (domains[domain] !== webpageSwitch.checked) {
webpageSwitch.checked = !!domains[domain];
if (webpageSwitch.checked) {
document.body.classList.add('loading-content');
try {
const content = await getPageContent();
if (content) {
pageContent = content;
} else {
console.error('loadWebpageSwitch 获取网页内容失败');
}
} catch (error) {
console.error('loadWebpageSwitch 获取网页内容失败:', error);
} finally {
document.body.classList.remove('loading-content');
}
} else {
pageContent = null;
}
}
} catch (error) {
console.error('加载网页问答状态失败:', error);
}
}
// 修改网页问答开关监听器
webpageSwitch.addEventListener('change', async () => {
try {
const domain = await getCurrentDomain();
console.log('网页问答开关状态改变后,获取当前域名:', domain);
if (!domain) {
console.log('无法获取域名,保持开关状态不变');
webpageSwitch.checked = !webpageSwitch.checked; // 恢复开关状态
return;
}
console.log('网页问答开关状态改变后,获取网页问答开关状态:', webpageSwitch.checked);
if (webpageSwitch.checked) {
document.body.classList.add('loading-content');
try {
const content = await getPageContent();
if (content) {
pageContent = content;
await saveWebpageSwitch(domain, true);
console.log('修改网页问答为已开启');
} else {
console.error('获取网页内容失败。');
}
} catch (error) {
console.error('获取网页内容失败:', error);
} finally {
document.body.classList.remove('loading-content');
}
} else {
pageContent = null;
await saveWebpageSwitch(domain, false);
console.log('修改网页问答为已关闭');
}
} catch (error) {
console.error('处理网页问答开关变化失败:', error);
webpageSwitch.checked = !webpageSwitch.checked; // 恢复开关状态
}
});
// 在 DOMContentLoaded 事件处理程序中添加加载网页问答状态
await loadWebpageSwitch();
// 获取当前域名
async function getCurrentDomain() {
try {
const tab = await browserAdapter.getCurrentTab();
if (!tab) return null;
// 如果是本地文件,直接返回hostname
if (tab.hostname === 'local_pdf') {
return tab.hostname;
}
// 处理普通URL
const hostname = tab.hostname;
// 规范化域名
const normalizedDomain = hostname
.replace(/^www\./, '') // 移除www前缀
.toLowerCase(); // 转换为小写
console.log('规范化域名:', hostname, '->', normalizedDomain);
return normalizedDomain;
} catch (error) {
// console.error('获取当前域名失败:', error);
return null;
}
}
async function sendMessage() {
// 如果有正在更新的AI消息,停止它
const updatingMessage = chatContainer.querySelector('.ai-message.updating');
if (updatingMessage && currentController) {
currentController.abort();
currentController = null;
updatingMessage.classList.remove('updating');
}
const message = messageInput.textContent.trim();
const imageTags = messageInput.querySelectorAll('.image-tag');
if (!message && imageTags.length === 0) return;
try {
// 构建消息内容
let content;
if (imageTags.length > 0) {
content = [];
if (message) {
content.push({
type: "text",
text: message
});
}
imageTags.forEach(tag => {
const base64Data = tag.getAttribute('data-image');
if (base64Data) {
content.push({
type: "image_url",
image_url: {
url: base64Data
}
});
}
});
} else {
content = message;
}
// 构建用户消息
const userMessage = {
role: "user",
content: content
};
// 先添加用户消息到界面和历史记录
appendMessage({
text: messageInput.innerHTML,
sender: 'user',
chatContainer,
config: messageHandlerConfig
});
// 清空输入框并调整高度
messageInput.innerHTML = '';
adjustTextareaHeight({
textarea: messageInput,
config: uiConfig.textarea
});
// 构建消息数组
const messages = [...chatHistory.slice(0, -1)]; // 排除刚刚添加的用户消息
messages.push(userMessage);
// 准备API调用参数
const apiParams = {
messages,
apiConfig: apiConfigs[selectedConfigIndex],
userLanguage: navigator.language,
webpageInfo: webpageSwitch.checked ? pageContent : null
};
// 调用 API
const { processStream, controller } = await callAPI(apiParams);
currentController = controller;
// 处理流式响应
await processStream(messageHandlerConfig.onUpdateAIMessage);
} catch (error) {
if (error.name === 'AbortError') {
console.log('用户手动停止更新');
return;
}
console.error('发送消息失败:', error);
appendMessage({
text: '发送失败: ' + error.message,
sender: 'ai',
chatContainer,
skipHistory: true,
config: messageHandlerConfig
});
// 从 chatHistory 中移除最后一条记录(用户的问题)
chatHistory.pop();
saveChatHistory();
} finally {
const lastMessage = chatContainer.querySelector('.ai-message:last-child');
if (lastMessage) {
lastMessage.classList.remove('updating');
}
}
}
// 监听来自 content script 的消息
window.addEventListener('message', (event) => {
if (event.data.type === 'DROP_IMAGE') {
console.log('收到拖放图片数据');
const imageData = event.data.imageData;
if (imageData && imageData.data) {
console.log('创建图片标签');
// 确保base64数据格式正确
const base64Data = imageData.data.startsWith('data:') ? imageData.data : `data:image/png;base64,${imageData.data}`;
const imageTag = createImageTag({
base64Data: base64Data,
fileName: imageData.name
});
// 确保输入框有焦点
messageInput.focus();
// 获取或创建选区
const selection = window.getSelection();
let range;
// 检查是否有现有选区
if (selection.rangeCount > 0) {
range = selection.getRangeAt(0);
} else {
// 创建新的选区
range = document.createRange();
// 将选区设置到输入框的末尾
range.selectNodeContents(messageInput);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}
console.log('插入图片标签到输入框');
// 插入图片标签
range.deleteContents();
range.insertNode(imageTag);
// 移动光标到图片标签后面
const newRange = document.createRange();
newRange.setStartAfter(imageTag);
newRange.collapse(true);
selection.removeAllRanges();
selection.addRange(newRange);
// 触发输入事件以调整高度
messageInput.dispatchEvent(new Event('input'));
console.log('图片插入完成');
}
} else if (event.data.type === 'FOCUS_INPUT') {
messageInput.focus();
const range = document.createRange();
range.selectNodeContents(messageInput);
range.collapse(false);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
} else if (event.data.type === 'URL_CHANGED') {
console.log('[收到URL变化]', event.data.url);
if (webpageSwitch.checked) {
console.log('[网页问答] URL变化,重新获取页面内容');
document.body.classList.add('loading-content');
getPageContent()
.then(async content => {
if (content) {
pageContent = content;
const domain = await getCurrentDomain();
if (domain) {
await saveWebpageSwitch(domain, true);
}
} else {
console.error('URL_CHANGED 无法获取网页内容');
}
})
.catch(async error => {
console.error('URL_CHANGED 获取网页内容失败:', error);
})
.finally(() => {
document.body.classList.remove('loading-content');
});
}
} else if (event.data.type === 'UPDATE_PLACEHOLDER') {
console.log('收到更新placeholder消息:', event.data);
if (messageInput) {
messageInput.setAttribute('placeholder', event.data.placeholder);
if (event.data.timeout) {
setTimeout(() => {
messageInput.setAttribute('placeholder', '输入消息...');
}, event.data.timeout);
}
}
}
});
// 监听输入框变化
messageInput.addEventListener('input', function() {
adjustTextareaHeight({
textarea: this,
config: uiConfig.textarea
});
// 处理 placeholder 的显示
if (this.textContent.trim() === '' && !this.querySelector('.image-tag')) {
// 如果内容空且没有图片标签,清空内容以显示 placeholder
while (this.firstChild) {
this.removeChild(this.firstChild);
}
}
// 移除不必要的 br 标签
const brElements = this.getElementsByTagName('br');
Array.from(brElements).forEach(br => {
if (!br.nextSibling || (br.nextSibling.nodeType === Node.TEXT_NODE && br.nextSibling.textContent.trim() === '')) {
br.remove();
}
});
});
// 处理换行和输入
let isComposing = false; // 跟踪输入法状态
messageInput.addEventListener('compositionstart', () => {
isComposing = true;
});
messageInput.addEventListener('compositionend', () => {
isComposing = false;
});
messageInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
if (isComposing) {
// 如果正在使用输入法,不发送消息
return;
}
e.preventDefault();
const text = this.textContent.trim();
if (text || this.querySelector('.image-tag')) { // 检查是否有文本或图片
sendMessage();
}
} else if (e.key === 'Escape') {
// 按 ESC 键时让输入框失去焦点
messageInput.blur();
}
});
// 修改点击事件监听器
document.addEventListener('click', (e) => {
// 如果点击的不是设置按钮本身和设置菜单,就关闭菜单
if (!settingsButton.contains(e.target) && !settingsMenu.contains(e.target)) {
settingsMenu.classList.remove('visible');
}
});
// 确保设置按钮的点击事件在文档点击事件之前处理
settingsButton.addEventListener('click', (e) => {
e.stopPropagation();
settingsMenu.classList.toggle('visible');
});
// 添加输入框的事件监听器
messageInput.addEventListener('focus', () => {
settingsMenu.classList.remove('visible');
});
// 主题切换
const themeSwitch = document.getElementById('theme-switch');
// 创建主题配置对象
const themeConfig = {
root: document.documentElement,
themeSwitch,
saveTheme: async (theme) => await syncStorageAdapter.set({ theme })
};
// 初始化主题
async function initTheme() {
try {
const result = await syncStorageAdapter.get('theme');
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const isDark = result.theme === 'dark' || (!result.theme && prefersDark);
setTheme(isDark, themeConfig);
} catch (error) {
console.error('初始化主题失败:', error);
// 如果出错,使用系统主题
setTheme(window.matchMedia('(prefers-color-scheme: dark)').matches, themeConfig);
}
}
// 监听主题切换
themeSwitch.addEventListener('change', () => {
setTheme(themeSwitch.checked, themeConfig);
});
// 监听系统主题变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', async (e) => {
const data = await syncStorageAdapter.get('theme');
if (!data.theme) { // 只有在用户没有手动设置主题时才跟随系统
setTheme(e.matches, themeConfig);
}
});
// 初始化主题
await initTheme();
// 修改 saveWebpageSwitch 函数,改进存储和错误处理
async function saveWebpageSwitch(domain, enabled) {
console.log('开始保存网页问答开关状态:', domain, enabled);
try {
const result = await storageAdapter.get('webpageSwitchDomains');
let domains = result.webpageSwitchDomains || {};
// 只在状态发生变化时才更新
if (domains[domain] !== enabled) {
domains[domain] = enabled;
await storageAdapter.set({ webpageSwitchDomains: domains });
console.log('网页问答状态已保存:', domain, enabled);
}
} catch (error) {
console.error('保存网页问答状态失败:', error, domain, enabled);
}
}
// API 设置功能
const apiSettings = document.getElementById('api-settings');
const apiSettingsToggle = document.getElementById('api-settings-toggle');
const backButton = document.querySelector('.back-button');
const apiCards = document.querySelector('.api-cards');
// 加载保存的 API 配置
let apiConfigs = [];
let selectedConfigIndex = 0;
// 使用新的selectCard函数
const handleCardSelect = (template, index) => {
selectCard({
template,
index,
onIndexChange: (newIndex) => {
selectedConfigIndex = newIndex;
},
onSave: saveAPIConfigs,
cardSelector: '.api-card',
onSelect: () => {
// 关闭API设置面板
apiSettings.classList.remove('visible');
}
});
};
// 创建渲染API卡片的辅助函数
const renderAPICardsWithCallbacks = () => {
renderAPICards({
apiConfigs,
apiCardsContainer: apiCards,
templateCard: document.querySelector('.api-card.template'),
...createCardCallbacks({
selectCard: handleCardSelect,
apiConfigs,
selectedConfigIndex,
saveAPIConfigs,
renderAPICardsWithCallbacks
}),
selectedIndex: selectedConfigIndex
});
};
// 从存储加载配置
async function loadAPIConfigs() {
try {
// console.log('开始加载API配置...');
// console.log('当前环境:', isExtensionEnvironment ? '扩展环境' : '网页环境');
// 统一使用 syncStorageAdapter 来实现配置同步
// console.log('使用存储适配器: syncStorageAdapter');
const result = await syncStorageAdapter.get(['apiConfigs', 'selectedConfigIndex']);
// console.log('从存储中读取的配置:', result);
// 分别检查每个配置项
apiConfigs = result.apiConfigs || [{
apiKey: '',
baseUrl: 'https://api.openai.com/v1/chat/completions',
modelName: 'gpt-4o'
}];
// console.log('设置后的 apiConfigs:', apiConfigs);
// 只有当 selectedConfigIndex 为 undefined 或 null 时才使用默认值 0
selectedConfigIndex = result.selectedConfigIndex ?? 0;
// console.log('设置后的 selectedConfigIndex:', selectedConfigIndex);
// 只有在没有任何配置的情况下才保存默认配置
if (!result.apiConfigs) {
// console.log('没有找到已存储的配置,保存默认配置...');
await saveAPIConfigs();
}
} catch (error) {
console.error('加载 API 配置失败:', error);
// console.log('使用默认配置...');
// 只有在出错的情况下才使用默认值
apiConfigs = [{
apiKey: '',
baseUrl: 'https://api.openai.com/v1/chat/completions',
modelName: 'gpt-4o'
}];
selectedConfigIndex = 0;
}
// console.log('最终配置状态:', {
// apiConfigs,
// selectedConfigIndex
// });
// 确保一定会渲染卡片
renderAPICardsWithCallbacks();
}
// 保存配置到存储
async function saveAPIConfigs() {
try {
// console.log('开始保存API配置...');
// console.log('要保存的配置:', {
// apiConfigs,
// selectedConfigIndex
// });
// 统一使用 syncStorageAdapter 来实现配置同步
// console.log('使用存储适配器: syncStorageAdapter');
await syncStorageAdapter.set({
apiConfigs,
selectedConfigIndex
});
// 验证保存是否成功
const savedResult = await syncStorageAdapter.get(['apiConfigs', 'selectedConfigIndex']);
// console.log('验证保存的配置:', savedResult);
} catch (error) {
console.error('保存 API 配置失败:', error);
}
}
// 等待 DOM 加载完成后再初始化
await loadAPIConfigs();
// 显示/隐藏 API 设置
apiSettingsToggle.addEventListener('click', () => {
apiSettings.classList.add('visible');
settingsMenu.classList.remove('visible');
// 确保每次打开设置时都重新渲染卡片
renderAPICardsWithCallbacks();
});
// 返回聊天界面
backButton.addEventListener('click', () => {
apiSettings.classList.remove('visible');
});
// 清空聊天记录功能
const clearChat = document.getElementById('clear-chat');
clearChat.addEventListener('click', () => {
// 如果有正在进行的请求,停止它
if (currentController) {
currentController.abort();
currentController = null;
}
// 清空聊天容器
chatContainer.innerHTML = '';
// 清空聊天历史记录
chatHistory = [];
saveChatHistory();
// 关闭设置菜单
settingsMenu.classList.remove('visible');
// 聚焦输入框并将光标移到末尾
messageInput.focus();
// 移动光标到末尾
const range = document.createRange();
range.selectNodeContents(messageInput);
range.collapse(false);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
});
// 添加点击事件监听
chatContainer.addEventListener('click', () => {
// 击聊天区域时让输入框失去焦点
messageInput.blur();
});
// 监听输入框的焦点状态
messageInput.addEventListener('focus', () => {
// 输入框获得焦点,阻止事件冒泡
messageInput.addEventListener('click', (e) => e.stopPropagation());
});
messageInput.addEventListener('blur', () => {
// 输入框失去焦点时,移除点击事件监听
messageInput.removeEventListener('click', (e) => e.stopPropagation());
});
// 监听 AI 消息的右键点击
chatContainer.addEventListener('contextmenu', (e) => {
const messageElement = e.target.closest('.ai-message');
const codeElement = e.target.closest('pre > code');
if (messageElement) {
currentMessageElement = messageElement;
currentCodeElement = codeElement;
// 根据右键点击的元素类型显示/隐藏相应的菜单项
copyMessageButton.style.display = 'flex';
copyCodeButton.style.display = codeElement ? 'flex' : 'none';
showContextMenu({
event: e,
messageElement,
contextMenu,
stopUpdateButton,
onMessageElementSelect: (element) => {
currentMessageElement = element;
}
});
}
});
// 添加长按触发右键菜单的支持
let touchTimeout;
let touchStartX;
let touchStartY;
const LONG_PRESS_DURATION = 200; // 长按触发时间为200ms
chatContainer.addEventListener('touchstart', (e) => {
const messageElement = e.target.closest('.ai-message');
if (!messageElement) return;
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
touchTimeout = setTimeout(() => {
const codeElement = e.target.closest('pre > code');
currentMessageElement = messageElement;
currentCodeElement = codeElement;
// 根据长按元素类型显示/隐藏相应的菜单项
copyMessageButton.style.display = 'flex';
copyCodeButton.style.display = codeElement ? 'flex' : 'none';
showContextMenu({
event: {
preventDefault: () => {},
clientX: touchStartX,
clientY: touchStartY
},
messageElement,
contextMenu,
stopUpdateButton,
onMessageElementSelect: (element) => {
currentMessageElement = element;
}
});
}, LONG_PRESS_DURATION);
}, { passive: false });
chatContainer.addEventListener('touchmove', (e) => {
// 如果移动超过10px,取消长按
if (touchTimeout &&
(Math.abs(e.touches[0].clientX - touchStartX) > 10 ||
Math.abs(e.touches[0].clientY - touchStartY) > 10)) {
clearTimeout(touchTimeout);
touchTimeout = null;
}
}, { passive: true });
chatContainer.addEventListener('touchend', () => {
if (touchTimeout) {
clearTimeout(touchTimeout);
touchTimeout = null;
}
});
// 点击复制按钮
copyMessageButton.addEventListener('click', () => {
copyMessageContent({
messageElement: currentMessageElement,
onSuccess: () => hideContextMenu({
contextMenu,
onMessageElementReset: () => {
currentMessageElement = null;
currentCodeElement = null;
}
}),
onError: (err) => console.error('复制失败:', err)
});
});
// 点击复制代码按钮
copyCodeButton.addEventListener('click', () => {
if (currentCodeElement) {
const codeText = currentCodeElement.textContent;
navigator.clipboard.writeText(codeText)
.then(() => {
hideContextMenu({
contextMenu,
onMessageElementReset: () => {
currentMessageElement = null;
currentCodeElement = null;
}
});
})
.catch(err => console.error('复制代码失败:', err));
}
});
// 点击其他地方隐藏菜单
document.addEventListener('click', (e) => {
if (!contextMenu.contains(e.target)) {
hideContextMenu({
contextMenu,
onMessageElementReset: () => { currentMessageElement = null; }
});
}
});
// 滚动时隐藏菜单
chatContainer.addEventListener('scroll', () => {
hideContextMenu({
contextMenu,
onMessageElementReset: () => { currentMessageElement = null; }
});
});
// 按下 Esc 键隐藏菜单
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
hideContextMenu({
contextMenu,
onMessageElementReset: () => { currentMessageElement = null; }
});
}
});
// 片粘贴功能
messageInput.addEventListener('paste', async (e) => {
e.preventDefault(); // 阻止默认粘贴行为
const items = Array.from(e.clipboardData.items);
const imageItem = items.find(item => item.type.startsWith('image/'));
if (imageItem) {
// 处理图片粘贴
const file = imageItem.getAsFile();
const reader = new FileReader();
reader.onload = async () => {
const base64Data = reader.result;
const imageTag = createImageTag({
base64Data,
fileName: file.name,
config: uiConfig.imageTag
});
// 在光标位置插入图片标签
const selection = window.getSelection();
const range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(imageTag);
// 移动光标到图片标签后面,并确保不会插入额外的换行
const newRange = document.createRange();
newRange.setStartAfter(imageTag);
newRange.collapse(true);
selection.removeAllRanges();
selection.addRange(newRange);
// 移除可能存在的多余行
const brElements = messageInput.getElementsByTagName('br');
Array.from(brElements).forEach(br => {
if (br.previousSibling && br.previousSibling.classList && br.previousSibling.classList.contains('image-tag')) {
br.remove();
}
});
// 触发输入事件以调整高度
messageInput.dispatchEvent(new Event('input'));
};
reader.readAsDataURL(file);
} else {
// 处理文本粘贴
const text = e.clipboardData.getData('text/plain');
document.execCommand('insertText', false, text);
}
});
// 处理图片标签的删除
messageInput.addEventListener('keydown', (e) => {
if (e.key === 'Backspace' || e.key === 'Delete') {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const startContainer = range.startContainer;
// 检查是否在图片标签旁边
if (startContainer.nodeType === Node.TEXT_NODE && startContainer.textContent === '') {
const previousSibling = startContainer.previousSibling;
if (previousSibling && previousSibling.classList?.contains('image-tag')) {
e.preventDefault();
previousSibling.remove();