const chatContent = document.getElementById('chat-content'); const questionInput = document.getElementById('question'); const sendButton = document.getElementById('send-btn'); const fileInput = document.getElementById('file-input'); // Initialize Markdown-it with syntax highlighting const md = markdownit({ highlight: function (str, lang) { if (lang && hljs.getLanguage(lang)) { try { return '
' + hljs.highlight(str, { language: lang }).value + '';
} catch (__) {}
}
return '' + md.utils.escapeHtml(str) + '';
},
});
// Function to add messages to the chat
const addMessage = (text, type, isMarkdown = false) => {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}`;
const messageContent = document.createElement('p');
messageContent.innerHTML = isMarkdown ? md.render(text) : text;
messageDiv.appendChild(messageContent);
chatContent.appendChild(messageDiv);
chatContent.scrollTop = chatContent.scrollHeight;
};
// Handle Send Button Click for Chat Messages
sendButton.addEventListener('click', async () => {
const question = questionInput.value.trim();
if (!question) return;
// Add user's message to the chat
addMessage(question, 'user');
// Clear the input field
questionInput.value = '';
// Send the question to the backend
try {
const response = await fetch('http://127.0.0.1:8080/qa', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question }),
});
const data = await response.json();
// Add bot's response to the chat
if (data.answer) {
addMessage(data.answer, 'bot', true); // Render bot's response as Markdown
} else if (data.error) {
addMessage(`Error: ${data.error}`, 'bot');
}
} catch (error) {
addMessage(`Error: ${error.message}`, 'bot');
}
});
// Handle File Upload
fileInput.addEventListener('change', async (event) => {
const files = event.target.files;
if (files.length > 0) {
const formData = new FormData();
Array.from(files).forEach((file) => {
formData.append('file', file);
});
// Send the file to the backend
try {
const response = await fetch('http://127.0.0.1:8080/upload', {
method: 'POST',
body: formData,
});
const data = await response.json();
// Add a confirmation message to the chat
if (data.message) {
addMessage(data.message, 'bot');
} else if (data.error) {
addMessage(`Error: ${data.error}`, 'bot');
}
} catch (error) {
addMessage(`Error: ${error.message}`, 'bot');
}
}
});