|
const sendBtn = document.getElementById('send-btn'); |
|
const userInput = document.getElementById('user-input'); |
|
const apiKeyInput = document.getElementById('api-key-input'); |
|
const chatBox = document.getElementById('chat-box'); |
|
|
|
|
|
function showTypingIndicator() { |
|
const typingIndicatorDiv = document.createElement('div'); |
|
typingIndicatorDiv.className = 'bot-message typing-indicator'; |
|
typingIndicatorDiv.innerHTML = '<span>Typing...</span>'; |
|
chatBox.appendChild(typingIndicatorDiv); |
|
scrollToBottom(); |
|
} |
|
|
|
function removeTypingIndicator() { |
|
const typingIndicatorDiv = chatBox.querySelector('.typing-indicator'); |
|
if (typingIndicatorDiv) { |
|
chatBox.removeChild(typingIndicatorDiv); |
|
} |
|
} |
|
|
|
const questionButtons = document.querySelectorAll('.question_btn'); |
|
questionButtons.forEach(btn => { |
|
console.log(btn) |
|
btn.addEventListener('click', function() { |
|
console.log("questionButtons clicked: ", this) |
|
const buttonTextContent = this.innerHTML; |
|
userInput.value = buttonTextContent; |
|
sendBtn.click(); |
|
}); |
|
}); |
|
|
|
sendBtn.addEventListener('click', () => { |
|
console.log("send clicked") |
|
const message = userInput.value.trim(); |
|
const apiKey = apiKeyInput.value.trim(); |
|
console.log("message: ", message) |
|
console.log("apiKey: ", apiKey) |
|
|
|
if (message && apiKey) { |
|
|
|
const userMessageDiv = document.createElement('div'); |
|
userMessageDiv.className = 'user-message'; |
|
userMessageDiv.innerText = message; |
|
chatBox.appendChild(userMessageDiv); |
|
scrollToBottom(); |
|
|
|
showTypingIndicator(); |
|
|
|
|
|
console.log("type: ", typeof message, typeof apiKey) |
|
fetch('/chat/', { |
|
method: 'POST', |
|
headers: { |
|
'Content-Type': 'application/json' |
|
}, |
|
body: JSON.stringify({user_input: message, api_key: apiKey}) |
|
}) |
|
.then(response => { |
|
console.log("response: ", response) |
|
if (!response.ok) { |
|
print(response) |
|
throw new Error('Network response was not ok'); |
|
} |
|
return response.json(); |
|
}) |
|
.then(data => { |
|
console.log("data: ", data) |
|
console.log("reply: ", data.response) |
|
|
|
removeTypingIndicator(); |
|
const botMessageHTML = marked.parse(data.response); |
|
|
|
const botMessageDiv = document.createElement('div'); |
|
botMessageDiv.className = 'bot-message'; |
|
botMessageDiv.innerHTML = botMessageHTML; |
|
chatBox.appendChild(botMessageDiv); |
|
console.log("botMessageDiv", botMessageDiv) |
|
scrollToBottom(); |
|
}) |
|
.catch(error => { |
|
removeTypingIndicator(); |
|
console.log('There was a problem with the fetch operation:', error.message); |
|
}); |
|
|
|
userInput.value = ''; |
|
} |
|
}); |
|
|
|
function scrollToBottom() { |
|
chatBox.scrollTop = chatBox.scrollHeight; |
|
} |
|
|