-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathapp.js
1773 lines (1502 loc) · 66 KB
/
app.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
// Load i18n translations
let i18n = {};
let currentLanguage = 'en';
let UI_STRINGS = {
buttons: {
send: () => 'Send',
addKey: () => 'Upgrade',
updateKey: () => 'Update Key',
getKey: () => 'Get API Key',
purchase: () => 'Purchase More Token',
downloadFile: () => 'Download file'
},
think: {
initial: () => 'Thinking...',
toggle: () => 'Thoughts',
},
references: {
title: () => 'References',
sources: () => 'Sources'
},
errors: {
invalidKey: () => 'Invalid API key. Please update your key by click the button below.',
insufficientTokens: () => 'Insufficient tokens in your API key. Please purchase more tokens or swap to another key.',
rateLimit: () => 'You have reached the rate limit. Please try again later. You can also upgrade to a higher plan by clicking the button below.'
}
};
// Function to load i18n translations
async function loadTranslations() {
try {
const response = await fetch('i18n.json');
i18n = await response.json();
applyTranslations();
} catch (error) {
console.error('Error loading translations:', error);
}
}
// Function to get translation for a key
function t(key, replacements = {}, fallbackLanguage = 'en') {
const keys = key.split('.');
let value = i18n[currentLanguage];
for (const k of keys) {
if (value && typeof value === 'object' && value !== null && k in value) {
value = value[k];
} else if (value && Array.isArray(value) && !isNaN(parseInt(k)) && parseInt(k) >= 0 && parseInt(k) < value.length) {
value = value[parseInt(k)];
} else {
let fallback = i18n[fallbackLanguage];
if (!fallback) {
fallback = i18n['en']; //ultimate fallback to English
}
let fallbackValue = fallback;
for (const fk of keys) {
if (fallbackValue && typeof fallbackValue === 'object' && fallbackValue !== null && fk in fallbackValue) {
fallbackValue = fallbackValue[fk];
} else if (fallbackValue && Array.isArray(fallbackValue) && !isNaN(parseInt(fk)) && parseInt(fk) >= 0 && parseInt(fk) < fallbackValue.length) {
fallbackValue = fallbackValue[parseInt(fk)];
} else {
return key; // Return the key if no translation found in either language
}
}
value = fallbackValue;
break;
}
}
// Apply replacements if provided
if (typeof value === 'string' && replacements) {
for (const replacementKey in replacements) {
if (replacements.hasOwnProperty(replacementKey)) {
const replacementValue = replacements[replacementKey];
const regex = new RegExp(`{{${replacementKey}}}`, 'g');
value = value.replace(regex, replacementValue);
}
}
}
return value;
}
// Function to apply translations to the UI
function applyTranslations() {
if (!i18n || !i18n[currentLanguage]) {
console.error('No translations found for current language:', currentLanguage);
return;
}
// Update document title and meta tags
document.title = t('title');
// Update meta tags
const metaTags = [
'meta[name="title"]',
'meta[name="description"]',
'meta[property="og:title"]',
'meta[property="og:description"]',
'meta[property="twitter:title"]',
'meta[property="twitter:description"]'
];
metaTags.forEach(selector => {
const tag = document.querySelector(selector);
if (tag) {
const key = selector.includes('description') ? 'description' : 'title';
tag.content = t(key);
}
});
// Update all elements with data-label attributes
document.querySelectorAll('[data-label]').forEach(element => {
const labelKey = element.getAttribute('data-label');
const newVal = t(labelKey);
if (newVal !== labelKey) {
element.textContent = newVal;
}
});
// Update input placeholders
document.querySelectorAll('[data-placeholder]').forEach(input => {
const placeholderKey = input.getAttribute('data-placeholder');
input.placeholder = t(placeholderKey);
});
// Update all elements with data-html attributes
document.querySelectorAll('[data-html]').forEach(element => {
const htmlKey = element.getAttribute('data-html');
element.innerHTML = t(htmlKey);
});
// Update all elements with data-tooltip attributes
document.querySelectorAll('[data-tooltip]').forEach(element => {
const tooltipElement = element.querySelector('.tooltip');
if (tooltipElement) {
tooltipElement.textContent = t(element.getAttribute('data-tooltip'));
}
});
// Update UI_STRINGS with translations
UI_STRINGS = {
buttons: {
send: () => t('buttons.send'),
addKey: () => t('buttons.addKey'),
updateKey: () => t('buttons.updateKey'),
getKey: () => t('buttons.getKey'),
purchase: () => t('buttons.purchase'),
downloadFile: () => t('buttons.downloadFile')
},
think: {
initial: () => t('think.initial'),
toggle: () => t('think.toggle'),
},
references: {
title: () => t('references.title'),
sources: () => t('references.sources')
},
errors: {
invalidKey: () => t('errors.invalidKey'),
insufficientTokens: () => t('errors.insufficientTokens'),
rateLimit: () => t('errors.rateLimit')
}
};
}
// DOM Elements - grouped at the top for better organization
const logo = document.getElementById('logo');
const mainContainer = document.getElementById('main-container');
const chatContainer = document.getElementById('chat-container');
const messageForm = document.getElementById('input-area');
const messageInput = document.getElementById('message-input');
const newChatButton = document.getElementById('new-chat-button');
const apiKeyInput = document.getElementById('api-key-input');
const saveApiKeyBtn = document.getElementById('save-api-key');
const toggleApiKeyBtn = document.getElementById('toggle-api-key');
const toggleApiKeyBtnText = toggleApiKeyBtn.querySelector('span');
const getApiKeyBtn = document.getElementById('get-api-key');
const freeUserRPMInfo = document.getElementById('free-user-rpm');
const apiKeyDialog = document.getElementById('api-key-dialog');
const helpButton = document.getElementById('help-button');
const helpDialog = document.getElementById('help-dialog');
const settingsButton = document.getElementById('settings-button');
const settingsDialog = document.getElementById('settings-dialog');
const dialogCloseBtns = document.querySelectorAll('.dialog-close');
const fileUploadButton = document.getElementById('file-upload-button');
const fileInput = document.getElementById('file-input');
const filePreviewContainer = document.getElementById('file-preview-container');
const inputErrorMessage = document.getElementById('input-error-message');
const loadingSvg = `<svg id="thinking-animation-icon" width="14" height="14" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><style>.spinner_mHwL{animation:spinner_OeFQ .75s cubic-bezier(0.56,.52,.17,.98) infinite; fill:currentColor}.spinner_ote2{animation:spinner_ZEPt .75s cubic-bezier(0.56,.52,.17,.98) infinite;fill:currentColor}@keyframes spinner_OeFQ{0%{cx:4px;r:3px}50%{cx:9px;r:8px}}@keyframes spinner_ZEPt{0%{cx:15px;r:8px}50%{cx:20px;r:3px}}</style><defs><filter id="spinner-gF00"><feGaussianBlur in="SourceGraphic" stdDeviation="1.5" result="y"/><feColorMatrix in="y" mode="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 18 -7" result="z"/><feBlend in="SourceGraphic" in2="z"/></filter></defs><g filter="url(#spinner-gF00)"><circle class="spinner_mHwL" cx="4" cy="12" r="3"/><circle class="spinner_ote2" cx="15" cy="12" r="8"/></g></svg>`;
const BASE_ORIGIN = 'https://deepsearch.jina.ai';
const MAX_TOTAL_SIZE = 10 * 1024 * 1024; // 10MB in bytes
const docIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>'
const imgIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-image"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>'
const SUPPORTED_FILE_TYPES = {
'application/pdf': docIcon,
'text/plain': docIcon,
'image/jpeg': imgIcon,
'image/png': imgIcon,
'image/webp': imgIcon,
};
// State variables
let isLoading = false;
let abortController = null;
let existingMessages = [];
let md;
// Composing state variables for handling IME input
let isComposing = false;
let compositionEnded = false;
// File upload state
let uploadedFiles = [];
// API Key Management
function initializeApiKey() {
const savedKey = localStorage.getItem('api_key') || '';
apiKeyInput.value = savedKey;
getApiKeyBtn.style.display = savedKey ? 'none' : 'block';
freeUserRPMInfo.style.display = savedKey ? 'none' : 'block';
toggleApiKeyBtnText.textContent = savedKey ? UI_STRINGS.buttons.updateKey() : UI_STRINGS.buttons.addKey();
}
// Chat Message Persistence
function saveChatMessages() {
const thinMessage = existingMessages.map(m => {
return {
role: m.role,
content: typeof m.content === 'string' ? m.content : m.content.map(c => ({ type: c.type, text: c.text, mimeType: c.mimeType, fileName: c.fileName })),
id: m.id
};
});
localStorage.setItem('chat_messages', JSON.stringify(thinMessage));
}
function loadChatMessages() {
const savedMessages = localStorage.getItem('chat_messages');
try {
return savedMessages ? JSON.parse(savedMessages) : [];
} catch (e) {
console.error('Error parsing saved messages:', e);
return [];
}
}
// File upload functions
function handleFileUpload(files) {
if (!files || files.length === 0) return;
// Check total size
let totalSize = uploadedFiles.reduce((sum, file) => sum + file.size, 0);
for (const file of files) {
totalSize += file.size;
}
if (totalSize > MAX_TOTAL_SIZE) {
inputErrorMessage.textContent = t('errors.fileSizeLimit');
inputErrorMessage.style.display = 'block';
return;
}
// Process each file
for (const file of files) {
// Check file type
if (!isSupportedFileType(file.type)) {
inputErrorMessage.textContent = t('errors.fileTypeNotSupported') + ': ' + file.name;
inputErrorMessage.style.display = 'block';
continue;
}
// Add file to uploaded files
uploadedFiles.push(file);
// Create file preview
createFilePreview(file);
}
// Reset file input
fileInput.value = '';
}
// Check if file type is supported
function isSupportedFileType(mimeType) {
return mimeType in SUPPORTED_FILE_TYPES;
}
// Create file preview
function createFilePreview(file) {
const reader = new FileReader();
const previewItem = document.createElement('div');
previewItem.classList.add('file-preview-item');
// Create remove button
const removeButton = document.createElement('div');
removeButton.classList.add('remove-file');
removeButton.innerHTML = '×';
removeButton.addEventListener('click', (e) => {
e.stopPropagation();
uploadedFiles = uploadedFiles.filter(f => f !== file);
previewItem.remove();
});
// Create file name element
const fileName = document.createElement('div');
fileName.classList.add('file-name');
fileName.textContent = file.name.length > 15 ? file.name.substring(0, 12) + '...' : file.name;
fileName.title = file.name;
previewItem.appendChild(removeButton);
// Handle different file types
if (file.type.startsWith('image/')) {
reader.onload = (e) => {
const img = document.createElement('img');
img.src = e.target.result;
previewItem.appendChild(img);
previewItem.appendChild(fileName);
};
reader.readAsDataURL(file);
} else {
// For non-image files, show an icon
const fileTypeIcon = document.createElement('div');
fileTypeIcon.classList.add('file-type-icon');
fileTypeIcon.innerHTML = getFileTypeDisplay(file.type);
previewItem.appendChild(fileTypeIcon);
previewItem.appendChild(fileName);
}
filePreviewContainer.appendChild(previewItem);
}
// Helper function to get file type display
function getFileTypeDisplay(mimeType) {
return SUPPORTED_FILE_TYPES[mimeType] || 'FILE';
}
// Initialize API key
initializeApiKey();
// File upload event listeners
fileUploadButton.addEventListener('click', () => {
fileInput.click();
});
fileInput.addEventListener('change', e => handleFileUpload(e.target.files));
saveApiKeyBtn.addEventListener('click', handleApiKeySave);
// Message display functions
function createReferencesSection(content, visitedURLs = []) {
// Don't create section if no content and no URLs
if (!content && (!visitedURLs || visitedURLs.length === 0)) {
return null;
}
const section = document.createElement('div');
section.classList.add('references-section');
const header = document.createElement('div');
header.classList.add('references-header');
header.classList.add('collapsed');
header.setAttribute('data-label', 'references.title');
header.textContent = UI_STRINGS.references.title();
const contentDiv = document.createElement('div');
contentDiv.classList.add('references-content');
contentDiv.innerHTML = content;
header.addEventListener('click', (e) => {
e.stopPropagation();
contentDiv.classList.toggle('expanded');
header.classList.toggle('expanded');
header.classList.toggle('collapsed');
});
section.appendChild(header);
section.appendChild(contentDiv);
// Add favicons section if URLs exist
if (visitedURLs?.length > 0) {
const faviconContainer = document.createElement('div');
faviconContainer.classList.add('references-favicons');
renderFaviconList(visitedURLs).then(faviconList => {
faviconContainer.appendChild(faviconList);
section.appendChild(faviconContainer);
});
}
return section;
}
const renderFaviconList = async (visitedURLs) => {
// Create DOM elements and data structures
const faviconList = document.createElement('div');
faviconList.classList.add('favicon-list');
// Process URLs and create Map of domain -> {urls, element data}
const domainMap = visitedURLs.reduce((map, url) => {
try {
const domain = new URL(url).hostname;
if (!map.has(domain)) {
const img = document.createElement('img');
const item = document.createElement('div');
img.src = 'favicon.ico';
img.width = img.height = 16;
img.alt = domain;
item.classList.add('favicon-item');
item.setAttribute('data-url', url);
item.appendChild(img);
// Add click handler for favicon
item.addEventListener('click', () => {
window.open(url, '_blank');
});
// Add cursor pointer style
item.style.cursor = 'pointer';
faviconList.appendChild(item);
map.set(domain, {
urls: [url],
img,
item
});
} else {
map.get(domain).urls.push(url);
}
// Update tooltip with URL count
const data = map.get(domain);
data.item.setAttribute('title', `${domain}\n${data.urls.length} URLs`);
} catch (e) {
console.error('Invalid URL:', url);
}
return map;
}, new Map());
// Add sources count
const sourceCount = document.createElement('div');
sourceCount.classList.add('sources-count');
sourceCount.textContent = `${visitedURLs.length} `;
const label = document.createElement('span');
label.setAttribute('data-label', 'references.sources');
label.textContent = UI_STRINGS.references.sources();
sourceCount.appendChild(label);
faviconList.appendChild(sourceCount);
// Favicon fetching function with retry support
const fetchFavicons = async (domains) => {
const failedDomains = [];
try {
const response = await fetch(
`https://favicon-fetcher.jina.ai/?domains=${domains.join(',')}&timeout=3000`
);
if (!response.ok) throw new Error('Favicon fetch failed');
const favicons = await response.json();
favicons.forEach(({domain, favicon, type}) => {
if (domainMap.has(domain) && favicon) {
domainMap.get(domain).img.src = `data:${type};base64,${favicon}`;
} else {
failedDomains.push(domain);
}
});
} catch (error) {
console.error('Error fetching favicons:', error);
failedDomains.push(...domains);
}
return failedDomains;
};
// Process domains in batches with retry
const BATCH_SIZE = 16;
const domains = Array.from(domainMap.keys());
let failedDomains = [];
// Initial batch processing
for (let i = 0; i < domains.length; i += BATCH_SIZE) {
failedDomains.push(
...await fetchFavicons(domains.slice(i, i + BATCH_SIZE))
);
}
// Retry failed domains
if (failedDomains.length > 0) {
console.log(`Retrying ${failedDomains.length} failed domains...`);
for (let i = 0; i < failedDomains.length; i += BATCH_SIZE) {
await fetchFavicons(failedDomains.slice(i, i + BATCH_SIZE));
}
}
return faviconList;
};
function createThinkSection(messageDiv) {
const thinkSection = document.createElement('div');
thinkSection.classList.add('think-section');
const thinkHeader = document.createElement('div');
thinkHeader.classList.add('think-header');
thinkHeader.classList.add('expanded');
thinkHeader.setAttribute('data-label', 'think.toggle');
thinkHeader.appendChild(document.createTextNode(UI_STRINGS.think.initial()));
thinkSection.appendChild(thinkHeader);
const thinkContent = document.createElement('div');
thinkContent.classList.add('think-content');
const expanded = localStorage.getItem('think_section_expanded') === 'true';
if (expanded) {
thinkHeader.classList.remove('collapsed');
thinkContent.classList.add('expanded');
} else {
thinkHeader.classList.remove('expanded');
thinkHeader.classList.add('collapsed');
}
thinkSection.addEventListener('click', (e) => {
e.stopPropagation();
thinkContent.classList.toggle('expanded');
thinkHeader.classList.toggle('expanded');
thinkHeader.classList.toggle('collapsed');
localStorage.setItem('think_section_expanded', thinkContent.classList.contains('expanded'));
});
// thinkSection.appendChild(thinkHeader);
thinkSection.appendChild(thinkContent);
messageDiv.prepend(thinkSection);
return thinkSection;
}
function scrollToBottom() {
mainContainer.scrollTop = mainContainer.scrollHeight;
}
function handleTooltipEvent (triggerElement, orientation = 'bottom' | 'top' | 'left' | 'right') {
let tooltip = triggerElement.querySelector('.tooltip');
if (!tooltip) {
tooltip = document.createElement('div');
tooltip.classList.add('tooltip');
tooltip.textContent = t(triggerElement.getAttribute('data-tooltip'));
triggerElement.appendChild(tooltip);
}
triggerElement.addEventListener('mouseenter', () => {
tooltip.style.visibility = 'visible';
switch (orientation) {
case 'top':
tooltip.style.bottom = '125%';
tooltip.style.left = '50%';
tooltip.style.top = 'unset';
tooltip.style.right = 'unset';
tooltip.style.transform = 'translateX(-50%)';
break;
case 'left':
tooltip.style.right = '0';
tooltip.style.top = '125%';
tooltip.style.left = 'unset';
tooltip.style.bottom = 'unset';
tooltip.style.transform = 'unset';
break;
case 'right':
tooltip.style.left = '0';
tooltip.style.top = '125%';
tooltip.style.right = 'unset';
tooltip.style.bottom = 'unset';
tooltip.style.transform = 'unset';
break;
case 'bottom':
default:
tooltip.style.top = '125%';
tooltip.style.left = '50%';
tooltip.style.right = 'unset';
tooltip.style.bottom = 'unset';
tooltip.style.transform = 'translateX(-50%)';
break;
}
});
triggerElement.addEventListener('mouseleave', () => {
tooltip.style.visibility = 'hidden';
});
}
function handleReDoEvent (redoButton) {
if (isLoading) return;
// Find the current message element
const messageElement = redoButton.closest('.message');
if (!messageElement) {
console.error('Current message not found');
return;
};
const currentMessageId = messageElement.getAttribute('id');
const currentMessageIndex = existingMessages.findIndex(m => m.id === currentMessageId);
if (currentMessageIndex < 0) {
console.error('Current message not found in existing messages');
return;
};
// Get the previous user message
let userMessageIndex = currentMessageIndex - 1;
while (userMessageIndex >= 0 && existingMessages[userMessageIndex].role !== 'user') {
userMessageIndex--;
}
const userMessage = existingMessages[userMessageIndex]?.content;
if (!userMessage) {
console.error('No user message found to redo');
return;
};
const allMessages = Array.from(chatContainer.querySelectorAll('.message'));
const startIndex = allMessages.findIndex(m => m.id === currentMessageId);
if (startIndex < 0) return;
// Remove all messages after the current message
allMessages.slice(startIndex).forEach(m => m.remove());
// Remove messages from existingMessages and localStorage
existingMessages.splice(currentMessageIndex);
saveChatMessages();
sendMessage(true);
}
function handleCopyEvent (copyButton, copyIcon, content) {
const checkIcon = `<svg class="action-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>`;
if (!navigator.clipboard) {
console.error('Clipboard API not available');
return
}
navigator.clipboard.writeText(content.trim())
.then(() => {
copyButton.innerHTML = checkIcon;
setTimeout(() => {
copyButton.innerHTML = copyIcon;
}, 2000);
});
}
function createActionButton(content) {
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('action-buttons-container');
// redo button
const redoButton = document.createElement('button');
redoButton.classList.add('redo-button', 'tooltip-container');
redoButton.setAttribute('data-tooltip', 'tooltips.redo');
const redoIcon = `<svg class="action-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-refresh-cw"><polyline points="23 4 23 10 17 10"></polyline><polyline points="1 20 1 14 7 14"></polyline><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path></svg>`;
redoButton.innerHTML = redoIcon;
// copy button
const copyButton = document.createElement('button');
copyButton.classList.add('copy-button', 'tooltip-container');
copyButton.setAttribute('data-tooltip', 'tooltips.copy');
const copyIcon = `<svg class="action-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>`;
copyButton.innerHTML = copyIcon;
buttonContainer.appendChild(redoButton);
buttonContainer.appendChild(copyButton);
redoButton.addEventListener('click', () => {
handleReDoEvent(redoButton);
});
copyButton.addEventListener('click', () => {
handleCopyEvent(copyButton, copyIcon, content);
});
[redoButton, copyButton].forEach(button => {
handleTooltipEvent(button);
});
return buttonContainer;
}
function createMessage(role, content, messageId = null) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', `${role}-message`)
const id = messageId || `message-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
messageDiv.id = id;
if (role === 'assistant') {
messageDiv.innerHTML = `<div id="loading-indicator">${loadingSvg}</div>`;
} else {
// Handle user message with potential file content
if (typeof content === 'string') {
// Simple text message
messageDiv.replaceChildren(renderMarkdown(content, true, [], role));
} else if (Array.isArray(content)) {
// Complex message with text and files
const messageContent = document.createElement('div');
// Process each part
content.forEach(part => {
switch (part.type) {
case 'image':
case 'file':
const fileContainer = document.createElement('div');
fileContainer.classList.add('message-file-container');
const fileLink = document.createElement('div');
fileLink.classList.add('message-file-link');
const fileIcon = document.createElement('span');
fileIcon.classList.add('message-file-icon');
fileIcon.innerHTML = getFileTypeDisplay(part.mimeType);
let fileName;
if (part.fileName) {
fileName = document.createElement('span');
fileName.classList.add('message-file-name');
fileName.setAttribute('data-label', 'buttons.downloadFile');
fileName.textContent = part.fileName;
}
fileLink.appendChild(fileIcon);
if (fileName) {
fileLink.appendChild(fileName);
}
fileContainer.appendChild(fileLink);
messageContent.appendChild(fileContainer);
break;
case 'text':
default:
const textElement = renderMarkdown(part.text, true, [], role);
messageContent.appendChild(textElement);
break;
}
});
messageDiv.appendChild(messageContent);
}
}
chatContainer.appendChild(messageDiv);
updateEmptyState();
scrollToBottom();
return messageDiv;
}
function removeLoadingIndicator(messageDiv) {
const loadingIndicator = messageDiv.querySelector('#loading-indicator');
if (loadingIndicator) {
loadingIndicator.remove();
}
}
function createErrorMessage(message, buttonText, onClick) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', 'assistant-message');
const errorContainer = document.createElement('div');
errorContainer.className = 'error-message';
const errorIcon = `<svg id="error-icon" class="action-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>`;
const errorText = document.createElement('span');
errorText.innerHTML = errorIcon + message;
const actionButton = document.createElement('button');
actionButton.textContent = buttonText;
actionButton.className = 'error-action-button';
actionButton.addEventListener('click', onClick);
errorContainer.appendChild(errorText);
errorContainer.appendChild(actionButton);
messageDiv.appendChild(errorContainer);
chatContainer.appendChild(messageDiv);
scrollToBottom();
}
function initializeMarkdown() {
if (window.markdownit) {
const options = {
html: true,
linkify: true,
typographer: true
};
// Only add highlighting if hljs is available
if (window.hljs) {
options.highlight = function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return '<pre><code class="hljs">' +
hljs.highlight(str, {language: lang, ignoreIllegals: true}).value +
'</code></pre>';
} catch (__) {
}
}
return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
};
}
md = window.markdownit(options)
.use(window.markdownitFootnote)
.use(markdownItTableWrapper);
}
}
function markdownItTableWrapper(md) {
const defaultTableRenderer = md.renderer.rules.table_open || function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options, env, self);
};
md.renderer.rules.table_open = function (tokens, idx, options, env, self) {
return '<div id="table-container">\n' + defaultTableRenderer(tokens, idx, options, env, self);
};
const defaultTableCloseRenderer = md.renderer.rules.table_close || function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options, env, self);
};
md.renderer.rules.table_close = function (tokens, idx, options, env, self) {
return defaultTableCloseRenderer(tokens, idx, options, env, self) + '\n</div>';
};
}
function renderMarkdown(content, returnElement = false, visitedURLs = [], role = 'assistant') {
if (!md) {
initializeMarkdown();
}
const tempDiv = document.createElement('div');
tempDiv.classList.add('markdown-inner');
tempDiv.innerHTML = content;
if (md) {
const rendered = md.render(content);
tempDiv.innerHTML = rendered;
const footnoteAnchors = tempDiv.querySelectorAll('.footnote-ref a');
footnoteAnchors.forEach(a => {
const text = a.textContent.replace(/[\[\]]/g, '');
a.textContent = text;
});
if (role === 'assistant') {
const footnotes = tempDiv.querySelector('.footnotes');
const footnoteContent = footnotes ? footnotes.innerHTML : '';
// Create references section if there are footnotes or visitedURLs
const referencesSection = createReferencesSection(footnoteContent, visitedURLs);
if (referencesSection) {
if (footnotes) {
footnotes.replaceWith(referencesSection);
} else {
tempDiv.appendChild(referencesSection);
}
} else if (footnotes) {
footnotes.remove();
}
} else {
const blockElements = tempDiv.querySelectorAll('p', 'span');
blockElements.forEach(el => {
el.innerHTML = el.innerHTML.replace(/\n/g, '<br>');
});
}
}
return returnElement ? tempDiv : tempDiv.innerHTML;
}
// Message handling functions
// Update empty state class
function updateEmptyState() {
const chatApp = document.getElementById('chat-app');
if (chatContainer.innerHTML.trim() === '') {
chatApp.classList.add('empty-chat');
messageInput.focus();
} else {
chatApp.classList.remove('empty-chat');
}
// blur the input if the chat is loading, incase the keyboard is open on mobile
if (isLoading && new URLSearchParams(window.location.search).get('q')) {
messageInput.blur();
}
}
function clearMessages() {
chatContainer.innerHTML = '';
existingMessages = [];
abortController?.abort();
// Clear messages from localStorage
localStorage.removeItem('chat_messages');
// Clear uploaded files
uploadedFiles = [];
filePreviewContainer.innerHTML = '';
updateEmptyState();
}
const makeAllLinksOpenInNewTab = () => {
// Select all <a> tags on the page
const links = document.querySelectorAll('a');
// Add target="_blank" to each link
links.forEach(link => {
link.setAttribute('target', '_blank');
// Add rel="noopener" for security best practices
link.setAttribute('rel', 'noopener');
});
};
async function sendMessage(redo = false) {
inputErrorMessage.style.display = 'none';
const queryText = messageInput.value.trim();
if (isLoading) return;
if (!queryText && !redo) return;
if (redo && existingMessages.length === 0) return;
abortController = new AbortController();
isLoading = true;
let messageContent;
// Create message content based on text and files
if (uploadedFiles.length > 0) {
messageContent = [];
// Add text part if there's text
if (queryText) {
messageContent.push({
type: 'text',
text: queryText
});
}
// Process files
const filePromises = uploadedFiles.map(file => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const base64Data = reader.result;
if (file.type.startsWith('image/')) {
resolve({
type: 'image',
image: base64Data,
mimeType: file.type,
fileName: file.name
});
} else {
resolve({
type: 'file',
data: base64Data,
mimeType: file.type,
fileName: file.name
});
}
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
});
// Wait for all files to be processed
const fileParts = await Promise.all(filePromises);
messageContent.push(...fileParts);
} else {
// Just text
messageContent = queryText;
}
if (!redo) {
const userMessageId = `message-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
createMessage('user', messageContent, userMessageId);
existingMessages.push({role: 'user', content: messageContent, id: userMessageId});
}
// Clear input and files
messageInput.value = '';
messageInput.style.height = 'auto';
uploadedFiles = [];
filePreviewContainer.innerHTML = '';
// To clear the badge
clearFaviconBadge();