Flask / static /script.js
UntilDot's picture
Upload 10 files
718aa48 verified
raw
history blame
1.98 kB
// === Theme Toggle ===
const themeToggle = document.getElementById("themeToggle");
const html = document.documentElement;
// Load from localStorage or system preference
function setInitialTheme() {
const savedTheme = localStorage.getItem("theme");
if (savedTheme === "dark") {
html.classList.add("dark");
} else if (savedTheme === "light") {
html.classList.remove("dark");
} else {
// Auto-detect
const prefersDark = window.matchMedia(
"(prefers-color-scheme: dark)",
).matches;
if (prefersDark) html.classList.add("dark");
else html.classList.remove("dark");
}
}
setInitialTheme();
// Toggle theme
themeToggle.addEventListener("click", () => {
const isDark = html.classList.toggle("dark");
localStorage.setItem("theme", isDark ? "dark" : "light");
});
// === Chat Handling ===
const chatForm = document.getElementById("chatForm");
const userInput = document.getElementById("userInput");
const chatContainer = document.getElementById("chatContainer");
function appendMessage(role, text) {
const div = document.createElement("div");
div.className = `p-3 rounded shadow max-w-2xl ${role === "user" ? "bg-blue text-fg0 self-end" : "bg-green text-fg0 self-start"}`;
div.innerText = text;
chatContainer.appendChild(div);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
chatForm.addEventListener("submit", async (e) => {
e.preventDefault();
const prompt = userInput.value.trim();
if (!prompt) return;
appendMessage("user", prompt);
userInput.value = "";
appendMessage("bot", "Thinking...");
const response = await fetch("/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt }),
});
chatContainer.lastChild.remove(); // remove 'Thinking...'
if (response.ok) {
const data = await response.json();
appendMessage("bot", data.response);
} else {
appendMessage("bot", "An error occurred. Please try again.");
}
});