-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat-init.js
More file actions
791 lines (787 loc) · 39 KB
/
chat-init.js
File metadata and controls
791 lines (787 loc) · 39 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
document.addEventListener("DOMContentLoaded", () => {
const { chatBox, chatInput, clearChatBtn, voiceToggleBtn, modelSelect, synth, autoSpeakEnabled, speakMessage, stopSpeaking, showToast, toggleSpeechRecognition, initSpeechRecognition, handleVoiceCommand, speakSentences } = window._chatInternals;
const imagePatterns = window.imagePatterns;
const randomSeed = window.randomSeed;
const generateSessionTitle = messages => {
let title = messages.find(m => m.role === "ai")?.content.replace(/[#_*`]/g, "").trim() || "New Chat";
return title.length > 50 ? title.substring(0, 50) + "..." : title;
};
const checkAndUpdateSessionTitle = () => {
const currentSession = Storage.getCurrentSession();
if (!currentSession.name || currentSession.name === "New Chat") {
const newTitle = generateSessionTitle(currentSession.messages);
if (newTitle && newTitle !== currentSession.name) Storage.renameSession(currentSession.id, newTitle);
}
};
const highlightAllCodeBlocks = () => {
if (!window.Prism) return;
chatBox.querySelectorAll("pre code").forEach(block => Prism.highlightElement(block));
};
const appendMessage = ({ role, content, index, imageUrls = [] }) => {
const container = document.createElement("div");
container.classList.add("message");
container.dataset.index = index;
container.dataset.role = role;
Object.assign(container.style, {
float: role === "user" ? "right" : "left",
clear: "both",
maxWidth: role === "user" ? "40%" : "60%",
marginRight: role === "user" ? "10px" : null,
marginLeft: role !== "user" ? "10px" : null,
});
container.classList.add(role === "user" ? "user-message" : "ai-message");
const bubbleContent = document.createElement("div");
bubbleContent.classList.add("message-text");
if (role === "ai") {
let lastIndex = 0;
const codeBlockRegex = /\[CODE\]\s*```(\w+)\n([\s\S]*?)\n```\s*\[\/CODE\]/g;
let match;
while ((match = codeBlockRegex.exec(content)) !== null) {
const matchStart = match.index;
const matchEnd = matchStart + match[0].length;
if (matchStart > lastIndex) {
const textPart = content.substring(lastIndex, matchStart);
if (textPart.trim()) {
const textNode = document.createTextNode(textPart.trim());
bubbleContent.appendChild(textNode);
}
}
const language = match[1];
const code = match[2];
const pre = document.createElement("pre");
const codeElement = document.createElement("code");
codeElement.className = `language-${language}`;
codeElement.textContent = code;
pre.appendChild(codeElement);
bubbleContent.appendChild(pre);
lastIndex = matchEnd;
}
if (lastIndex < content.length) {
const remainingText = content.substring(lastIndex);
if (remainingText.trim()) {
const textNode = document.createTextNode(remainingText.trim());
bubbleContent.appendChild(textNode);
}
}
if (imageUrls.length > 0) {
imageUrls.forEach(url => {
const imageContainer = createImageElement(url, index);
bubbleContent.appendChild(imageContainer);
});
}
} else {
bubbleContent.textContent = content;
}
container.appendChild(bubbleContent);
const actionsDiv = document.createElement("div");
actionsDiv.className = "message-actions";
if (role === "ai") {
const copyBtn = document.createElement("button");
copyBtn.className = "message-action-btn";
copyBtn.textContent = "Copy";
copyBtn.addEventListener("click", () => {
navigator.clipboard.writeText(content)
.then(() => showToast("AI response copied to clipboard"))
.catch(() => showToast("Failed to copy to clipboard"));
});
actionsDiv.appendChild(copyBtn);
const speakBtn = document.createElement("button");
speakBtn.className = "message-action-btn speak-message-btn";
speakBtn.innerHTML = '<span class="icon">🔊</span> Speak';
speakBtn.addEventListener("click", () => {
stopSpeaking();
const sentences = content.split(/(?<=[.!?])\s+/).filter(s => s.trim().length > 0);
speakSentences(sentences);
});
actionsDiv.appendChild(speakBtn);
const regenBtn = document.createElement("button");
regenBtn.className = "message-action-btn";
regenBtn.textContent = "Re-generate";
regenBtn.addEventListener("click", () => reGenerateAIResponse(index));
actionsDiv.appendChild(regenBtn);
const editAIBtn = document.createElement("button");
editAIBtn.className = "message-action-btn";
editAIBtn.textContent = "Edit";
editAIBtn.addEventListener("click", () => editMessage(index));
actionsDiv.appendChild(editAIBtn);
} else {
const editUserBtn = document.createElement("button");
editUserBtn.className = "message-action-btn";
editUserBtn.textContent = "Edit";
editUserBtn.addEventListener("click", () => editMessage(index));
actionsDiv.appendChild(editUserBtn);
}
container.appendChild(actionsDiv);
bubbleContent.querySelectorAll("pre code").forEach(block => {
const buttonContainer = document.createElement("div");
Object.assign(buttonContainer.style, { display: "flex", gap: "5px", marginTop: "5px" });
const codeContent = block.textContent.trim();
const language = block.className.match(/language-(\w+)/)?.[1] || "text";
const copyCodeBtn = document.createElement("button");
copyCodeBtn.className = "message-action-btn";
copyCodeBtn.textContent = "Copy Code";
copyCodeBtn.style.fontSize = "12px";
copyCodeBtn.addEventListener("click", () => {
navigator.clipboard.writeText(codeContent)
.then(() => showToast("Code copied to clipboard"))
.catch(() => showToast("Failed to copy code"));
});
buttonContainer.appendChild(copyCodeBtn);
const downloadCodeBtn = document.createElement("button");
downloadCodeBtn.className = "message-action-btn";
downloadCodeBtn.textContent = "Download";
downloadCodeBtn.style.fontSize = "12px";
downloadCodeBtn.addEventListener("click", () => downloadCodeAsTxt(codeContent, language));
buttonContainer.appendChild(downloadCodeBtn);
block.parentNode.insertAdjacentElement("afterend", buttonContainer);
});
chatBox.appendChild(container);
chatBox.scrollTop = chatBox.scrollHeight;
highlightAllCodeBlocks();
};
const downloadCodeAsTxt = (codeContent, language) => {
const blob = new Blob([codeContent], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `code-${language}-${Date.now()}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showToast("Code downloaded as .txt");
};
const copyImage = (img, imageId) => {
console.log(`Copying image with ID: ${imageId}`);
if (!img.complete || img.naturalWidth === 0) {
showToast("Image not fully loaded yet. Please try again.");
return;
}
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
try {
ctx.drawImage(img, 0, 0);
canvas.toBlob((blob) => {
if (!blob) {
showToast("Failed to copy image: Unable to create blob.");
return;
}
navigator.clipboard.write([new ClipboardItem({ "image/png": blob })])
.then(() => {
const dataURL = canvas.toDataURL("image/png");
localStorage.setItem(`lastCopiedImage_${imageId}`, dataURL);
showToast("Image copied to clipboard and saved to local storage");
})
.catch(err => {
console.error("Copy image error:", err);
showToast("Failed to copy image: " + err.message);
});
}, "image/png");
} catch (err) {
console.error("Copy image error:", err);
showToast("Failed to copy image due to CORS or other error: " + err.message);
}
};
const downloadImage = (img, imageId) => {
console.log(`Downloading image with ID: ${imageId}`);
if (!img.src) {
showToast("No image source available to download.");
return;
}
fetch(img.src, { mode: "cors" })
.then(response => {
if (!response.ok) throw new Error("Network response was not ok");
return response.blob();
})
.then(blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `image-${imageId}-${Date.now()}.png`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showToast("Image downloaded successfully");
})
.catch(err => {
console.error("Download image error:", err);
showToast("Failed to download image: " + err.message);
});
};
const refreshImage = (img, imageId) => {
console.log(`Refreshing image with ID: ${imageId}`);
if (!img.src || !img.src.includes("image.pollinations.ai")) {
showToast("No valid Pollinations image source to refresh.");
return;
}
const urlObj = new URL(img.src);
const newSeed = Math.floor(Math.random() * 1000000);
urlObj.searchParams.set("seed", newSeed);
urlObj.searchParams.set("nolog", "true");
const newUrl = urlObj.toString();
const loadingDiv = document.createElement("div");
loadingDiv.className = "ai-image-loading";
const spinner = document.createElement("div");
spinner.className = "loading-spinner";
loadingDiv.appendChild(spinner);
Object.assign(loadingDiv.style, { width: img.width + "px", height: img.height + "px" });
img.parentNode.insertBefore(loadingDiv, img);
img.style.display = "none";
img.onload = () => {
loadingDiv.remove();
img.style.display = "block";
showToast("Image refreshed with new seed");
};
img.onerror = () => {
loadingDiv.innerHTML = "⚠️ Failed to refresh image";
Object.assign(loadingDiv.style, { display: "flex", justifyContent: "center", alignItems: "center" });
showToast("Failed to refresh image");
};
img.src = newUrl;
};
const openImageInNewTab = (img, imageId) => {
console.log(`Opening image in new tab with ID: ${imageId}`);
if (!img.src) {
showToast("No image source available to open.");
return;
}
window.open(img.src, "_blank");
showToast("Image opened in new tab");
};
const createImageElement = (url, msgIndex) => {
const imageId = `img-${msgIndex}-${Date.now()}`;
localStorage.setItem(`imageId_${msgIndex}`, imageId);
const imageContainer = document.createElement("div");
imageContainer.className = "ai-image-container";
const loadingDiv = document.createElement("div");
loadingDiv.className = "ai-image-loading";
const spinner = document.createElement("div");
spinner.className = "loading-spinner";
loadingDiv.appendChild(spinner);
Object.assign(loadingDiv.style, { width: "512px", height: "512px" });
imageContainer.appendChild(loadingDiv);
const img = document.createElement("img");
img.src = url;
img.alt = "AI Generated Image";
img.className = "ai-generated-image";
img.style.display = "none";
img.dataset.imageUrl = url;
img.dataset.imageId = imageId;
img.crossOrigin = "anonymous";
img.onload = () => {
loadingDiv.remove();
img.style.display = "block";
attachImageButtonListeners(img, imageId);
};
img.onerror = () => {
loadingDiv.innerHTML = "⚠️ Failed to load image";
loadingDiv.style.display = "flex";
loadingDiv.style.justifyContent = "center";
loadingDiv.style.alignItems = "center";
};
imageContainer.appendChild(img);
const imgButtonContainer = document.createElement("div");
imgButtonContainer.className = "image-button-container";
imgButtonContainer.dataset.imageId = imageId;
imageContainer.appendChild(imgButtonContainer);
return imageContainer;
};
const attachImageButtonListeners = (img, imageId) => {
const imgButtonContainer = document.querySelector(`.image-button-container[data-image-id="${imageId}"]`);
if (!imgButtonContainer) {
console.warn(`No image button container found for image ID: ${imageId}`);
return;
}
console.log(`Attaching image button listeners for image ID: ${imageId}`);
imgButtonContainer.innerHTML = "";
const copyImgBtn = document.createElement("button");
copyImgBtn.className = "message-action-btn";
copyImgBtn.textContent = "Copy Image";
copyImgBtn.style.pointerEvents = "auto";
copyImgBtn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
console.log(`Copy Image button clicked for image ID: ${imageId}`);
copyImage(img, imageId);
});
imgButtonContainer.appendChild(copyImgBtn);
const downloadImgBtn = document.createElement("button");
downloadImgBtn.className = "message-action-btn";
downloadImgBtn.textContent = "Download Image";
downloadImgBtn.style.pointerEvents = "auto";
downloadImgBtn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
console.log(`Download Image button clicked for image ID: ${imageId}`);
downloadImage(img, imageId);
});
imgButtonContainer.appendChild(downloadImgBtn);
const refreshImgBtn = document.createElement("button");
refreshImgBtn.className = "message-action-btn";
refreshImgBtn.textContent = "Refresh Image";
refreshImgBtn.style.pointerEvents = "auto";
refreshImgBtn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
console.log(`Refresh Image button clicked for image ID: ${imageId}`);
refreshImage(img, imageId);
});
imgButtonContainer.appendChild(refreshImgBtn);
const openImgBtn = document.createElement("button");
openImgBtn.className = "message-action-btn";
openImgBtn.textContent = "Open in New Tab";
openImgBtn.style.pointerEvents = "auto";
openImgBtn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
console.log(`Open in New Tab button clicked for image ID: ${imageId}`);
openImageInNewTab(img, imageId);
});
imgButtonContainer.appendChild(openImgBtn);
};
const renderStoredMessages = messages => {
console.log("Rendering stored messages...");
chatBox.innerHTML = "";
messages.forEach((msg, idx) => {
console.log(`Appending message at index ${idx}: ${msg.role}`);
const imgRegex = /(https:\/\/image\.pollinations\.ai\/prompt\/[^ ]+)/g;
const imgMatches = msg.content.match(imgRegex) || [];
appendMessage({
role: msg.role,
content: msg.content,
index: idx,
imageUrls: imgMatches
});
});
messages.forEach((msg, idx) => {
const storedImageId = localStorage.getItem(`imageId_${idx}`);
if (storedImageId) {
const img = chatBox.querySelector(`img[data-image-id="${storedImageId}"]`);
if (img) {
console.log(`Re-attaching image button listeners for stored image ID: ${storedImageId}`);
attachImageButtonListeners(img, storedImageId);
} else {
console.warn(`Image with ID ${storedImageId} not found in DOM`);
}
}
});
highlightAllCodeBlocks();
};
window.addNewMessage = ({ role, content }) => {
const currentSession = Storage.getCurrentSession();
currentSession.messages.push({ role, content });
Storage.updateSessionMessages(currentSession.id, currentSession.messages);
const imgRegex = /(https:\/\/image\.pollinations\.ai\/prompt\/[^ ]+)/g;
const imgMatches = content.match(imgRegex) || [];
appendMessage({
role,
content,
index: currentSession.messages.length - 1,
imageUrls: imgMatches
});
if (role === "ai") checkAndUpdateSessionTitle();
};
const editMessage = msgIndex => {
const currentSession = Storage.getCurrentSession();
const oldMessage = currentSession.messages[msgIndex];
if (!oldMessage) return;
stopSpeaking();
const newContent = prompt("Edit this message:", oldMessage.content);
if (newContent === null || newContent === oldMessage.content) return;
if (oldMessage.role === "user") {
currentSession.messages[msgIndex].content = newContent;
currentSession.messages = currentSession.messages.slice(0, msgIndex + 1);
Storage.updateSessionMessages(currentSession.id, currentSession.messages);
renderStoredMessages(currentSession.messages);
const loadingDiv = document.createElement("div");
loadingDiv.id = `loading-${Date.now()}`;
loadingDiv.classList.add("message", "ai-message");
Object.assign(loadingDiv.style, { float: "left", clear: "both", maxWidth: "60%", marginLeft: "10px" });
loadingDiv.textContent = "Generating response...";
chatBox.appendChild(loadingDiv);
chatBox.scrollTop = chatBox.scrollHeight;
sendToPollinations(() => {
loadingDiv.remove();
highlightAllCodeBlocks();
}, newContent);
showToast("User message updated and new response generated");
} else {
currentSession.messages[msgIndex].content = newContent;
Storage.updateSessionMessages(currentSession.id, currentSession.messages);
renderStoredMessages(currentSession.messages);
highlightAllCodeBlocks();
showToast("AI message updated");
}
};
const reGenerateAIResponse = aiIndex => {
console.log(`Re-generating AI response for index: ${aiIndex}`);
const currentSession = Storage.getCurrentSession();
if (aiIndex < 0 || aiIndex >= currentSession.messages.length || currentSession.messages[aiIndex].role !== "ai") {
showToast("Invalid AI message index for regeneration.");
return;
}
let userIndex = -1;
for (let i = aiIndex - 1; i >= 0; i--) {
if (currentSession.messages[i].role === "user") {
userIndex = i;
break;
}
}
if (userIndex === -1) {
showToast("No preceding user message found to regenerate from.");
return;
}
stopSpeaking();
const userMessage = currentSession.messages[userIndex].content;
currentSession.messages = currentSession.messages.slice(0, userIndex + 1);
Storage.updateSessionMessages(currentSession.id, currentSession.messages);
renderStoredMessages(currentSession.messages);
const loadingDiv = document.createElement("div");
loadingDiv.id = `loading-${Date.now()}`;
loadingDiv.classList.add("message", "ai-message");
Object.assign(loadingDiv.style, { float: "left", clear: "both", maxWidth: "60%", marginLeft: "10px" });
loadingDiv.textContent = "Regenerating response...";
chatBox.appendChild(loadingDiv);
chatBox.scrollTop = chatBox.scrollHeight;
const uniqueUserMessage = `${userMessage} [regen-${Date.now()}-${Math.random().toString(36).substring(2)}]`;
console.log(`Sending re-generate request for user message: ${userMessage} (with unique suffix: ${uniqueUserMessage})`);
window.sendToPollinations(() => {
loadingDiv.remove();
highlightAllCodeBlocks();
checkAndUpdateSessionTitle();
showToast("Response regenerated successfully");
}, uniqueUserMessage);
};
if (voiceToggleBtn) {
voiceToggleBtn.addEventListener("click", window._chatInternals.toggleAutoSpeak);
window._chatInternals.updateVoiceToggleUI();
setTimeout(() => {
if (autoSpeakEnabled) {
const testUtterance = new SpeechSynthesisUtterance("Voice check");
testUtterance.volume = 0.1;
testUtterance.onend = () => {};
testUtterance.onerror = err => {
window._chatInternals.autoSpeakEnabled = false;
localStorage.setItem("autoSpeakEnabled", "false");
window._chatInternals.updateVoiceToggleUI();
showToast("Voice synthesis unavailable. Voice mode disabled.");
};
synth.speak(testUtterance);
}
}, 5000);
}
if (clearChatBtn) {
clearChatBtn.addEventListener("click", () => {
const currentSession = Storage.getCurrentSession();
if (confirm("Are you sure you want to clear this chat?")) {
currentSession.messages = [];
Storage.updateSessionMessages(currentSession.id, currentSession.messages);
chatBox.innerHTML = "";
showToast("Chat cleared");
}
});
}
const checkFirstLaunch = () => {
if (localStorage.getItem("firstLaunch") !== "0") return;
const firstLaunchModal = document.getElementById("first-launch-modal");
if (!firstLaunchModal) return;
firstLaunchModal.classList.remove("hidden");
const closeModal = () => {
firstLaunchModal.classList.add("hidden");
localStorage.setItem("firstLaunch", "1");
};
document.getElementById("first-launch-close").addEventListener("click", closeModal);
document.getElementById("first-launch-complete").addEventListener("click", closeModal);
document.getElementById("setup-theme").addEventListener("click", () => {
firstLaunchModal.classList.add("hidden");
document.getElementById("settings-modal").classList.remove("hidden");
});
document.getElementById("setup-personalization").addEventListener("click", () => {
firstLaunchModal.classList.add("hidden");
document.getElementById("personalization-modal").classList.remove("hidden");
});
document.getElementById("setup-model").addEventListener("click", () => {
firstLaunchModal.classList.add("hidden");
document.getElementById("model-select").focus();
});
};
checkFirstLaunch();
const setupVoiceInputButton = () => {
if (!("webkitSpeechRecognition" in window || "SpeechRecognition" in window)) {
const voiceInputBtn = document.getElementById("voice-input-btn");
if (voiceInputBtn) {
voiceInputBtn.disabled = true;
voiceInputBtn.title = "Voice input not supported in this browser";
}
return;
}
const inputButtonsContainer = document.querySelector(".input-buttons-container");
if (!window._chatInternals.voiceInputBtn && inputButtonsContainer) {
const voiceInputBtn = document.createElement("button");
voiceInputBtn.id = "voice-input-btn";
voiceInputBtn.innerHTML = '<i class="fas fa-microphone"></i>';
voiceInputBtn.title = "Voice input";
inputButtonsContainer.insertBefore(voiceInputBtn, document.getElementById("send-button"));
window._chatInternals.setVoiceInputButton(voiceInputBtn);
voiceInputBtn.addEventListener("click", toggleSpeechRecognition);
}
};
setupVoiceInputButton();
if ("webkitSpeechRecognition" in window || "SpeechRecognition" in window) {
try {
toggleSpeechRecognition();
} catch (err) {
console.error("Automatic speech recognition start failed:", err);
}
}
document.addEventListener("click", e => {
if (e.target.closest(".image-button-container")) {
e.preventDefault();
e.stopPropagation();
console.log("Click detected on image-button-container, preventing propagation");
}
}, true);
const sendButton = document.getElementById("send-button");
const handleSendMessage = () => {
const message = chatInput.value.trim();
if (!message) return;
chatInput.value = "";
chatInput.style.height = "auto";
window.addNewMessage({ role: "user", content: message });
// Typed input should always go to the model. Commands are voice-only.
window.sendToPollinations(() => {
sendButton.disabled = false;
chatInput.disabled = false;
chatInput.focus();
});
sendButton.disabled = true;
chatInput.disabled = true;
};
window._chatInternals.handleSendMessage = handleSendMessage;
chatInput.addEventListener("input", () => {
sendButton.disabled = chatInput.value.trim() === "";
chatInput.style.height = "auto";
chatInput.style.height = chatInput.scrollHeight + "px";
});
sendButton.addEventListener("click", handleSendMessage);
sendButton.disabled = chatInput.value.trim() === "";
chatInput.dispatchEvent(new Event("input"));
const initialSession = Storage.getCurrentSession();
if (initialSession.messages?.length > 0) renderStoredMessages(initialSession.messages);
chatInput.disabled = false;
chatInput.focus();
const voiceChatModal = document.getElementById("voice-chat-modal");
const openVoiceChatModalBtn = document.getElementById("open-voice-chat-modal");
const closeVoiceChatModalBtn = document.getElementById("voice-chat-modal-close");
const voiceSettingsModal = document.getElementById("voice-settings-modal");
const openVoiceSettingsModalBtn = document.getElementById("open-voice-settings-modal");
const voiceChatImage = document.getElementById("voice-chat-image");
let slideshowInterval = null;
const startVoiceChatSlideshow = () => {
if (slideshowInterval) clearInterval(slideshowInterval);
const currentSession = Storage.getCurrentSession();
let lastMessage = currentSession.messages.slice(-1)[0]?.content || "default scene";
let imagePrompt = "";
for (const { pattern, group } of imagePatterns) {
const match = lastMessage.match(pattern);
if (match) {
imagePrompt = match[group].trim();
break;
}
}
if (!imagePrompt) {
imagePrompt = lastMessage.replace(/image|picture|show me|generate/gi, "").trim();
}
imagePrompt = imagePrompt.slice(0, 100) + ", photographic";
const updateImage = () => {
const seed = randomSeed();
voiceChatImage.src = `https://image.pollinations.ai/prompt/${encodeURIComponent(imagePrompt)}?width=512&height=512&seed=${seed}&nolog=true&referrer=unityailab.com`;
};
updateImage();
slideshowInterval = setInterval(updateImage, 10000);
};
const stopVoiceChatSlideshow = () => {
if (slideshowInterval) {
clearInterval(slideshowInterval);
slideshowInterval = null;
}
};
let voiceBuffer = "";
let silenceTimeout = null;
const setupCustomSpeechRecognition = () => {
if (!window._chatInternals.recognition) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SpeechRecognition) {
showToast("Speech recognition not supported in this browser");
return false;
}
window._chatInternals.recognition = new SpeechRecognition();
const recognition = window._chatInternals.recognition;
recognition.continuous = true;
recognition.interimResults = true;
recognition.lang = "en-US";
recognition.onstart = () => {
window._chatInternals.isListening = true;
showToast("Voice recognition active");
document.getElementById("voice-chat-start").disabled = true;
document.getElementById("voice-chat-stop").disabled = false;
};
recognition.onend = () => {
window._chatInternals.isListening = false;
document.getElementById("voice-chat-start").disabled = false;
document.getElementById("voice-chat-stop").disabled = true;
};
recognition.onerror = event => {
window._chatInternals.isListening = false;
document.getElementById("voice-chat-start").disabled = false;
document.getElementById("voice-chat-stop").disabled = true;
const errors = {
"no-speech": "No speech detected. Please try again.",
"not-allowed": "Microphone access denied. Please allow microphone access in your browser settings.",
"service-not-allowed": "Microphone access denied. Please allow microphone access in your browser settings.",
};
showToast(errors[event.error] || "Voice recognition error: " + event.error);
};
recognition.onresult = event => {
let interimTranscript = "";
let finalTranscript = "";
for (let i = event.resultIndex; i < event.results.length; i++) {
const transcript = event.results[i][0].transcript;
if (event.results[i].isFinal) {
const processed = transcript.trim();
if (!handleVoiceCommand(processed)) finalTranscript += processed + " ";
} else {
interimTranscript += transcript;
}
}
voiceBuffer += finalTranscript;
chatInput.value = voiceBuffer + interimTranscript;
if (finalTranscript) {
clearTimeout(silenceTimeout);
silenceTimeout = setTimeout(() => {
if (voiceBuffer.trim()) {
window.addNewMessage({ role: "user", content: voiceBuffer.trim() });
window.sendToPollinations(startVoiceChatSlideshow);
voiceBuffer = "";
chatInput.value = "";
}
}, 1500);
}
};
}
return true;
};
const setupVoiceChatControls = () => {
const modalBody = voiceChatModal.querySelector(".modal-body");
let voiceSelectChat = modalBody.querySelector("#voice-select-voicechat");
if (!voiceSelectChat) {
const voiceSelectContainer = document.createElement("div");
voiceSelectContainer.className = "form-group mb-3";
const voiceSelectLabel = document.createElement("label");
voiceSelectLabel.className = "form-label";
voiceSelectLabel.innerHTML = '<i class="fas fa-headset"></i> Voice Selection:';
voiceSelectLabel.htmlFor = "voice-select-voicechat";
voiceSelectChat = document.createElement("select");
voiceSelectChat.id = "voice-select-voicechat";
voiceSelectChat.className = "form-control";
voiceSelectContainer.appendChild(voiceSelectLabel);
voiceSelectContainer.appendChild(voiceSelectChat);
const insertAfter = modalBody.querySelector("p") || voiceChatImage;
if (insertAfter?.nextSibling) modalBody.insertBefore(voiceSelectContainer, insertAfter.nextSibling);
else modalBody.appendChild(voiceSelectContainer);
}
const existingControls = modalBody.querySelector(".voice-chat-controls");
if (existingControls) existingControls.remove();
const controlsDiv = document.createElement("div");
controlsDiv.className = "voice-chat-controls";
Object.assign(controlsDiv.style, { display: "flex", gap: "10px", marginTop: "15px" });
const startBtn = document.createElement("button");
startBtn.id = "voice-chat-start";
startBtn.className = "btn btn-primary";
startBtn.textContent = "Start Listening";
startBtn.style.width = "100%";
startBtn.style.padding = "10px";
startBtn.disabled = window._chatInternals.isListening;
const stopBtn = document.createElement("button");
stopBtn.id = "voice-chat-stop";
stopBtn.className = "btn btn-danger";
stopBtn.textContent = "Stop Listening";
stopBtn.style.width = "100%";
stopBtn.style.padding = "10px";
stopBtn.disabled = !window._chatInternals.isListening;
controlsDiv.appendChild(startBtn);
controlsDiv.appendChild(stopBtn);
modalBody.appendChild(controlsDiv);
startBtn.addEventListener("click", () => {
if (!setupCustomSpeechRecognition()) return showToast("Failed to initialize speech recognition");
try {
window._chatInternals.recognition.start();
startVoiceChatSlideshow();
} catch (error) {
showToast("Could not start speech recognition: " + error.message);
}
});
stopBtn.addEventListener("click", () => {
if (window._chatInternals.recognition && window._chatInternals.isListening) {
window._chatInternals.recognition.stop();
stopVoiceChatSlideshow();
showToast("Voice recognition stopped");
}
});
};
const updateAllVoiceDropdowns = selectedIndex => {
["voice-select", "voice-select-modal", "voice-settings-modal", "voice-select-voicechat"].forEach(id => {
const dropdown = document.getElementById(id);
if (dropdown) dropdown.value = selectedIndex;
});
};
openVoiceChatModalBtn.addEventListener("click", () => {
voiceChatModal.classList.remove("hidden");
setupVoiceChatControls();
window._chatInternals.populateAllVoiceDropdowns();
});
closeVoiceChatModalBtn.addEventListener("click", () => {
voiceChatModal.classList.add("hidden");
if (window._chatInternals.recognition && window._chatInternals.isListening) window._chatInternals.recognition.stop();
stopVoiceChatSlideshow();
});
openVoiceSettingsModalBtn.addEventListener("click", () => {
voiceSettingsModal.classList.remove("hidden");
window._chatInternals.populateAllVoiceDropdowns();
const voiceSpeedInput = document.getElementById("voice-speed");
const voicePitchInput = document.getElementById("voice-pitch");
const voiceSpeedValue = document.getElementById("voice-speed-value");
const voicePitchValue = document.getElementById("voice-pitch-value");
voiceSpeedInput.value = localStorage.getItem("voiceSpeed") || 0.9;
voicePitchInput.value = localStorage.getItem("voicePitch") || 1.0;
voiceSpeedValue.textContent = `${voiceSpeedInput.value}x`;
voicePitchValue.textContent = `${voicePitchInput.value}x`;
});
document.getElementById("voice-settings-modal-close").addEventListener("click", () => voiceSettingsModal.classList.add("hidden"));
document.getElementById("voice-settings-cancel").addEventListener("click", () => voiceSettingsModal.classList.add("hidden"));
document.getElementById("voice-settings-save").addEventListener("click", () => {
const voiceSpeedInput = document.getElementById("voice-speed");
const voicePitchInput = document.getElementById("voice-pitch");
const voiceSelectModal = document.getElementById("voice-select-modal");
const selectedVoiceIndex = voiceSelectModal.value;
const voiceSpeed = voiceSpeedInput.value;
const voicePitch = voicePitchInput.value;
window._chatInternals.selectedVoice = window._chatInternals.voices[selectedVoiceIndex];
localStorage.setItem("selectedVoiceIndex", selectedVoiceIndex);
localStorage.setItem("voiceSpeed", voiceSpeed);
localStorage.setItem("voicePitch", voicePitch);
window._chatInternals.updateVoiceToggleUI();
updateAllVoiceDropdowns(selectedVoiceIndex);
voiceSettingsModal.classList.add("hidden");
showToast("Voice settings saved");
});
document.getElementById("voice-speed").addEventListener("input", () => {
document.getElementById("voice-speed-value").textContent = `${document.getElementById("voice-speed").value}x`;
});
document.getElementById("voice-pitch").addEventListener("input", () => {
document.getElementById("voice-pitch-value").textContent = `${document.getElementById("voice-pitch").value}x`;
});
});