|
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(); |
|
|
|
let response = ""; |
|
|
|
|
|
function addLoader() { |
|
const loaderEle = document.createElement('div'); |
|
loaderEle.classList.add('dot-loader'); |
|
loaderEle.innerHTML = ` |
|
<div></div> |
|
<div></div> |
|
<div></div> |
|
`; |
|
chatBox.appendChild(loaderEle); |
|
} |
|
|
|
|
|
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; |
|
|
|
|
|
setTimeout(addLoader, 500); |
|
} |
|
} |
|
|
|
|
|
sendButton.addEventListener('click', () => { |
|
const message = chatInput.value.trim(); |
|
if (message) { |
|
appendMessage(message, 'user'); |
|
socket.emit('message', { question: message, language:"en", session_id: 'abc123' }); |
|
chatInput.value = ''; |
|
response = ""; |
|
} else { |
|
console.error("Message cannot be empty."); |
|
} |
|
}); |
|
|
|
|
|
chatInput.addEventListener('keypress', (e) => { |
|
if (e.key === 'Enter') { |
|
sendButton.click(); |
|
} |
|
}); |
|
|
|
|
|
socket.on('response', (data) => { |
|
if (data && typeof data === 'string') { |
|
appendMessage(data, 'bot'); |
|
} else { |
|
console.error("Invalid response format received from the server."); |
|
} |
|
}); |
|
|
|
|
|
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'); |
|
}); |
|
|
|
|
|
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'); |
|
}); |
|
|