File size: 1,681 Bytes
a1955ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const socket = io.connect('http://' + document.baseURI + ':' + location.port);

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 appendMessage(message, sender) {
    last_message_ele = chatBox.children[chatBox.children.length - 2];
    response += message;
    message = converter.makeHtml(response);
    if(last_message_ele && last_message_ele.classList.contains('bot')){
        last_message_ele.lastChild.innerHTML  = message;
    }else{
        if(sender == 'bot'){
            document.getElementById("loader").classList.add('hidden');
        }
        const messageElement = document.createElement('div');
        messageElement.classList.add('chat-message', sender);
        messageElement.innerHTML = `<span>${message}</span>`;
        if(sender == 'bot'){
            chatBox.append(messageElement);
        }else{
            chatBox.prepend(messageElement);
        }
        chatBox.scrollTop = chatBox.scrollHeight;
    }
}

sendButton.addEventListener('click', () => {
    const message = chatInput.value.trim();
    if (message) {
        appendMessage(message, 'user');
        document.getElementById("loader").classList.remove('hidden');
        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');
});