File size: 2,823 Bytes
4416e3b | 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 | document.addEventListener('DOMContentLoaded', () => {
const chatHistory = document.getElementById('chat-history');
const queryInput = document.getElementById('query-input');
const sendBtn = document.getElementById('send-btn');
const appendMessage = (content, isUser, sources = []) => {
const msgDiv = document.createElement('div');
msgDiv.className = `message ${isUser ? 'user-message' : 'bot-message'}`;
// Parse markdown if it's from the bot
const parsedContent = isUser ? content : marked.parse(content);
let html = `<div class="content">${parsedContent}</div>`;
if (!isUser && sources.length > 0) {
html += '<div class="sources"><strong>Sources:</strong><br>';
sources.forEach(src => {
html += `<span class="source-tag">${src}</span>`;
});
html += '</div>';
}
msgDiv.innerHTML = html;
chatHistory.appendChild(msgDiv);
chatHistory.scrollTop = chatHistory.scrollHeight;
};
const handleQuery = async (forcedQuery = null) => {
const query = (forcedQuery || queryInput.value).trim();
if (!query) return;
appendMessage(query, true);
queryInput.value = '';
// Add loading indicator
const loadingDiv = document.createElement('div');
loadingDiv.className = 'message bot-message loading-indicator';
loadingDiv.innerHTML = '<span class="loading-dots">Thinking</span>';
chatHistory.appendChild(loadingDiv);
chatHistory.scrollTop = chatHistory.scrollHeight;
try {
const response = await fetch('/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query })
});
const data = await response.json();
// Remove loading
chatHistory.removeChild(loadingDiv);
if (data.answer) {
appendMessage(data.answer, false, data.sources);
} else {
appendMessage("Sorry, I encountered an error: " + (data.error || "Unknown error"), false);
}
} catch (error) {
chatHistory.removeChild(loadingDiv);
appendMessage("Connection error. Is the server running?", false);
}
};
// Suggestion chips
document.querySelectorAll('.chip').forEach(chip => {
chip.addEventListener('click', () => {
handleQuery(chip.getAttribute('data-query'));
});
});
sendBtn.addEventListener('click', () => handleQuery());
queryInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') handleQuery();
});
});
|