-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathchat-panel.tsx
More file actions
317 lines (293 loc) · 9.96 KB
/
Copy pathchat-panel.tsx
File metadata and controls
317 lines (293 loc) · 9.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
'use client'
import { useEffect, useState, useRef, ChangeEvent, forwardRef, useImperativeHandle, useCallback } from 'react'
import type { AI, UIState } from '@/app/actions'
import { useUIState, useActions, readStreamableValue } from 'ai/rsc'
import { cn } from '@/lib/utils'
import { UserMessage } from './user-message'
import { Button } from './ui/button'
import { ArrowRight, Plus, Paperclip, X, Sprout } from 'lucide-react'
import Textarea from 'react-textarea-autosize'
import { nanoid } from '@/lib/utils'
import { useSettingsStore } from '@/lib/store/settings'
import { PartialRelated } from '@/lib/schema/related'
import { getSuggestions } from '@/lib/actions/suggest'
import { useMapData } from './map/map-data-context'
import SuggestionsDropdown from './suggestions-dropdown'
interface ChatPanelProps {
messages: UIState
input: string
setInput: (value: string) => void
onSuggestionsChange?: (suggestions: PartialRelated | null) => void
searchParams?: { [key: string]: string | string[] | undefined }
}
export interface ChatPanelRef {
handleAttachmentClick: () => void
submitForm: () => void
}
export const ChatPanel = forwardRef<ChatPanelRef, ChatPanelProps>(({ messages, input, setInput, onSuggestionsChange, searchParams }, ref) => {
const [, setMessages] = useUIState<typeof AI>()
const { submit, clearChat } = useActions()
const { mapProvider } = useSettingsStore()
const [isMobile, setIsMobile] = useState(false)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [suggestions, setSuggestionsState] = useState<PartialRelated | null>(null)
const setSuggestions = useCallback((s: PartialRelated | null) => {
setSuggestionsState(s)
onSuggestionsChange?.(s)
}, [onSuggestionsChange, setSuggestionsState])
const { mapData } = useMapData()
const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null)
const inputRef = useRef<HTMLTextAreaElement>(null)
const formRef = useRef<HTMLFormElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
useImperativeHandle(ref, () => ({
handleAttachmentClick() {
fileInputRef.current?.click()
},
submitForm() {
formRef.current?.requestSubmit()
}
}));
// Detect mobile layout
useEffect(() => {
const checkMobile = () => {
setIsMobile(window.innerWidth <= 1024)
}
checkMobile()
window.addEventListener('resize', checkMobile)
return () => window.removeEventListener('resize', checkMobile)
}, [])
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
if (file.size > 10 * 1024 * 1024) {
alert('File size must be less than 10MB')
return
}
setSelectedFile(file)
}
}
const handleAttachmentClick = () => {
fileInputRef.current?.click()
}
const clearAttachment = () => {
setSelectedFile(null)
if (fileInputRef.current) {
fileInputRef.current.value = ''
}
}
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
if (!input.trim() && !selectedFile) {
return
}
const content: ({ type: 'text'; text: string } | { type: 'image'; image: string })[] = []
if (input) {
content.push({ type: 'text', text: input })
}
if (selectedFile && selectedFile.type.startsWith('image/')) {
content.push({
type: 'image',
image: URL.createObjectURL(selectedFile)
})
}
setMessages(currentMessages => [
...currentMessages,
{
id: nanoid(),
component: <UserMessage content={content} />
}
])
const formData = new FormData(e.currentTarget)
if (selectedFile) {
formData.append('file', selectedFile)
}
// Include drawn features in the form data
formData.append('drawnFeatures', JSON.stringify(mapData.drawnFeatures || []))
// Include searchParams in the form data if they exist
if (searchParams) {
Object.entries(searchParams).forEach(([key, value]) => {
if (value !== undefined) {
formData.append(key, Array.isArray(value) ? value.join(',') : value);
}
});
}
setInput('')
clearAttachment()
const responseMessage = await submit(formData)
setMessages(currentMessages => [...currentMessages, responseMessage as any])
}
const handleClear = async () => {
setMessages([])
clearAttachment()
await clearChat()
}
const debouncedGetSuggestions = useCallback(
(value: string) => {
if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current)
}
const wordCount = value.trim().split(/\s+/).filter(Boolean).length
if (wordCount < 2) {
setSuggestions(null)
return
}
debounceTimeoutRef.current = setTimeout(async () => {
const suggestionsStream = await getSuggestions(value, mapData)
for await (const partialSuggestions of readStreamableValue(
suggestionsStream
)) {
if (partialSuggestions) {
setSuggestions(partialSuggestions as PartialRelated)
}
}
}, 500) // 500ms debounce delay
},
[mapData, setSuggestions]
)
useEffect(() => {
inputRef.current?.focus()
}, [])
// New chat button (appears when there are messages)
if (messages.length > 0 && !isMobile) {
return (
<div
className={cn(
'fixed bottom-4 left-4 flex justify-start items-center pointer-events-none z-50'
)}
>
<Button
type="button"
variant={'ghost'}
size={'icon'}
className="rounded-full transition-all hover:scale-110 pointer-events-auto text-primary"
onClick={() => handleClear()}
data-testid="new-chat-button"
title="New Chat"
>
<Sprout size={28} className="fill-primary/20" />
</Button>
</div>
)
}
return (
<div
className={cn(
'flex flex-col items-start',
isMobile
? 'w-full h-full'
: 'sticky bottom-0 bg-background z-10 w-full border-t border-border px-2 py-3 md:px-4'
)}
>
<form
ref={formRef}
onSubmit={handleSubmit}
className={cn(
'max-w-full w-full',
isMobile ? 'px-2 pb-2 pt-1 h-full flex flex-col justify-center' : ''
)}
>
<div
className={cn(
'relative flex items-start w-full',
isMobile && 'mobile-chat-input' // Apply mobile chat input styling
)}
>
<input type="hidden" name="mapProvider" value={mapProvider} />
<input
type="file"
ref={fileInputRef}
onChange={handleFileChange}
className="hidden"
accept="text/plain,image/png,image/jpeg,image/webp"
/>
{!isMobile && (
<Button
type="button"
variant={'ghost'}
size={'icon'}
className={cn(
'absolute top-1/2 transform -translate-y-1/2 left-3'
)}
onClick={handleAttachmentClick}
data-testid="desktop-attachment-button"
>
<Paperclip size={isMobile ? 18 : 20} />
</Button>
)}
<Textarea
ref={inputRef}
name="input"
rows={1}
maxRows={isMobile ? 3 : 5}
tabIndex={0}
placeholder="Explore"
spellCheck={false}
value={input}
data-testid="chat-input"
className={cn(
'resize-none w-full min-h-12 rounded-fill border border-input pl-14 pr-12 pt-3 pb-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
isMobile
? 'mobile-chat-input input bg-background'
: 'bg-muted'
)}
onChange={e => {
setInput(e.target.value)
debouncedGetSuggestions(e.target.value)
}}
onKeyDown={e => {
if (
e.key === 'Enter' &&
!e.shiftKey &&
!e.nativeEvent.isComposing
) {
if (input.trim().length === 0 && !selectedFile) {
e.preventDefault()
return
}
e.preventDefault()
formRef.current?.requestSubmit()
}
}}
onHeightChange={height => {
if (!inputRef.current) return
const initialHeight = 70
const initialBorder = 32
const multiple = (height - initialHeight) / 20
const newBorder = initialBorder - 4 * multiple
inputRef.current.style.borderRadius =
Math.max(8, newBorder) + 'px'
}}
/>
<Button
type="submit"
size={'icon'}
variant={'ghost'}
className={cn(
'absolute top-1/2 transform -translate-y-1/2',
isMobile ? 'right-1' : 'right-2'
)}
disabled={input.length === 0 && !selectedFile}
aria-label="Send message"
data-testid="chat-submit"
>
<ArrowRight size={isMobile ? 18 : 20} />
</Button>
</div>
</form>
{selectedFile && (
<div className="w-full px-4 pb-2 mb-2">
<div className="flex items-center justify-between p-2 bg-muted rounded-lg">
<span className="text-sm text-muted-foreground truncate max-w-xs">
{selectedFile.name}
</span>
<Button variant="ghost" size="icon" onClick={clearAttachment} data-testid="clear-attachment-button">
<X size={16} />
</Button>
</div>
</div>
)}
</div>
)
})
ChatPanel.displayName = 'ChatPanel'