|
|
|
|
|
var messages = document.querySelector('.message-list'); |
|
|
var btn = document.querySelector('.btn'); |
|
|
var input = document.querySelector('input'); |
|
|
|
|
|
|
|
|
btn.addEventListener('click', sendMessage); |
|
|
input.addEventListener('keyup', function(e) { |
|
|
if (e.key === 'Enter') sendMessage(); |
|
|
}); |
|
|
|
|
|
|
|
|
function loadHistory() { |
|
|
fetch('/history') |
|
|
.then(response => response.json()) |
|
|
.then(data => { |
|
|
for (let i = 0; i < data.length; i++) { |
|
|
if (data[i].role === 'User') { |
|
|
addMessage({ FROM: 'User', MESSAGE: data[i].content }, 'primary'); |
|
|
} else if (data[i].role === 'assistant') { |
|
|
addMessage({ FROM: 'Oshi no Ko', MESSAGE: data[i].content }, 'secondary'); |
|
|
} |
|
|
} |
|
|
}) |
|
|
.catch(error => console.error('Error:', error)); |
|
|
} |
|
|
|
|
|
loadHistory(); |
|
|
|
|
|
|
|
|
function sendMessage() { |
|
|
var msg = input.value.trim(); |
|
|
if (!msg) return; |
|
|
|
|
|
|
|
|
addMessage({ FROM: 'User', MESSAGE: msg }, 'primary'); |
|
|
|
|
|
|
|
|
input.value = ''; |
|
|
|
|
|
|
|
|
fetch('/chat', { |
|
|
method: 'POST', |
|
|
headers: { 'Content-Type': 'application/json' }, |
|
|
body: JSON.stringify({ message: msg }) |
|
|
}) |
|
|
.then(response => response.json()) |
|
|
.then(data => { |
|
|
|
|
|
addMessage({ FROM: 'Oshi no Ko', MESSAGE: data.MESSAGE }, 'secondary'); |
|
|
}) |
|
|
.catch(error => console.error('Error:', error)); |
|
|
} |
|
|
|
|
|
|
|
|
function addMessage(msg, typeMessage = 'primary') { |
|
|
writeLine(`<span>${msg.FROM}</span><br><br> ${msg.MESSAGE}`, typeMessage); |
|
|
} |
|
|
|
|
|
|
|
|
function writeLine(text, typeMessage) { |
|
|
var message = document.createElement('li'); |
|
|
message.classList.add('message-item', 'item-' + typeMessage); |
|
|
message.innerHTML = text; |
|
|
messages.appendChild(message); |
|
|
messages.scrollTop = messages.scrollHeight; |
|
|
} |
|
|
|