Spaces:
Sleeping
Sleeping
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 {'&':'&','<':'<','>':'>','\'':''','"':'"','/':'/'}[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'); | |
}); | |
}; |