Jasleen05's picture
Update static folder
675b901 verified
raw
history blame
7.42 kB
window.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("chat-form");
const input = document.getElementById("user-input");
const chatBox = document.getElementById("chat-box");
const historyList = document.getElementById("history-list");
const newChatBtn = document.getElementById("new-chat-btn"); // โœ… Use existing button
let currentSession = null;
// ๐Ÿ“† Format time
function formatTime(iso) {
try {
const d = new Date(iso);
return d.toLocaleString("en-IN", {
hour: "numeric",
minute: "2-digit",
hour12: true,
day: "2-digit",
month: "short",
year: "numeric",
});
} catch (err) {
console.error("Error formatting time:", err);
return "(no date)";
}
}
// ๐Ÿ’พ Load full chat of selected session
async function loadSession(sessionId) {
try {
const res = await fetch(`/history/${sessionId}`, {
method: "GET",
headers: { "Content-Type": "application/json" },
});
if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to fetch history`);
const data = await res.json();
chatBox.innerHTML = "";
currentSession = sessionId;
if (data.length === 0) {
chatBox.innerHTML = `<div class="msg bot-msg">No messages in this session yet.</div>`;
} else {
data.forEach(entry => {
chatBox.innerHTML += `
<div class="msg user-msg"><strong>You:</strong> ${entry.user}</div>
<div class="msg bot-msg"><strong>Bot:</strong> ${entry.bot}</div>
`;
});
}
chatBox.scrollTop = chatBox.scrollHeight;
// Highlight active session
[...historyList.children].forEach(li => li.classList.remove("active"));
const activeLi = document.querySelector(`[data-id="${sessionId}"]`);
if (activeLi) activeLi.classList.add("active");
} catch (err) {
console.error(`Error loading session ${sessionId}:`, err);
chatBox.innerHTML = `<div class="msg bot-msg">โš ๏ธ Could not load chat session: ${err.message}</div>`;
}
}
// ๐Ÿ“œ Load all session summaries
async function loadHistory() {
try {
const res = await fetch("/sessions", {
method: "GET",
headers: { "Content-Type": "application/json" },
});
if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to fetch sessions`);
const sessions = await res.json();
historyList.innerHTML = "";
if (sessions.length === 0) {
historyList.innerHTML = "<li>No chat sessions available.</li>";
return;
}
sessions.forEach(s => {
const li = document.createElement("li");
li.className = "session-entry";
li.setAttribute("data-id", s.session_id);
const formatted = s.created_at ? formatTime(s.created_at) : "(no date)";
li.innerHTML = `
<span class="session-text">${formatted}</span>
<button class="delete-btn" title="Delete">๐Ÿ—‘๏ธ</button>
`;
// โœ… Load session on click
li.querySelector(".session-text").addEventListener("click", () => loadSession(s.session_id));
// โœ… Delete session
li.querySelector(".delete-btn").addEventListener("click", async (e) => {
e.stopPropagation();
if (confirm("๐Ÿ—‘๏ธ Delete this chat session?")) {
try {
const res = await fetch(`/sessions/${s.session_id}`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
});
if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to delete session`);
if (s.session_id === currentSession) {
chatBox.innerHTML = `<div class="msg bot-msg">Chat session deleted.</div>`;
currentSession = null;
}
loadHistory();
} catch (err) {
console.error(`Error deleting session ${s.session_id}:`, err);
alert(`Failed to delete session: ${err.message}`);
}
}
});
historyList.appendChild(li);
});
// Load the current session if it exists
if (currentSession) {
loadSession(currentSession);
}
} catch (err) {
console.error("Error loading sessions:", err);
historyList.innerHTML = `<li>โš ๏ธ Failed to load chat sessions: ${err.message}</li>`;
}
}
// ๐Ÿ“ Handle new message submission
form.addEventListener("submit", async (e) => {
e.preventDefault();
const message = input.value.trim();
if (!message) return;
chatBox.innerHTML += `<div class="msg user-msg"><strong>You:</strong> ${message}</div>`;
input.value = "";
input.disabled = true;
chatBox.scrollTop = chatBox.scrollHeight;
try {
const response = await fetch("/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: Failed to send message`);
const data = await response.json();
const botResponse = data.response || data.error || "โš ๏ธ No response";
chatBox.innerHTML += `<div class="msg bot-msg"><strong>Bot:</strong> ${botResponse}</div>`;
chatBox.scrollTop = chatBox.scrollHeight;
loadHistory(); // Refresh session list to include new messages
} catch (error) {
console.error("Error sending message:", error);
chatBox.innerHTML += `<div class="msg bot-msg">โš ๏ธ Error getting response: ${error.message}</div>`;
}
input.disabled = false;
input.focus();
});
// โž• Create new chat session
newChatBtn.addEventListener("click", async () => {
try {
const res = await fetch("/new_session", {
method: "GET",
headers: { "Content-Type": "application/json" },
});
if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to create new session`);
const data = await res.json();
currentSession = data.session_id;
chatBox.innerHTML = `<div class="msg bot-msg">New chat session started.</div>`;
await loadHistory();
await loadSession(currentSession);
} catch (err) {
console.error("Error creating new session:", err);
chatBox.innerHTML = `<div class="msg bot-msg">โš ๏ธ Failed to create new session: ${err.message}</div>`;
}
});
// ๐Ÿš€ Initialize: Load current session history
async function init() {
try {
const res = await fetch("/history", {
method: "GET",
headers: { "Content-Type": "application/json" },
});
if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to fetch current session`);
const data = await res.json();
if (data.length > 0) {
currentSession = data[0].session_id; // Assume session_id is consistent in backend
await loadSession(currentSession);
}
await loadHistory();
} catch (err) {
console.error("Error initializing:", err);
chatBox.innerHTML = `<div class="msg bot-msg">โš ๏ธ Could not initialize chat: ${err.message}</div>`;
}
}
init();
});