|
const socket = io.connect(document.baseURI); |
|
|
|
const chatBox = document.getElementById('chat-box'); |
|
const chatInput = document.getElementById('chat-input'); |
|
const sendButton = document.getElementById('send-button'); |
|
var converter = new showdown.Converter(); |
|
var response=""; |
|
|
|
|
|
function addLoader(){ |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const loader_ele = document.createElement('div'); |
|
loader_ele.classList.add('dot-loader'); |
|
loader_ele.innerHTML = ` |
|
<div></div> |
|
<div></div> |
|
<div></div> |
|
`; |
|
chatBox.appendChild(loader_ele); |
|
} |
|
|
|
function appendMessage(message, sender) { |
|
if(sender == "bot"){ |
|
response += message; |
|
message = converter.makeHtml(response); |
|
|
|
let loader_ele = chatBox.lastElementChild; |
|
|
|
if(!loader_ele.classList.contains("hidden")){ |
|
chatBox.removeChild(loader_ele); |
|
const messageElement = document.createElement('div'); |
|
messageElement.classList.add('chat-message', sender); |
|
messageElement.innerHTML = `<span>${message}</span>`; |
|
chatBox.append(messageElement); |
|
chatBox.scrollTop = chatBox.scrollHeight; |
|
}else{ |
|
last_message_ele = chatBox.lastElementChild.lastChild; |
|
last_message_ele.innerHTML = message; |
|
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); |
|
} |
|
chatBox.scrollTop = chatBox.scrollHeight; |
|
} |
|
|
|
sendButton.addEventListener('click', () => { |
|
const message = chatInput.value.trim(); |
|
if (message) { |
|
appendMessage(message, 'user'); |
|
socket.emit('message', { question: message, session_id: 'abc123' }); |
|
|
|
|
|
|
|
chatInput.value = ''; |
|
response = ""; |
|
} |
|
}); |
|
|
|
chatInput.addEventListener('keypress', (e) => { |
|
if (e.key === 'Enter') { |
|
sendButton.click(); |
|
} |
|
}); |
|
|
|
socket.on('response', (response) => { |
|
appendMessage(response, 'bot'); |
|
}); |
|
|