File size: 2,582 Bytes
e227a15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
const chatBox = document.getElementById('chat-box');
const chatForm = document.getElementById('chat-form');
const userInput = document.getElementById('user-input');
const loading = document.getElementById('loading');

function escapeHTML(str) {
    return str.replace(/[&<>'"/]/g, function (c) {
        return {'&':'&amp;','<':'&lt;','>':'&gt;','\'':'&#39;','"':'&quot;','/':'&#x2F;'}[c];
    });
}

function addMessage(text, sender, logId=null) {
    const msgDiv = document.createElement('div');
    msgDiv.className = `message ${sender}`;
    const bubble = document.createElement('div');
    bubble.className = `bubble ${sender}`;
    bubble.innerHTML = escapeHTML(text);
    msgDiv.appendChild(bubble);
    if (sender === 'ai' && logId) {
        const feedbackDiv = document.createElement('div');
        feedbackDiv.className = 'feedback';
        const upBtn = document.createElement('button');
        upBtn.innerHTML = 'πŸ‘';
        upBtn.onclick = () => sendFeedback(logId, 'up', upBtn, downBtn);
        const downBtn = document.createElement('button');
        downBtn.innerHTML = 'πŸ‘Ž';
        downBtn.onclick = () => sendFeedback(logId, 'down', upBtn, downBtn);
        feedbackDiv.appendChild(upBtn);
        feedbackDiv.appendChild(downBtn);
        msgDiv.appendChild(feedbackDiv);
    }
    chatBox.appendChild(msgDiv);
    chatBox.scrollTop = chatBox.scrollHeight;
}

function sendFeedback(logId, rating, upBtn, downBtn) {
    fetch('/feedback', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({log_id: logId, rating: rating})
    })
    .then(res => res.json())
    .then(() => {
        upBtn.disabled = true;
        downBtn.disabled = true;
    });
}

chatForm.onsubmit = function(e) {
    e.preventDefault();
    const text = userInput.value.trim();
    if (!text) return;
    addMessage(text, 'user');
    userInput.value = '';
    loading.style.display = 'block';
    fetch('/chat', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({query: text})
    })
    .then(res => res.json())
    .then(data => {
        loading.style.display = 'none';
        if (data.response) {
            addMessage(data.response, 'ai', data.log_id);
        } else {
            addMessage('Sorry, something went wrong.', 'ai');
        }
    })
    .catch(() => {
        loading.style.display = 'none';
        addMessage('Sorry, something went wrong.', 'ai');
    });
};