document.addEventListener("DOMContentLoaded", () => { const chatHistory = document.getElementById("chat-history"); const messageInput = document.getElementById("message-input"); const sendBtn = document.getElementById("send-btn"); const clearBtn = document.getElementById("clear-btn"); const typingIndicator = document.getElementById("typing-indicator"); // Auto-resize textarea messageInput.addEventListener("input", function() { this.style.height = "auto"; this.style.height = (this.scrollHeight < 150 ? this.scrollHeight : 150) + "px"; }); // Handle Enter key (Shift+Enter for new line) messageInput.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendMessage(); } }); sendBtn.addEventListener("click", sendMessage); clearBtn.addEventListener("click", async () => { if(confirm("Sohbet geçmişini silmek istediğinize emin misiniz?")) { chatHistory.innerHTML = `
`; // Call backend to clear memory try { await fetch("/chat/default", { method: "DELETE" }); } catch (err) { console.error("Failed to clear backend chat history", err); } } }); function addMessage(content, sender) { const msgDiv = document.createElement("div"); msgDiv.className = `message ${sender}-message`; const contentDiv = document.createElement("div"); contentDiv.className = "message-content"; // Use marked to parse markdown if it's the bot, else just text if (sender === "bot") { contentDiv.innerHTML = marked.parse(content); } else { contentDiv.textContent = content; } msgDiv.appendChild(contentDiv); chatHistory.appendChild(msgDiv); // Scroll to bottom setTimeout(() => { chatHistory.scrollTop = chatHistory.scrollHeight; }, 50); } async function sendMessage() { const text = messageInput.value.trim(); if (!text) return; // Reset input messageInput.value = ""; messageInput.style.height = "auto"; // Add user message to UI addMessage(text, "user"); // Show typing indicator typingIndicator.style.display = "flex"; chatHistory.appendChild(typingIndicator); chatHistory.scrollTop = chatHistory.scrollHeight; try { const response = await fetch("/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: text, session_id: "default" }) }); if (!response.ok) { throw new Error("Sunucu hatası oluştu."); } const data = await response.json(); // Hide typing indicator typingIndicator.style.display = "none"; // Add bot response addMessage(data.response, "bot"); } catch (error) { typingIndicator.style.display = "none"; addMessage("Üzgünüm, bir hata oluştu: " + error.message, "bot"); } } });