-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat-input.tsx
More file actions
276 lines (251 loc) · 8.52 KB
/
chat-input.tsx
File metadata and controls
276 lines (251 loc) · 8.52 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
"use client"
import { InputDropZone } from "./input-drop-zone"
import {
PromptInput,
PromptInputAction,
PromptInputActions,
PromptInputTextarea,
} from "@/components/ui/prompt-input"
import { Button } from "@/components/ui/button"
import { StopBulkRoundedIcon } from "@/lib/icons"
import { getModelInfo } from "@/lib/models"
import { HugeiconsIcon } from "@hugeicons/react"
import { ArrowUp02Icon } from "@hugeicons-pro/core-stroke-rounded"
import { resolveComposerPrimaryActionState } from "./primary-action-state"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { PromptSystem } from "../suggestions/prompt-system"
import { ButtonPlusMenu } from "./button-plus-menu"
import { FileList } from "./file-list"
type ChatInputProps = {
defaultValue?: string
onValueChange: (value: string) => void
onSend: () => void
isSubmitting?: boolean
hasMessages?: boolean
files: File[]
onFileUpload: (files: File[]) => void
onFileRemove: (file: File) => void
onSuggestion: (suggestion: string) => void
hasSuggestions?: boolean
selectedModel: string
isUserAuthenticated: boolean
stop: () => void
status?: "submitted" | "streaming" | "ready" | "error"
setEnableSearch: (enabled: boolean) => void
enableSearch: boolean
quotedText?: { text: string; messageId: string } | null
registerInputListener?: (
listener: ((value: string) => void) | null
) => void
/** Callback to register a focus function so parents can imperatively focus the textarea */
registerFocus?: (fn: (() => void) | null) => void
}
export function ChatInput({
defaultValue = "",
onValueChange,
onSend,
isSubmitting,
files,
onFileUpload,
onFileRemove,
onSuggestion,
hasSuggestions,
selectedModel,
isUserAuthenticated,
stop,
status,
setEnableSearch,
enableSearch,
quotedText,
registerInputListener,
registerFocus,
}: ChatInputProps) {
const selectModelConfig = getModelInfo(selectedModel)
// Web search is disabled only when the model explicitly can't accept tool calls
// (tools: false) or has opted out of search (webSearch: false).
// All other models get search via Layer 1 (provider-native) or Layer 2 (Exa fallback).
const isSearchDisabled =
selectModelConfig?.tools === false || selectModelConfig?.webSearch === false
const isFileUploadAvailable = Boolean(selectModelConfig?.vision)
const isOnlyWhitespace = (text: string) => !/[^\s]/.test(text)
const textareaRef = useRef<HTMLTextAreaElement>(null)
// Expose a focus callback so parents / hooks can imperatively focus the textarea
useEffect(() => {
registerFocus?.(() => textareaRef.current?.focus())
return () => registerFocus?.(null)
}, [registerFocus])
// Local state — ChatInput owns the displayed text to avoid re-renders in parent tree
const [localValue, setLocalValue] = useState(defaultValue)
// Sync when parent changes defaultValue (e.g. clearing input after submit in project view).
// During normal typing the parent's defaultValue tracks localValue, so the set is a no-op.
useEffect(() => {
setLocalValue(defaultValue)
}, [defaultValue])
// Register local setState so use-chat-core can imperatively update display
// (e.g. clear on submit, hydrate from ?prompt= search param)
useEffect(() => {
registerInputListener?.(setLocalValue)
return () => registerInputListener?.(null)
}, [registerInputListener])
// Wrapper: updates local display state + notifies parent (ref + debounced draft)
const handleValueChange = useCallback(
(newValue: string) => {
setLocalValue(newValue)
onValueChange(newValue)
},
[onValueChange]
)
const primaryAction = useMemo(
() =>
resolveComposerPrimaryActionState({
isStreaming: status === "streaming",
isAbortable: status === "streaming",
canSend: !isSubmitting && !isOnlyWhitespace(localValue),
}),
[isSubmitting, localValue, status]
)
const handlePrimaryActionClick = useCallback(() => {
if (primaryAction.disabled) {
return
}
if (primaryAction.intent === "stop") {
stop()
return
}
onSend()
}, [onSend, primaryAction.disabled, primaryAction.intent, stop])
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key !== "Enter" || e.shiftKey) {
return
}
if (primaryAction.mode === "stop") {
return
}
if (!primaryAction.disabled) {
e.preventDefault()
onSend()
}
},
[onSend, primaryAction.disabled, primaryAction.mode]
)
const handlePaste = useCallback(
async (e: React.ClipboardEvent) => {
const items = e.clipboardData?.items
if (!items) return
const hasImageContent = Array.from(items).some((item) =>
item.type.startsWith("image/")
)
if (!isUserAuthenticated && hasImageContent) {
e.preventDefault()
return
}
if (isUserAuthenticated && hasImageContent) {
const imageFiles: File[] = []
for (const item of Array.from(items)) {
if (item.type.startsWith("image/")) {
const file = item.getAsFile()
if (file) {
const newFile = new File(
[file],
`pasted-image-${Date.now()}.${file.type.split("/")[1]}`,
{ type: file.type }
)
imageFiles.push(newFile)
}
}
}
if (imageFiles.length > 0) {
onFileUpload(imageFiles)
}
}
// Text pasting will work by default for everyone
},
[isUserAuthenticated, onFileUpload]
)
const valueRef = useRef(localValue)
useEffect(() => {
valueRef.current = localValue
}, [localValue])
useEffect(() => {
if (quotedText) {
const current = valueRef.current
const quoted = quotedText.text
.split("\n")
.map((line) => `> ${line}`)
.join("\n")
handleValueChange(
current ? `${current}\n\n${quoted}\n\n` : `${quoted}\n\n`
)
requestAnimationFrame(() => {
textareaRef.current?.focus()
})
}
}, [quotedText, handleValueChange])
return (
<div className="relative flex w-full flex-col gap-4">
{hasSuggestions && (
<PromptSystem
onValueChange={handleValueChange}
onSuggestion={onSuggestion}
value={localValue}
/>
)}
<InputDropZone
onFileUpload={onFileUpload}
disabled={!isUserAuthenticated || !isFileUploadAvailable}
>
<div
className="relative order-2 px-2 pb-3 sm:pb-4 md:order-1"
onClick={() => textareaRef.current?.focus()}
>
<PromptInput
className="relative z-10 p-0 pt-1"
maxHeight={200}
value={localValue}
onValueChange={handleValueChange}
>
<FileList files={files} onFileRemove={onFileRemove} />
<PromptInputTextarea
ref={textareaRef}
placeholder="Ask anything..."
onKeyDown={handleKeyDown}
onPaste={handlePaste}
className="min-h-[44px] pt-3 pl-4 text-base leading-[1.3] sm:text-base md:text-base"
/>
<PromptInputActions className="mt-3 w-full justify-between p-2">
<div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
<ButtonPlusMenu
onFileUpload={onFileUpload}
isUserAuthenticated={isUserAuthenticated}
isFileUploadAvailable={isFileUploadAvailable}
enableSearch={enableSearch}
onToggleSearch={setEnableSearch}
isSearchDisabled={isSearchDisabled}
/>
</div>
<PromptInputAction
tooltip={primaryAction.tooltip}
>
<Button
size="sm"
className="size-9 rounded-full transition-all duration-300 ease-out"
disabled={primaryAction.disabled}
type="button"
onClick={handlePrimaryActionClick}
aria-label={primaryAction.ariaLabel}
>
{primaryAction.mode === "stop" ? (
<HugeiconsIcon icon={StopBulkRoundedIcon} size={16} />
) : (
<HugeiconsIcon icon={ArrowUp02Icon} size={20} strokeWidth={2.5} className="size-5" />
)}
</Button>
</PromptInputAction>
</PromptInputActions>
</PromptInput>
</div>
</InputDropZone>
</div>
)
}