Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

main.js

169 lines4.8 KB

1import { ChatClient, fetchServerSentEvents } from '@tanstack/ai-client'
2​
3// Initialize ChatClient
4const client = new ChatClient({
5 connection: fetchServerSentEvents('http://localhost:8000/chat'),
6 onMessagesChange: (messages) => {
7 renderMessages(messages)
8 },
9 onLoadingChange: (isLoading) => {
10 updateLoadingState(isLoading)
11 },
12 onErrorChange: (error) => {
13 showError(error)
14 },
15})
16​
17// DOM elements
18const messagesContainer = document.getElementById('messages')
19const chatForm = document.getElementById('chat-form')
20const messageInput = document.getElementById('message-input')
21const sendButton = document.getElementById('send-button')
22const errorDiv = document.getElementById('error')
23​
24// Auto-resize textarea
25messageInput.addEventListener('input', () => {
26 messageInput.style.height = 'auto'
27 messageInput.style.height = messageInput.scrollHeight + 'px'
28})
29​
30// Handle form submission
31chatForm.addEventListener('submit', async (e) => {
32 e.preventDefault()
33​
34 const message = messageInput.value.trim()
35 if (!message || client.getIsLoading()) return
36​
37 // Clear input
38 messageInput.value = ''
39 messageInput.style.height = 'auto'
40​
41 // Focus back on input
42 messageInput.focus()
43​
44 try {
45 await client.sendMessage(message)
46 } catch (error) {
47 console.error('Error sending message:', error)
48 showError(error)
49 }
50})
51​
52// Allow Enter to send (Shift+Enter for new line)
53messageInput.addEventListener('keydown', (e) => {
54 if (e.key === 'Enter' && !e.shiftKey) {
55 e.preventDefault()
56 chatForm.dispatchEvent(new Event('submit'))
57 }
58})
59​
60// Render messages
61function renderMessages(messages) {
62 if (!messagesContainer) return
63​
64 messagesContainer.innerHTML = ''
65​
66 messages.forEach((message) => {
67 const messageDiv = document.createElement('div')
68 messageDiv.className = `message ${message.role}`
69​
70 if (message.role === 'user') {
71 // Extract text content from parts
72 const textParts = message.parts.filter((p) => p.type === 'text')
73 const content = textParts.map((p) => p.content).join('')
74​
75 messageDiv.innerHTML = `
76 <div class="message-content">${escapeHtml(content)}</div>
77 `
78 } else if (message.role === 'assistant') {
79 // Render parts in their original order (maintains chronological flow)
80 const partsHtml = message.parts
81 .map((part) => {
82 if (part.type === 'thinking') {
83 return `<div class="thinking">${escapeHtml(part.content)}</div>`
84 } else if (part.type === 'text') {
85 return `<div class="message-content">${escapeHtml(part.content)}</div>`
86 } else if (part.type === 'tool-call') {
87 return `
88 <div class="tool-call">
89 <div>
90 <span class="tool-name">${escapeHtml(part.name)}</span>
91 <span class="tool-state">${escapeHtml(part.state)}</span>
92 </div>
93 <pre class="tool-args">${escapeHtml(part.arguments)}</pre>
94 ${part.output ? `<pre class="tool-output">${escapeHtml(JSON.stringify(part.output, null, 2))}</pre>` : ''}
95 </div>
96 `
97 } else if (part.type === 'tool-result') {
98 return `
99 <div class="tool-result">
100 <div class="tool-result-label">Tool Result:</div>
101 <pre class="tool-result-content">${escapeHtml(part.content)}</pre>
102 </div>
103 `
104 }
105 return ''
106 })
107 .join('')
108​
109 messageDiv.innerHTML = partsHtml
110 }
111​
112 messagesContainer.appendChild(messageDiv)
113 })
114​
115 // Scroll to bottom
116 messagesContainer.scrollTop = messagesContainer.scrollHeight
118​
119// Update loading state
120function updateLoadingState(isLoading) {
121 if (sendButton) {
122 sendButton.disabled = isLoading
123 sendButton.textContent = isLoading ? 'Sending...' : 'Send'
124 }
125​
126 if (messageInput) {
127 messageInput.disabled = isLoading
128 }
129​
130 // Show typing indicator
131 if (isLoading && messagesContainer) {
132 const typingIndicator = document.createElement('div')
133 typingIndicator.className = 'message assistant typing'
134 typingIndicator.id = 'typing-indicator'
135 typingIndicator.innerHTML = '<div class="message-content">...</div>'
136 messagesContainer.appendChild(typingIndicator)
137 messagesContainer.scrollTop = messagesContainer.scrollHeight
138 } else {
139 const indicator = document.getElementById('typing-indicator')
140 if (indicator) {
141 indicator.remove()
142 }
143 }
145​
146// Show error
147function showError(error) {
148 if (!errorDiv) return
149​
150 if (error) {
151 errorDiv.textContent = error.message || 'An error occurred'
152 errorDiv.style.display = 'block'
153 } else {
154 errorDiv.style.display = 'none'
155 }
157​
158// Escape HTML to prevent XSS
159function escapeHtml(text) {
160 const div = document.createElement('div')
161 div.textContent = text
162 return div.innerHTML
164​
165// Initialize - render any existing messages
166renderMessages(client.getMessages())
167​
168// Focus input on load
169messageInput?.focus()