StreamAI / scripts /chat.js
privateuserh's picture
Update scripts/chat.js
905ca9b verified
raw
history blame
2.61 kB
// scripts/chat.js
export function initChat() {
const sendBtn = document.getElementById('send-btn');
const userInput = document.getElementById('user-input');
if (sendBtn && userInput) {
sendBtn.addEventListener('click', sendMessage);
userInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') sendMessage();
});
}
}
// In scripts/chat.js
async function sendMessage() {
const userInput = document.getElementById('user-input');
const chatMessages = document.getElementById('chat-messages');
const userMessageText = userInput.value.trim();
if (userMessageText === '') return;
// Create and add the user's message bubble
const userBubble = document.createElement('div');
userBubble.className = 'chat-bubble user-bubble p-4 fade-in';
userBubble.innerHTML = `<p>${userMessageText}</p>`;
chatMessages.appendChild(userBubble);
userInput.value = '';
chatMessages.scrollTop = chatMessages.scrollHeight;
// Create the AI's response bubble
const aiBubble = document.createElement('div');
aiBubble.className = 'chat-bubble ai-bubble p-4 fade-in';
aiBubble.innerHTML = '<div class="typing-indicator"><span></span><span></span><span></span></div>';
chatMessages.appendChild(aiBubble);
chatMessages.scrollTop = chatMessages.scrollHeight;
// --- THIS IS THE CRUCIAL UPDATE ---
// This now points to your new worker's chat endpoint.
const workerUrl = 'https://streamai-backend-v2.smplushypermedia.workers.dev/api/chat';
try {
const response = await fetch(workerUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt: userMessageText }),
});
if (!response.ok) throw new Error(`Network response was not ok. Status: ${response.status}`);
// Handle the streaming response from Gemini
const reader = response.body.getReader();
const decoder = new TextDecoder();
aiBubble.innerHTML = ''; // Clear the typing indicator
const aiParagraph = document.createElement('p');
aiBubble.appendChild(aiParagraph);
while (true) {
const { done, value } = await reader.read();
if (done) break;
aiParagraph.textContent += decoder.decode(value, { stream: true });
chatMessages.scrollTop = chatMessages.scrollHeight;
}
} catch (error) {
aiBubble.innerHTML = `<p class="text-red-400">Error: Could not connect to the AI assistant. ${error.message}</p>`;
}
}