Ritesh-hf's picture
update app.py
4e322c2
raw
history blame
3.15 kB
const socket = io.connect(document.baseURI);
const chatBox = document.getElementById('chat-box');
const chatInput = document.getElementById('chat-input');
const sendButton = document.getElementById('send-button');
const converter = new showdown.Converter(); // If you're using showdown.js for markdown to HTML conversion
let response = "";
// Function to add a loader element
function addLoader() {
const loaderEle = document.createElement('div');
loaderEle.classList.add('dot-loader');
loaderEle.innerHTML = `
<div></div>
<div></div>
<div></div>
`;
chatBox.appendChild(loaderEle);
}
// Function to append a message to the chat box
function appendMessage(message, sender) {
if (sender === 'bot') {
response += message;
const loaderEle = chatBox.lastElementChild;
if (loaderEle && loaderEle.classList.contains('dot-loader')) {
chatBox.removeChild(loaderEle);
const messageElement = document.createElement('div');
messageElement.classList.add('chat-message', sender);
messageElement.innerHTML = `<span>${response}</span>`;
chatBox.append(messageElement);
chatBox.scrollTop = chatBox.scrollHeight;
} else {
const lastMessageEle = chatBox.lastElementChild;
if (lastMessageEle) {
lastMessageEle.innerHTML = response;
}
chatBox.scrollTop = chatBox.scrollHeight;
}
} else {
const messageElement = document.createElement('div');
messageElement.classList.add('chat-message', sender);
messageElement.innerHTML = `<span>${message}</span>`;
chatBox.append(messageElement);
chatBox.scrollTop = chatBox.scrollHeight;
// Add a loader after a slight delay
setTimeout(addLoader, 500);
}
}
// Event listener for the send button
sendButton.addEventListener('click', () => {
const message = chatInput.value.trim();
if (message) {
appendMessage(message, 'user');
socket.emit('message', { question: message, session_id: 'abc123' });
chatInput.value = '';
response = "";
} else {
console.error("Message cannot be empty.");
}
});
// Event listener for 'Enter' key press in the chat input
chatInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendButton.click();
}
});
// Handle incoming responses from the server
socket.on('response', (data) => {
if (data && typeof data === 'string') {
appendMessage(data, 'bot');
} else {
console.error("Invalid response format received from the server.");
}
});
// Handle connection errors
socket.on('connect_error', (error) => {
console.error("Connection error:", error);
appendMessage("Sorry, there was a problem connecting to the server. Please try again later.", 'bot');
});
// Handle disconnection
socket.on('disconnect', (reason) => {
console.warn("Disconnected from server:", reason);
appendMessage("You have been disconnected from the server. Please refresh the page to reconnect.", 'bot');
});