80 lines
2.7 KiB
JavaScript
80 lines
2.7 KiB
JavaScript
document.addEventListener('DOMContentLoaded', function () {
|
|
const chatWindow = document.getElementById('chat-window');
|
|
const chatInput = document.getElementById('chat-input');
|
|
const sendBtn = document.getElementById('send-btn');
|
|
|
|
function addMessage(message, sender) {
|
|
const messageElement = document.createElement('div');
|
|
const bubble = document.createElement('div');
|
|
const time = document.createElement('div');
|
|
|
|
messageElement.classList.add('chat-message', `${sender}-message`);
|
|
bubble.classList.add('message-bubble');
|
|
time.classList.add('message-time');
|
|
|
|
bubble.innerText = message;
|
|
time.innerText = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
|
|
messageElement.appendChild(bubble);
|
|
messageElement.appendChild(time);
|
|
chatWindow.appendChild(messageElement);
|
|
chatWindow.scrollTop = chatWindow.scrollHeight;
|
|
}
|
|
|
|
async function getNextQuestion(answer = null) {
|
|
const response = await fetch('api/chat.php', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify({ answer: answer })
|
|
});
|
|
return response.json();
|
|
}
|
|
|
|
async function handleUserInput() {
|
|
const userInput = chatInput.value.trim();
|
|
if (userInput === '') return;
|
|
|
|
const rating = parseInt(userInput, 10);
|
|
if (isNaN(rating) || rating < 1 || rating > 5) {
|
|
addMessage('Please enter a number between 1 and 5.', 'bot');
|
|
return;
|
|
}
|
|
|
|
addMessage(userInput, 'user');
|
|
chatInput.value = '';
|
|
chatInput.disabled = true;
|
|
sendBtn.disabled = true;
|
|
|
|
const data = await getNextQuestion(rating);
|
|
|
|
if (data.question) {
|
|
addMessage(data.question, 'bot');
|
|
} else if (data.message) {
|
|
addMessage(data.message, 'bot');
|
|
chatInput.style.display = 'none';
|
|
sendBtn.style.display = 'none';
|
|
}
|
|
chatInput.disabled = false;
|
|
sendBtn.disabled = false;
|
|
chatInput.focus();
|
|
}
|
|
|
|
sendBtn.addEventListener('click', handleUserInput);
|
|
chatInput.addEventListener('keypress', function (e) {
|
|
if (e.key === 'Enter') {
|
|
handleUserInput();
|
|
}
|
|
});
|
|
|
|
async function startConversation() {
|
|
const data = await getNextQuestion();
|
|
if (data.question) {
|
|
addMessage("Welcome to the Burnout Survey. I'll ask you a series of questions. Please rate each one on a scale of 1 (Strongly Disagree) to 5 (Strongly Agree).", 'bot');
|
|
addMessage(data.question, 'bot');
|
|
}
|
|
}
|
|
|
|
startConversation();
|
|
}); |