Spaces:
Running
Running
| const chatContainer = document.getElementById("chat-container"); | |
| const chatBox = document.getElementById("chat-box"); | |
| const input = document.getElementById("user-input"); | |
| const intro = document.getElementById("intro"); | |
| const scrollBtn = document.getElementById("scroll-to-bottom-btn"); | |
| const currentUser = localStorage.getItem('mentorGenUser') || "guest_user"; | |
| let chats = []; | |
| let currentChat = []; | |
| let currentChatId = null; | |
| let generatingSessions = new Set(); | |
| let abortControllers = new Map(); | |
| let currentImageData = null; | |
| /* --- AUDIO ENGINE: MECHANICAL TYPING SOUND --- */ | |
| let audioCtx; | |
| function initAudio() { | |
| if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)(); | |
| if (audioCtx.state === 'suspended') audioCtx.resume(); | |
| } | |
| function playTypingSound() { | |
| if (!audioCtx) return; | |
| const osc = audioCtx.createOscillator(); | |
| const gain = audioCtx.createGain(); | |
| osc.type = 'sine'; | |
| osc.frequency.setValueAtTime(600 + Math.random() * 200, audioCtx.currentTime); | |
| gain.gain.setValueAtTime(0.015, audioCtx.currentTime); | |
| gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.04); | |
| osc.connect(gain); gain.connect(audioCtx.destination); | |
| osc.start(); osc.stop(audioCtx.currentTime + 0.04); | |
| } | |
| /* --- MOBILE LAYOUT LOGIC --- */ | |
| function toggleMobileSidebar() { | |
| document.getElementById('main-sidebar').classList.toggle('mobile-open'); | |
| document.getElementById('sidebar-overlay').classList.toggle('active'); | |
| } | |
| function closeMobileSidebar() { | |
| const sidebar = document.getElementById('main-sidebar'); | |
| const overlay = document.getElementById('sidebar-overlay'); | |
| if (sidebar) sidebar.classList.remove('mobile-open'); | |
| if (overlay) overlay.classList.remove('active'); | |
| } | |
| /* --- ATTACHMENT LOGIC --- */ | |
| function toggleAttachMenu() { | |
| const menu = document.getElementById('attach-menu'); | |
| const icon = document.getElementById('plus-icon'); | |
| if(menu) menu.classList.toggle('show'); | |
| if(icon) icon.style.transform = menu.classList.contains('show') ? 'rotate(45deg)' : 'rotate(0deg)'; | |
| } | |
| document.addEventListener('click', (e) => { | |
| const wrapper = document.querySelector('.attach-wrapper'); | |
| if (wrapper && !wrapper.contains(e.target)) { | |
| const menu = document.getElementById('attach-menu'); | |
| const icon = document.getElementById('plus-icon'); | |
| if (menu) menu.classList.remove('show'); | |
| if (icon) icon.style.transform = 'rotate(0deg)'; | |
| } | |
| }); | |
| function triggerFileInput(type) { toggleAttachMenu(); document.getElementById('file-input').click(); } | |
| function mockDriveUpload() { toggleAttachMenu(); showToast("Drive integration requires active API keys."); } | |
| function handleImageUpload(event) { | |
| const file = event.target.files[0]; | |
| if (!file) return; | |
| const reader = new FileReader(); | |
| reader.onload = function(e) { | |
| currentImageData = e.target.result; | |
| document.getElementById('image-preview').src = currentImageData; | |
| document.getElementById('image-preview-container').style.display = 'inline-block'; | |
| input.focus(); | |
| }; | |
| reader.readAsDataURL(file); | |
| } | |
| function removeImage() { | |
| currentImageData = null; | |
| document.getElementById('file-input').value = ""; | |
| document.getElementById('image-preview-container').style.display = 'none'; | |
| } | |
| document.addEventListener('keydown', (e) => { | |
| if ((e.ctrlKey || e.metaKey) && e.key === 'k') { e.preventDefault(); input.focus(); } | |
| if (e.key === 'ArrowUp' && input.value.trim() === '') { | |
| e.preventDefault(); | |
| for (let i = currentChat.length - 1; i >= 0; i--) { | |
| if (currentChat[i].role === 'user') { input.value = currentChat[i].text; autoResize(input); break; } | |
| } | |
| } | |
| }); | |
| chatContainer.addEventListener("scroll", () => { | |
| if (!scrollBtn) return; | |
| const scrollFromBottom = chatContainer.scrollHeight - chatContainer.scrollTop - chatContainer.clientHeight; | |
| scrollBtn.style.display = scrollFromBottom > 150 ? "flex" : "none"; | |
| }); | |
| function scrollToBottom() { chatContainer.scrollTo({ top: chatContainer.scrollHeight, behavior: "smooth" }); } | |
| marked.setOptions({ | |
| highlight: function(code, lang) { | |
| if (lang && hljs.getLanguage(lang)) { return hljs.highlight(code, { language: lang }).value; } | |
| return hljs.highlightAuto(code).value; | |
| }, | |
| langPrefix: 'hljs language-' | |
| }); | |
| function toggleTheme() { | |
| const body = document.body; const icon = document.getElementById("theme-icon"); | |
| if (body.classList.contains("dark-theme")) { body.classList.replace("dark-theme", "light-theme"); icon.classList.replace("fa-moon", "fa-sun"); } | |
| else { body.classList.replace("light-theme", "dark-theme"); icon.classList.replace("fa-sun", "fa-moon"); } | |
| } | |
| function fillPrompt(text) { input.value = text; autoResize(input); input.focus(); } | |
| function autoResize(el) { el.style.height = 'auto'; el.style.height = el.scrollHeight + 'px'; } | |
| input.addEventListener('keydown', function(e) { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } }); | |
| function showToast(message, isError = false) { | |
| const toast = document.getElementById("toast"); | |
| const icon = isError ? '<i class="fas fa-exclamation-circle" style="color: #ef4444;"></i>' : '<i class="fas fa-check-circle" style="color: #10b981;"></i>'; | |
| toast.innerHTML = `${icon} ${message}`; toast.classList.add("show"); | |
| setTimeout(() => toast.classList.remove("show"), 3000); | |
| } | |
| function shareChat() { | |
| if (!currentChatId || currentChat.length === 0) return showToast("Please start a session first.", true); | |
| const shareUrl = window.location.origin + "/chat?session=" + currentChatId; | |
| if (navigator.clipboard && window.isSecureContext) { | |
| navigator.clipboard.writeText(shareUrl).then(() => showToast("Shareable link copied to clipboard!")).catch(() => fallbackCopyTextToClipboard(shareUrl)); | |
| } else { fallbackCopyTextToClipboard(shareUrl); } | |
| } | |
| function fallbackCopyTextToClipboard(text) { | |
| const textArea = document.createElement("textarea"); textArea.value = text; textArea.style.position = "fixed"; | |
| document.body.appendChild(textArea); textArea.focus(); textArea.select(); | |
| try { document.execCommand('copy'); showToast("Shareable link copied to clipboard!"); } catch (err) { showToast("Failed to copy link.", true); } | |
| document.body.removeChild(textArea); | |
| } | |
| function copyMessageText(iconElement, text) { | |
| navigator.clipboard.writeText(text).then(() => { | |
| const originalClass = iconElement.className; | |
| iconElement.className = "fas fa-check"; iconElement.style.color = "#10b981"; | |
| setTimeout(() => { iconElement.className = originalClass; iconElement.style.color = ""; }, 2000); | |
| }).catch(err => showToast("Failed to copy.", true)); | |
| } | |
| function startListening() { | |
| const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; | |
| if (!SpeechRecognition) return showToast("Microphone not supported.", true); | |
| const rec = new SpeechRecognition(); rec.start(); input.placeholder = "Listening..."; | |
| rec.onresult = e => { input.value += e.results[0][0].transcript; autoResize(input); }; | |
| rec.onend = () => input.placeholder = "Ask anything or attach a photo..."; | |
| } | |
| let botVoice = null; | |
| function setVoice() { | |
| const voices = window.speechSynthesis.getVoices(); | |
| if (voices.length === 0) return; | |
| botVoice = voices.find(v => (v.name.includes('Male') || v.name.includes('David') || v.name.includes('Mark')) && !v.name.includes('Female')); | |
| if (!botVoice) botVoice = voices[0]; | |
| } | |
| window.speechSynthesis.onvoiceschanged = setVoice; setVoice(); | |
| function speakText(text) { | |
| speechSynthesis.cancel(); | |
| let cleanText = text.replace(/`{3}[\s\S]*?`{3}/g, ' [Code block omitted] ') | |
| .replace(/`[^`]*`/g, ' ') | |
| .replace(/[*#_=\-><~]/g, ' ') | |
| .replace(/\s+/g, ' ') | |
| .trim(); | |
| const utterance = new SpeechSynthesisUtterance(cleanText); | |
| if (botVoice) utterance.voice = botVoice; | |
| speechSynthesis.speak(utterance); | |
| } | |
| function stopSpeaking() { speechSynthesis.cancel(); } | |
| function stopGeneration() { if (abortControllers.has(currentChatId)) abortControllers.get(currentChatId).abort(); } | |
| function getCurrentTime() { return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); } | |
| async function sendMessage(textOverride = null, skipUserAppend = false) { | |
| if (currentChatId && generatingSessions.has(currentChatId)) return; | |
| initAudio(); | |
| const text = textOverride || input.value.trim(); | |
| if (!text && !currentImageData) return; | |
| if(intro) intro.style.display = "none"; | |
| if (currentChatId === null) currentChatId = "Session_" + Date.now(); | |
| const reqChatId = currentChatId; const timeSent = getCurrentTime(); const sentImage = currentImageData; | |
| if (!skipUserAppend) { | |
| appendUser(text, timeSent, sentImage); | |
| currentChat.push({ role: "user", text: text, image: sentImage, time: timeSent }); | |
| if(!textOverride) { input.value = ""; input.style.height = 'auto'; } | |
| removeImage(); saveToHistory(); window.history.replaceState(null, null, "?session=" + reqChatId); | |
| } | |
| generatingSessions.add(reqChatId); | |
| const controller = new AbortController(); abortControllers.set(reqChatId, controller); | |
| appendPremiumThinking(); setSendButtonState("stop"); | |
| const startTime = Date.now(); | |
| try { | |
| const res = await fetch("/chat", { | |
| method: "POST", headers: { "Content-Type": "application/json", "ngrok-skip-browser-warning": "true" }, | |
| body: JSON.stringify({ username: currentUser, message: text, image: sentImage }), signal: controller.signal | |
| }); | |
| const data = await res.json(); | |
| const responseTime = ((Date.now() - startTime) / 1000).toFixed(1); | |
| const timeReceived = getCurrentTime(); | |
| if (currentChatId === reqChatId) { | |
| removeThinkingUI(); | |
| currentChat.push({ role: "bot", text: data.reply, time: timeReceived, respTime: responseTime }); | |
| simulateTyping(data.reply, reqChatId, timeReceived, responseTime); | |
| saveToHistory(); | |
| } else { | |
| const sessionIndex = chats.findIndex(c => c.id === reqChatId); | |
| if (sessionIndex > -1) { | |
| chats[sessionIndex].messages.push({ role: "bot", text: data.reply, time: timeReceived, respTime: responseTime }); | |
| saveToHistorySilent(chats[sessionIndex]); | |
| } | |
| } | |
| } catch (e) { | |
| let finalMsg = "System error. Check backend connection."; | |
| if (e.name === 'AbortError') finalMsg = "<em>Response stopped by user.</em>"; | |
| if (currentChatId === reqChatId) { | |
| removeThinkingUI(); | |
| currentChat.push({ role: "bot", text: finalMsg, time: getCurrentTime(), respTime: null }); | |
| appendBot(finalMsg, getCurrentTime(), null); saveToHistory(); | |
| } | |
| } finally { | |
| generatingSessions.delete(reqChatId); abortControllers.delete(reqChatId); | |
| if (currentChatId === reqChatId) setSendButtonState("send"); renderHistory(); | |
| } | |
| } | |
| function setSendButtonState(state) { | |
| const sendBtn = document.getElementById("send-btn"); | |
| if (state === "stop") { | |
| sendBtn.innerHTML = '<i class="fas fa-stop"></i>'; sendBtn.classList.add("stop-mode"); sendBtn.title = "Stop Generation"; sendBtn.onclick = stopGeneration; | |
| } else { | |
| sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i>'; sendBtn.classList.remove("stop-mode"); sendBtn.title = "Send Message"; sendBtn.onclick = () => sendMessage(); | |
| } | |
| } | |
| function simulateTyping(text, reqChatId, timeStr, respTime) { | |
| const wrapper = document.createElement("div"); wrapper.className = "message-wrapper bot"; | |
| const header = document.createElement("div"); header.className = "bot-header"; | |
| header.innerHTML = `<img src="./static/logo.png" class="bot-avatar"> <span class="thinking-text pulse-text">MentoraGen is thinking...</span>`; | |
| wrapper.appendChild(header); | |
| const msg = document.createElement("div"); msg.className = "message"; | |
| wrapper.appendChild(msg); chatBox.appendChild(wrapper); | |
| let i = 0; let buffer = ""; let tickCounter = 0; | |
| const typeInterval = setInterval(() => { | |
| if (currentChatId !== reqChatId) { clearInterval(typeInterval); return; } | |
| buffer += text.substr(i, 4); i += 4; | |
| if (tickCounter % 3 === 0) playTypingSound(); | |
| tickCounter++; | |
| // Inject the WhatsApp style time at the end of the parsed markdown | |
| msg.innerHTML = marked.parse(buffer) + `<span class="msg-time bot-time">${timeStr}</span>`; | |
| chatContainer.scrollTop = chatContainer.scrollHeight; | |
| if (i >= text.length) { | |
| clearInterval(typeInterval); | |
| msg.innerHTML = marked.parse(text) + `<span class="msg-time bot-time">${timeStr}</span>`; | |
| msg.querySelectorAll('pre code').forEach((block) => { try { hljs.highlightElement(block); } catch(e) {} }); | |
| addCodeCopyButtons(msg); | |
| header.innerHTML = `<img src="./static/logo.png" class="bot-avatar"> <span class="thinking-text">Thinking for ${respTime} seconds</span>`; | |
| wrapper.appendChild(createBotActions(text, timeStr)); // Time is removed from the actions visually now | |
| chatContainer.scrollTop = chatContainer.scrollHeight; | |
| } | |
| }, 10); | |
| } | |
| function addCodeCopyButtons(container) { | |
| container.querySelectorAll('pre').forEach(pre => { | |
| if (pre.querySelector('.code-header')) return; | |
| const codeBlock = pre.querySelector('code'); let lang = "Code"; | |
| if (codeBlock && codeBlock.className) { const match = codeBlock.className.match(/language-(\w+)/); if (match) lang = match[1]; } | |
| const header = document.createElement('div'); header.className = 'code-header'; header.innerHTML = `<span class="code-lang">${lang}</span>`; | |
| const btn = document.createElement('button'); btn.className = 'copy-code-btn'; btn.innerHTML = '<i class="far fa-clipboard"></i> Copy code'; | |
| btn.onclick = () => { navigator.clipboard.writeText(codeBlock.innerText); btn.innerHTML = '<i class="fas fa-check" style="color:#10b981;"></i> Copied!'; | |
| setTimeout(() => { btn.innerHTML = '<i class="far fa-clipboard"></i> Copy code'; }, 2000); }; | |
| header.appendChild(btn); pre.prepend(header); | |
| }); | |
| } | |
| function appendPremiumThinking() { | |
| if (document.getElementById("thinking-wrapper")) return; | |
| const wrapper = document.createElement("div"); wrapper.className = "message-wrapper bot"; wrapper.id = "thinking-wrapper"; | |
| wrapper.innerHTML = `<div class="bot-header"><img src="./static/logo.png" class="bot-avatar"> <span class="thinking-text pulse-text">MentoraGen is thinking...</span></div>`; | |
| chatBox.appendChild(wrapper); chatContainer.scrollTop = chatContainer.scrollHeight; | |
| } | |
| function removeThinkingUI() { | |
| const thinkingWrapper = document.getElementById("thinking-wrapper"); | |
| if (thinkingWrapper) thinkingWrapper.remove(); | |
| } | |
| function createUserActions(text, timeStr) { | |
| const actions = document.createElement("div"); | |
| actions.className = "msg-actions"; | |
| // Time is physically removed from here | |
| actions.innerHTML = ` | |
| <i class="far fa-copy" title="Copy Message" onclick="copyMessageText(this, \`${text.replace(/`/g, '\\`')}\`)"></i> | |
| <i class="fas fa-edit" title="Edit Message" onclick="editUserMessageInline(this, \`${text.replace(/`/g, '\\`')}\`)"></i> | |
| `; | |
| return actions; | |
| } | |
| function createBotActions(text, timeStr) { | |
| const actions = document.createElement("div"); actions.className = "msg-actions"; | |
| const btnCopy = document.createElement("i"); btnCopy.className = "far fa-copy"; btnCopy.title = "Copy"; btnCopy.onclick = (e) => copyMessageText(e.target, text); | |
| const btnLike = document.createElement("i"); btnLike.className = "far fa-thumbs-up"; | |
| const btnDislike = document.createElement("i"); btnDislike.className = "far fa-thumbs-down"; | |
| btnLike.onclick = function() { | |
| this.classList.toggle("fas"); this.classList.toggle("far"); | |
| btnDislike.className = "far fa-thumbs-down"; btnDislike.style.color = ""; | |
| this.style.color = this.classList.contains("fas") ? "var(--accent-solid)" : ""; | |
| if (this.classList.contains("fas")) showToast("Thank you for your feedback"); | |
| }; | |
| btnDislike.onclick = function() { | |
| this.classList.toggle("fas"); this.classList.toggle("far"); | |
| btnLike.className = "far fa-thumbs-up"; btnLike.style.color = ""; | |
| this.style.color = this.classList.contains("fas") ? "#ef4444" : ""; | |
| if (this.classList.contains("fas")) showToast("Share your valuable opinion in contact section for improvement", true); | |
| }; | |
| const btnSpeak = document.createElement("i"); btnSpeak.className = "fas fa-volume-up"; btnSpeak.onclick = () => speakText(text); | |
| const btnStop = document.createElement("i"); btnStop.className = "fas fa-stop-circle"; btnStop.onclick = stopSpeaking; | |
| // Time is physically removed from here | |
| actions.append(btnCopy, btnLike, btnDislike, btnSpeak, btnStop); return actions; | |
| } | |
| function editUserMessageInline(iconElement, oldText) { | |
| const wrapper = iconElement.closest('.message-wrapper'); const msgDiv = wrapper.querySelector('.message'); const actionsDiv = wrapper.querySelector('.msg-actions'); | |
| const originalHTML = msgDiv.innerHTML; actionsDiv.style.display = 'none'; | |
| msgDiv.innerHTML = `<textarea class="inline-edit-box" rows="3">${oldText}</textarea><div class="inline-edit-actions"><button class="btn-cancel">Cancel</button><button class="btn-save">Send</button></div>`; | |
| const textarea = msgDiv.querySelector('.inline-edit-box'); textarea.focus(); | |
| msgDiv.querySelector('.btn-cancel').onclick = () => { msgDiv.innerHTML = originalHTML; actionsDiv.style.display = 'flex'; }; | |
| msgDiv.querySelector('.btn-save').onclick = () => { | |
| const newText = textarea.value.trim(); | |
| if(!newText || newText === oldText) { msgDiv.innerHTML = originalHTML; actionsDiv.style.display = 'flex'; return; } | |
| let nextSibling = wrapper.nextElementSibling; while(nextSibling) { const toRemove = nextSibling; nextSibling = nextSibling.nextElementSibling; toRemove.remove(); } | |
| const index = Array.from(chatBox.querySelectorAll('.message-wrapper')).indexOf(wrapper); const updatedTime = getCurrentTime(); | |
| if (index > -1) { currentChat = currentChat.slice(0, index + 1); currentChat[index].text = newText; currentChat[index].time = updatedTime; saveToHistory(); } | |
| // WhatsApp style rebuild for edited user message | |
| msgDiv.innerHTML = ''; | |
| const textContainer = document.createElement("div"); | |
| textContainer.className = "user-text-content clamped-text"; | |
| textContainer.innerText = newText; | |
| msgDiv.appendChild(textContainer); | |
| const timeSpan = document.createElement("span"); | |
| timeSpan.className = "msg-time user-time"; | |
| timeSpan.innerText = updatedTime; | |
| msgDiv.appendChild(timeSpan); | |
| wrapper.replaceChild(createUserActions(newText, updatedTime), actionsDiv); sendMessage(newText, true); | |
| }; | |
| } | |
| function appendUser(text, time = null, imageData = null) { | |
| if (!time) time = getCurrentTime(); | |
| const wrapper = document.createElement("div"); | |
| wrapper.className = "message-wrapper user"; | |
| const msg = document.createElement("div"); | |
| msg.className = "message"; | |
| if (imageData) { | |
| const imgEl = document.createElement("img"); | |
| imgEl.src = imageData; | |
| imgEl.className = "chat-uploaded-img"; | |
| msg.appendChild(imgEl); | |
| } | |
| if (text) { | |
| const textContainer = document.createElement("div"); | |
| textContainer.className = "user-text-content clamped-text"; | |
| textContainer.innerText = text; | |
| msg.appendChild(textContainer); | |
| requestAnimationFrame(() => { | |
| if (textContainer.scrollHeight > textContainer.clientHeight) { | |
| const expandBtn = document.createElement("div"); | |
| expandBtn.className = "expand-toggle"; | |
| expandBtn.innerHTML = '<i class="fas fa-chevron-down"></i>'; | |
| expandBtn.onclick = function() { | |
| textContainer.classList.toggle("expanded"); | |
| this.innerHTML = textContainer.classList.contains("expanded") ? '<i class="fas fa-chevron-up"></i>' : '<i class="fas fa-chevron-down"></i>'; | |
| }; | |
| msg.appendChild(expandBtn); | |
| } | |
| }); | |
| } | |
| // Inject the WhatsApp style time at the end of the User bubble | |
| const timeSpan = document.createElement("span"); | |
| timeSpan.className = "msg-time user-time"; | |
| timeSpan.innerText = time; | |
| msg.appendChild(timeSpan); | |
| wrapper.appendChild(msg); | |
| wrapper.appendChild(createUserActions(text, time)); | |
| chatBox.appendChild(wrapper); | |
| chatContainer.scrollTop = chatContainer.scrollHeight; | |
| } | |
| function appendBot(text, time = null, respTime = null) { | |
| if (!time) time = getCurrentTime(); | |
| const wrapper = document.createElement("div"); wrapper.className = "message-wrapper bot"; | |
| const latencyText = respTime ? `Thinking for ${respTime} seconds` : "MentoraGen"; | |
| wrapper.innerHTML = `<div class="bot-header"><img src="./static/logo.png" class="bot-avatar"> <span class="thinking-text">${latencyText}</span></div>`; | |
| const msg = document.createElement("div"); msg.className = "message"; | |
| // Inject the WhatsApp style time at the end of the AI bubble | |
| msg.innerHTML = marked.parse(text) + `<span class="msg-time bot-time">${time}</span>`; | |
| msg.querySelectorAll('pre code').forEach((block) => { try { hljs.highlightElement(block); } catch(e) {} }); | |
| addCodeCopyButtons(msg); | |
| wrapper.appendChild(msg); wrapper.appendChild(createBotActions(text, time)); | |
| chatBox.appendChild(wrapper); chatContainer.scrollTop = chatContainer.scrollHeight; | |
| } | |
| function generateSummary(text) { | |
| let cleanText = text.replace(/[^a-zA-Z0-9 ]/g, " ").replace(/\s+/g, " ").trim(); | |
| const fillers = ["can you explain how to", "can you explain how", "explain how", "what is the difference between", "how do i", "tell me about", "debug this", "write a", "what are", "what is", "difference between"]; | |
| let lowerText = cleanText.toLowerCase(); | |
| for (let filler of fillers) { if (lowerText.startsWith(filler)) { cleanText = cleanText.substring(filler.length).trim(); break; } } | |
| const words = cleanText.split(" "); let title = words.slice(0, 4).join(" ") + (words.length > 4 ? "..." : ""); | |
| return title.length === 0 ? "New Session" : title.split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' '); | |
| } | |
| async function loadAllChats() { | |
| if (currentUser === "guest_user") return; | |
| try { | |
| const res = await fetch("/get_chats/" + currentUser, { headers: {"ngrok-skip-browser-warning": "true"} }); | |
| if (res.ok) { | |
| chats = await res.json(); | |
| renderHistory(); | |
| } | |
| } catch (e) { console.error("Could not load chats from DB", e); } | |
| } | |
| async function saveToHistory() { | |
| if (!currentChatId || currentChat.length === 0) return; | |
| const sessionData = { id: currentChatId, title: generateSummary(currentChat[0].text || "Image Upload"), messages: [...currentChat] }; | |
| const existingIndex = chats.findIndex(c => c.id === currentChatId); | |
| if (existingIndex > -1) chats[existingIndex] = sessionData; | |
| else chats.unshift(sessionData); | |
| renderHistory(); | |
| fetch("/save_chat", { | |
| method: "POST", headers: { "Content-Type": "application/json", "ngrok-skip-browser-warning": "true" }, | |
| body: JSON.stringify({ chat_id: sessionData.id, username: currentUser, title: sessionData.title, messages: sessionData.messages }) | |
| }).catch(e => console.log("DB save failed", e)); | |
| } | |
| function saveToHistorySilent(sessionData) { | |
| fetch("/save_chat", { | |
| method: "POST", headers: { "Content-Type": "application/json", "ngrok-skip-browser-warning": "true" }, | |
| body: JSON.stringify({ chat_id: sessionData.id, username: currentUser, title: sessionData.title, messages: sessionData.messages }) | |
| }).catch(e => console.log("DB silent save failed", e)); | |
| } | |
| async function deleteChat(e, id) { | |
| e.stopPropagation(); | |
| chats = chats.filter(c => c.id !== id); | |
| currentChatId === id ? newChat() : renderHistory(); | |
| fetch("/delete_chat/" + id, { method: "DELETE", headers: { "ngrok-skip-browser-warning": "true" } }).catch(e => console.log("DB delete failed", e)); | |
| } | |
| function renderHistory() { | |
| const ul = document.getElementById("history"); ul.innerHTML = ""; | |
| chats.forEach(session => { | |
| const li = document.createElement("li"); | |
| if (session.id === currentChatId) li.classList.add("active"); | |
| li.onclick = () => loadSession(session); | |
| li.innerHTML = `<i class="fas fa-message" style="color: var(--accent-solid); opacity: 0.8;"></i><span class="history-text">${session.title}</span><i class="fas fa-trash delete-chat-btn" onclick="deleteChat(event, '${session.id}')" title="Delete Session"></i>`; | |
| ul.appendChild(li); | |
| }); | |
| } | |
| function resetBackendContext() { | |
| fetch("/chat", { method: "POST", headers: { "Content-Type": "application/json", "ngrok-skip-browser-warning": "true" }, body: JSON.stringify({ username: currentUser, message: "reset" }) }).catch(e => console.log("Context isolated.")); | |
| } | |
| function loadSession(session) { | |
| resetBackendContext(); currentChatId = session.id; currentChat = session.messages; chatBox.innerHTML = ""; | |
| if(intro) intro.style.display = "none"; | |
| currentChat.forEach(msg => { if(msg.role === "user") appendUser(msg.text, msg.time, msg.image); else appendBot(msg.text, msg.time, msg.respTime); }); | |
| setSendButtonState(generatingSessions.has(currentChatId) ? "stop" : "send"); | |
| window.history.replaceState(null, null, "?session=" + currentChatId); | |
| renderHistory(); | |
| closeMobileSidebar(); | |
| } | |
| function newChat() { | |
| resetBackendContext(); currentChat = []; currentChatId = null; chatBox.innerHTML = ""; | |
| if(intro) { intro.style.display = "flex"; chatBox.appendChild(intro); } | |
| stopSpeaking(); setSendButtonState("send"); window.history.replaceState(null, null, window.location.pathname); | |
| renderHistory(); | |
| closeMobileSidebar(); | |
| } | |
| async function init() { | |
| const savedUser = localStorage.getItem('mentorGenUser'); | |
| const profileBtn = document.getElementById('user-profile-btn'); | |
| const userNameEl = document.querySelector('.user-name'); | |
| const userActionEl = document.querySelector('.user-action'); | |
| if (savedUser) { | |
| if (userNameEl) userNameEl.innerText = savedUser; | |
| if (userActionEl) userActionEl.innerText = "Manage Profile"; | |
| if (profileBtn) { profileBtn.href = "/profile"; profileBtn.onclick = null; } | |
| } else { | |
| if (userNameEl) userNameEl.innerText = "Guest User"; | |
| if (userActionEl) userActionEl.innerText = "Log in / Sign up"; | |
| if (profileBtn) { profileBtn.href = "/login"; profileBtn.onclick = null; } | |
| } | |
| await loadAllChats(); | |
| const sharedSessionId = new URLSearchParams(window.location.search).get('session'); | |
| if (sharedSessionId) { | |
| const sessionToLoad = chats.find(c => c.id === sharedSessionId); | |
| if (sessionToLoad) { loadSession(sessionToLoad); } else { showToast("Shared session not found.", true); newChat(); } | |
| } else { newChat(); } | |
| } | |
| init(); |