File size: 2,170 Bytes
2376116
 
 
 
 
 
 
 
 
 
 
41c8295
2376116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
$(document).ready(function() {
    // Initialize variables
    var $messages = $('.chat-messages');
    var $input = $('.chat-input input');
    var $submit = $('.chat_submit');
    var session_id = '';
    $messages.children().each(function() {
        $(this).addClass('chat-message');
    });

    // Initialize SocketIO connection
    var socket = io.connect('https://' + document.domain + ':' + location.port);

    // Function to send message to Flask-SocketIO app
    function sendMessage(message) {
        console.log("message: " + message )
        socket.emit('message', {'question': message});
    }

    // Function to display message
    function displayMessage(message, isUser) {
        var $message = $('<div>').addClass('chat-message round');
        var $messageText = $('<p>').html(message.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1">$1</a>'));

        $message.append($messageText);
        if (isUser) {
            $message.addClass('user');
        } else {
            $message.addClass('bot')
        }
        if ($messages) {
            $messages.append($message);
            if ($messages[0]) {
                $messages.animate({scrollTop: $messages[0].scrollHeight}, 300);
            }
        } else {
            $('.chat-container').append($message);
            $('.chat-container').animate({scrollTop: 0}, 300);
        }
    }


    socket.on('response', function(data) {
        console.log("Received response: " + data.response)
        var response = data.response;
        displayMessage(response, false);
    });


    // Send message on submit
    $submit.click(function(event) {
        event.preventDefault();
        var message = $input.val().trim();
        console.log("Submit clicked: " + message)
        if (message !== '') {
            displayMessage(message, true);
            sendMessage(message);
            $input.val('');
        }
    });

    // Send message on enter key press
    $input.keydown(function(event) {
        if (event.keyCode === 13) {
            event.preventDefault();
            $submit.click();
        }
    });

    // Initial message
    displayMessage('Ask me anything');
});