@leitware/composables 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +387 -0
  3. package/dist/presets/brutalist.css +298 -0
  4. package/dist/presets/default.css +298 -0
  5. package/dist/presets/signal-pop.css +369 -0
  6. package/dist/styles.css +2 -0
  7. package/package.json +216 -0
  8. package/rules/composables.md +244 -0
  9. package/src/_internal/accordion.tsx +93 -0
  10. package/src/_internal/ai-elements/attachments.tsx +385 -0
  11. package/src/_internal/ai-elements/chain-of-thought.tsx +197 -0
  12. package/src/_internal/ai-elements/code-block.tsx +516 -0
  13. package/src/_internal/ai-elements/confirmation.tsx +150 -0
  14. package/src/_internal/ai-elements/conversation.tsx +148 -0
  15. package/src/_internal/ai-elements/inline-citation.tsx +248 -0
  16. package/src/_internal/ai-elements/message.tsx +292 -0
  17. package/src/_internal/ai-elements/plan.tsx +126 -0
  18. package/src/_internal/ai-elements/prompt-input.tsx +1285 -0
  19. package/src/_internal/ai-elements/reasoning.tsx +208 -0
  20. package/src/_internal/ai-elements/shimmer.tsx +72 -0
  21. package/src/_internal/ai-elements/sources.tsx +53 -0
  22. package/src/_internal/ai-elements/suggestion.tsx +48 -0
  23. package/src/_internal/ai-elements/task.tsx +64 -0
  24. package/src/_internal/ai-elements/tool.tsx +156 -0
  25. package/src/_internal/alert-dialog.tsx +159 -0
  26. package/src/_internal/alert.tsx +88 -0
  27. package/src/_internal/aspect-ratio.tsx +23 -0
  28. package/src/_internal/avatar.tsx +58 -0
  29. package/src/_internal/badge.tsx +60 -0
  30. package/src/_internal/breadcrumb.tsx +104 -0
  31. package/src/_internal/bubble.tsx +125 -0
  32. package/src/_internal/button-group.tsx +78 -0
  33. package/src/_internal/button.tsx +62 -0
  34. package/src/_internal/calendar.tsx +179 -0
  35. package/src/_internal/card.tsx +83 -0
  36. package/src/_internal/carousel.tsx +215 -0
  37. package/src/_internal/checkbox.tsx +26 -0
  38. package/src/_internal/code-block.tsx +53 -0
  39. package/src/_internal/collapsible.tsx +15 -0
  40. package/src/_internal/combobox.tsx +264 -0
  41. package/src/_internal/command.tsx +155 -0
  42. package/src/_internal/container.tsx +35 -0
  43. package/src/_internal/dialog.tsx +132 -0
  44. package/src/_internal/direction.tsx +12 -0
  45. package/src/_internal/divider.tsx +162 -0
  46. package/src/_internal/dropdown-menu.tsx +247 -0
  47. package/src/_internal/dropzone.tsx +481 -0
  48. package/src/_internal/empty.tsx +94 -0
  49. package/src/_internal/field.tsx +221 -0
  50. package/src/_internal/grid-overlay.tsx +48 -0
  51. package/src/_internal/grid.tsx +109 -0
  52. package/src/_internal/hover-card.tsx +47 -0
  53. package/src/_internal/icon.tsx +45 -0
  54. package/src/_internal/input-group.tsx +146 -0
  55. package/src/_internal/input.tsx +24 -0
  56. package/src/_internal/item.tsx +187 -0
  57. package/src/_internal/kbd.tsx +28 -0
  58. package/src/_internal/label.tsx +18 -0
  59. package/src/_internal/layout-bento.tsx +386 -0
  60. package/src/_internal/layout.tsx +174 -0
  61. package/src/_internal/marker.tsx +66 -0
  62. package/src/_internal/message.tsx +85 -0
  63. package/src/_internal/native-select.tsx +50 -0
  64. package/src/_internal/pagination.tsx +108 -0
  65. package/src/_internal/popover.tsx +83 -0
  66. package/src/_internal/progress.tsx +59 -0
  67. package/src/_internal/radio-group.tsx +36 -0
  68. package/src/_internal/resizable.tsx +44 -0
  69. package/src/_internal/scroll-area.tsx +48 -0
  70. package/src/_internal/select.tsx +187 -0
  71. package/src/_internal/separator.tsx +19 -0
  72. package/src/_internal/sheet.tsx +122 -0
  73. package/src/_internal/sidebar.tsx +687 -0
  74. package/src/_internal/skeleton.tsx +13 -0
  75. package/src/_internal/slider.tsx +60 -0
  76. package/src/_internal/sonner.tsx +51 -0
  77. package/src/_internal/spacer.tsx +42 -0
  78. package/src/_internal/spinner.tsx +16 -0
  79. package/src/_internal/stack.tsx +78 -0
  80. package/src/_internal/switch.tsx +31 -0
  81. package/src/_internal/table.tsx +84 -0
  82. package/src/_internal/tabs.tsx +74 -0
  83. package/src/_internal/textarea.tsx +19 -0
  84. package/src/_internal/toggle-group.tsx +99 -0
  85. package/src/_internal/toggle.tsx +42 -0
  86. package/src/_internal/tooltip.tsx +55 -0
  87. package/src/_internal/typography.tsx +129 -0
  88. package/src/hooks/use-mobile.ts +19 -0
  89. package/src/hooks/use-numeric-input.ts +119 -0
  90. package/src/index.ts +443 -0
  91. package/src/lib/numeric-input.ts +88 -0
  92. package/src/lib/utils.ts +39 -0
  93. package/src/opinionated/accordion.tsx +92 -0
  94. package/src/opinionated/ai/attachments.tsx +27 -0
  95. package/src/opinionated/ai/chain-of-thought.tsx +16 -0
  96. package/src/opinionated/ai/code-block.tsx +22 -0
  97. package/src/opinionated/ai/confirmation.tsx +16 -0
  98. package/src/opinionated/ai/conversation.tsx +13 -0
  99. package/src/opinionated/ai/index.ts +15 -0
  100. package/src/opinionated/ai/inline-citation.tsx +30 -0
  101. package/src/opinionated/ai/message.tsx +26 -0
  102. package/src/opinionated/ai/plan.tsx +18 -0
  103. package/src/opinionated/ai/prompt-input.tsx +29 -0
  104. package/src/opinionated/ai/reasoning.tsx +9 -0
  105. package/src/opinionated/ai/shimmer.tsx +4 -0
  106. package/src/opinionated/ai/sources.tsx +10 -0
  107. package/src/opinionated/ai/suggestion.tsx +6 -0
  108. package/src/opinionated/ai/task.tsx +12 -0
  109. package/src/opinionated/ai/tool.tsx +14 -0
  110. package/src/opinionated/alert-dialog.tsx +143 -0
  111. package/src/opinionated/alert.tsx +99 -0
  112. package/src/opinionated/aspect-ratio.tsx +12 -0
  113. package/src/opinionated/avatar.tsx +59 -0
  114. package/src/opinionated/badge.tsx +33 -0
  115. package/src/opinionated/breadcrumb.tsx +99 -0
  116. package/src/opinionated/bubble.tsx +9 -0
  117. package/src/opinionated/button.tsx +59 -0
  118. package/src/opinionated/calendar.tsx +20 -0
  119. package/src/opinionated/card.tsx +83 -0
  120. package/src/opinionated/carousel.tsx +99 -0
  121. package/src/opinionated/checkbox.tsx +11 -0
  122. package/src/opinionated/code-block.tsx +12 -0
  123. package/src/opinionated/collapsible.tsx +123 -0
  124. package/src/opinionated/combobox.tsx +123 -0
  125. package/src/opinionated/container.tsx +12 -0
  126. package/src/opinionated/dialog.tsx +124 -0
  127. package/src/opinionated/direction.tsx +6 -0
  128. package/src/opinionated/divider.tsx +13 -0
  129. package/src/opinionated/dropdown-menu.tsx +131 -0
  130. package/src/opinionated/dropzone.tsx +39 -0
  131. package/src/opinionated/empty.tsx +191 -0
  132. package/src/opinionated/field.tsx +26 -0
  133. package/src/opinionated/form-calendar-popover.tsx +138 -0
  134. package/src/opinionated/form-checkbox.tsx +107 -0
  135. package/src/opinionated/form-combobox.tsx +181 -0
  136. package/src/opinionated/form-date-of-birth.tsx +193 -0
  137. package/src/opinionated/form-dropzone.tsx +126 -0
  138. package/src/opinionated/form-input-group.tsx +184 -0
  139. package/src/opinionated/form-input.tsx +118 -0
  140. package/src/opinionated/form-multi-combobox.tsx +213 -0
  141. package/src/opinionated/form-multi-dropzone.tsx +141 -0
  142. package/src/opinionated/form-radiogroup.tsx +116 -0
  143. package/src/opinionated/form-select.tsx +176 -0
  144. package/src/opinionated/form-slider.tsx +100 -0
  145. package/src/opinionated/form-switch.tsx +117 -0
  146. package/src/opinionated/form-textarea.tsx +79 -0
  147. package/src/opinionated/grid-overlay.tsx +11 -0
  148. package/src/opinionated/grid.tsx +14 -0
  149. package/src/opinionated/hover-card.tsx +59 -0
  150. package/src/opinionated/icon.tsx +14 -0
  151. package/src/opinionated/input-group.tsx +20 -0
  152. package/src/opinionated/input.tsx +11 -0
  153. package/src/opinionated/item.tsx +182 -0
  154. package/src/opinionated/kbd.tsx +16 -0
  155. package/src/opinionated/label.tsx +11 -0
  156. package/src/opinionated/layout-bento.tsx +29 -0
  157. package/src/opinionated/layout.tsx +26 -0
  158. package/src/opinionated/list.tsx +94 -0
  159. package/src/opinionated/marker.tsx +7 -0
  160. package/src/opinionated/message.tsx +8 -0
  161. package/src/opinionated/native-select.tsx +51 -0
  162. package/src/opinionated/pagination.tsx +204 -0
  163. package/src/opinionated/popover.tsx +68 -0
  164. package/src/opinionated/progress.tsx +48 -0
  165. package/src/opinionated/radio-group.tsx +13 -0
  166. package/src/opinionated/resizable.tsx +2 -0
  167. package/src/opinionated/scroll-area.tsx +82 -0
  168. package/src/opinionated/select.tsx +101 -0
  169. package/src/opinionated/separator.tsx +11 -0
  170. package/src/opinionated/sheet.tsx +120 -0
  171. package/src/opinionated/sidebar.tsx +68 -0
  172. package/src/opinionated/skeleton.tsx +246 -0
  173. package/src/opinionated/slider.tsx +11 -0
  174. package/src/opinionated/sonner.tsx +15 -0
  175. package/src/opinionated/spacer.tsx +11 -0
  176. package/src/opinionated/stack.tsx +18 -0
  177. package/src/opinionated/switch.tsx +11 -0
  178. package/src/opinionated/table.tsx +11 -0
  179. package/src/opinionated/tabs.tsx +68 -0
  180. package/src/opinionated/textarea.tsx +11 -0
  181. package/src/opinionated/theme-injector.tsx +31 -0
  182. package/src/opinionated/toggle-group.tsx +63 -0
  183. package/src/opinionated/toggle.tsx +75 -0
  184. package/src/opinionated/token-config-panel/color-editor.tsx +85 -0
  185. package/src/opinionated/token-config-panel/helpers.ts +31 -0
  186. package/src/opinionated/token-config-panel/index.tsx +398 -0
  187. package/src/opinionated/token-config-panel/json-import-export.tsx +89 -0
  188. package/src/opinionated/token-config-panel/preset-manager.ts +31 -0
  189. package/src/opinionated/token-config-panel/presets-data.ts +23 -0
  190. package/src/opinionated/token-config-panel/spacing-editor.tsx +325 -0
  191. package/src/opinionated/token-config-panel/types.ts +39 -0
  192. package/src/opinionated/token-config-panel/typography-editor.tsx +145 -0
  193. package/src/opinionated/tooltip.tsx +62 -0
  194. package/src/opinionated/typography.tsx +7 -0
  195. package/src/scripts/lint-no-arbitrary.ts +155 -0
  196. package/src/styles/composable.css +68 -0
  197. package/src/styles/presets/brutalist.css +298 -0
  198. package/src/styles/presets/default.css +298 -0
  199. package/src/styles/presets/signal-pop.css +369 -0
  200. package/src/styles/presets-data/brutalist.ts +325 -0
  201. package/src/styles/presets-data/default.ts +315 -0
  202. package/src/styles/presets-data/index.ts +45 -0
  203. package/src/styles/presets-data/signal-pop.ts +393 -0
  204. package/src/styles/tokens/base.css +71 -0
  205. package/src/styles/tokens/components.css +150 -0
  206. package/src/styles/tokens/palette.css +795 -0
  207. package/src/styles/tokens/registry.ts +324 -0
  208. package/src/styles/tokens/semantic.css +266 -0
  209. package/src/styles/tokens/tailwind-theme.css +247 -0
@@ -0,0 +1,1285 @@
1
+ 'use client'
2
+
3
+ import {
4
+ Command,
5
+ CommandEmpty,
6
+ CommandGroup,
7
+ CommandInput,
8
+ CommandItem,
9
+ CommandList,
10
+ CommandSeparator,
11
+ } from '../command'
12
+ import {
13
+ DropdownMenu,
14
+ DropdownMenuContent,
15
+ DropdownMenuItem,
16
+ DropdownMenuTrigger,
17
+ } from '../dropdown-menu'
18
+ import { HoverCard, HoverCardContent, HoverCardTrigger } from '../hover-card'
19
+ import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupTextarea } from '../input-group'
20
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../select'
21
+ import { Spinner } from '../spinner'
22
+ import { Tooltip, TooltipContent, TooltipTrigger } from '../tooltip'
23
+ import { cn } from '../../lib/utils'
24
+ import type { ChatStatus, FileUIPart, SourceDocumentUIPart } from 'ai'
25
+ import { CornerDownLeftIcon, ImageIcon, Monitor, PlusIcon, SquareIcon, XIcon } from 'lucide-react'
26
+ import { nanoid } from 'nanoid'
27
+ import type {
28
+ ChangeEvent,
29
+ ChangeEventHandler,
30
+ ClipboardEventHandler,
31
+ ComponentProps,
32
+ FormEvent,
33
+ FormEventHandler,
34
+ HTMLAttributes,
35
+ KeyboardEventHandler,
36
+ PropsWithChildren,
37
+ ReactNode,
38
+ RefObject,
39
+ } from 'react'
40
+ import {
41
+ Children,
42
+ createContext,
43
+ useCallback,
44
+ useContext,
45
+ useEffect,
46
+ useMemo,
47
+ useRef,
48
+ useState,
49
+ } from 'react'
50
+
51
+ // ============================================================================
52
+ // Helpers
53
+ // ============================================================================
54
+
55
+ const convertBlobUrlToDataUrl = async (url: string): Promise<string | null> => {
56
+ try {
57
+ const response = await fetch(url)
58
+ const blob = await response.blob()
59
+ // FileReader uses callback-based API, wrapping in Promise is necessary
60
+ // oxlint-disable-next-line eslint-plugin-promise(avoid-new)
61
+ return new Promise((resolve) => {
62
+ const reader = new FileReader()
63
+ // oxlint-disable-next-line eslint-plugin-unicorn(prefer-add-event-listener)
64
+ reader.onloadend = () => resolve(reader.result as string)
65
+ // oxlint-disable-next-line eslint-plugin-unicorn(prefer-add-event-listener)
66
+ reader.onerror = () => resolve(null)
67
+ reader.readAsDataURL(blob)
68
+ })
69
+ } catch {
70
+ return null
71
+ }
72
+ }
73
+
74
+ const captureScreenshot = async (): Promise<File | null> => {
75
+ if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getDisplayMedia) {
76
+ return null
77
+ }
78
+
79
+ let stream: MediaStream | null = null
80
+ const video = document.createElement('video')
81
+ video.muted = true
82
+ video.playsInline = true
83
+
84
+ try {
85
+ stream = await navigator.mediaDevices.getDisplayMedia({
86
+ audio: false,
87
+ video: true,
88
+ })
89
+
90
+ video.srcObject = stream
91
+
92
+ // Video element uses callback-based API, wrapping in Promise is necessary
93
+ // oxlint-disable-next-line eslint-plugin-promise(avoid-new)
94
+ await new Promise<void>((resolve, reject) => {
95
+ // oxlint-disable-next-line eslint-plugin-unicorn(prefer-add-event-listener)
96
+ video.onloadedmetadata = () => resolve()
97
+ // oxlint-disable-next-line eslint-plugin-unicorn(prefer-add-event-listener)
98
+ video.onerror = () => reject(new Error('Failed to load screen stream'))
99
+ })
100
+
101
+ await video.play()
102
+
103
+ const width = video.videoWidth
104
+ const height = video.videoHeight
105
+ if (!width || !height) {
106
+ return null
107
+ }
108
+
109
+ const canvas = document.createElement('canvas')
110
+ canvas.width = width
111
+ canvas.height = height
112
+ const context = canvas.getContext('2d')
113
+ if (!context) {
114
+ return null
115
+ }
116
+
117
+ context.drawImage(video, 0, 0, width, height)
118
+ // canvas.toBlob uses callback-based API, wrapping in Promise is necessary
119
+ // oxlint-disable-next-line eslint-plugin-promise(avoid-new)
120
+ const blob = await new Promise<Blob | null>((resolve) => {
121
+ canvas.toBlob(resolve, 'image/png')
122
+ })
123
+ if (!blob) {
124
+ return null
125
+ }
126
+
127
+ const timestamp = new Date()
128
+ .toISOString()
129
+ .replaceAll(/[:.]/g, '-')
130
+ .replace('T', '_')
131
+ .replace('Z', '')
132
+
133
+ return new File([blob], `screenshot-${timestamp}.png`, {
134
+ lastModified: Date.now(),
135
+ type: 'image/png',
136
+ })
137
+ } finally {
138
+ if (stream) {
139
+ for (const track of stream.getTracks()) {
140
+ track.stop()
141
+ }
142
+ }
143
+ video.pause()
144
+ video.srcObject = null
145
+ }
146
+ }
147
+
148
+ // ============================================================================
149
+ // Provider Context & Types
150
+ // ============================================================================
151
+
152
+ export interface AttachmentsContext {
153
+ files: (FileUIPart & { id: string })[]
154
+ add: (files: File[] | FileList) => void
155
+ remove: (id: string) => void
156
+ clear: () => void
157
+ openFileDialog: () => void
158
+ fileInputRef: RefObject<HTMLInputElement | null>
159
+ }
160
+
161
+ export interface TextInputContext {
162
+ value: string
163
+ setInput: (v: string) => void
164
+ clear: () => void
165
+ }
166
+
167
+ export interface PromptInputControllerProps {
168
+ textInput: TextInputContext
169
+ attachments: AttachmentsContext
170
+ /** INTERNAL: Allows PromptInput to register its file textInput + "open" callback */
171
+ __registerFileInput: (ref: RefObject<HTMLInputElement | null>, open: () => void) => void
172
+ }
173
+
174
+ const PromptInputController = createContext<PromptInputControllerProps | null>(null)
175
+ const ProviderAttachmentsContext = createContext<AttachmentsContext | null>(null)
176
+
177
+ export const usePromptInputController = () => {
178
+ const ctx = useContext(PromptInputController)
179
+ if (!ctx) {
180
+ throw new Error(
181
+ 'Wrap your component inside <PromptInputProvider> to use usePromptInputController().',
182
+ )
183
+ }
184
+ return ctx
185
+ }
186
+
187
+ // Optional variants (do NOT throw). Useful for dual-mode components.
188
+ const useOptionalPromptInputController = () => useContext(PromptInputController)
189
+
190
+ export const useProviderAttachments = () => {
191
+ const ctx = useContext(ProviderAttachmentsContext)
192
+ if (!ctx) {
193
+ throw new Error(
194
+ 'Wrap your component inside <PromptInputProvider> to use useProviderAttachments().',
195
+ )
196
+ }
197
+ return ctx
198
+ }
199
+
200
+ const useOptionalProviderAttachments = () => useContext(ProviderAttachmentsContext)
201
+
202
+ export type PromptInputProviderProps = PropsWithChildren<{
203
+ initialInput?: string
204
+ }>
205
+
206
+ /**
207
+ * Optional global provider that lifts PromptInput state outside of PromptInput.
208
+ * If you don't use it, PromptInput stays fully self-managed.
209
+ */
210
+ export const PromptInputProvider = ({
211
+ initialInput: initialTextInput = '',
212
+ children,
213
+ }: PromptInputProviderProps) => {
214
+ // ----- textInput state
215
+ const [textInput, setTextInput] = useState(initialTextInput)
216
+ const clearInput = useCallback(() => setTextInput(''), [])
217
+
218
+ // ----- attachments state (global when wrapped)
219
+ const [attachmentFiles, setAttachmentFiles] = useState<(FileUIPart & { id: string })[]>([])
220
+ const fileInputRef = useRef<HTMLInputElement | null>(null)
221
+ // oxlint-disable-next-line eslint(no-empty-function)
222
+ const openRef = useRef<() => void>(() => {})
223
+
224
+ const add = useCallback((files: File[] | FileList) => {
225
+ const incoming = [...files]
226
+ if (incoming.length === 0) {
227
+ return
228
+ }
229
+
230
+ setAttachmentFiles((prev) => [
231
+ ...prev,
232
+ ...incoming.map((file) => ({
233
+ filename: file.name,
234
+ id: nanoid(),
235
+ mediaType: file.type,
236
+ type: 'file' as const,
237
+ url: URL.createObjectURL(file),
238
+ })),
239
+ ])
240
+ }, [])
241
+
242
+ const remove = useCallback((id: string) => {
243
+ setAttachmentFiles((prev) => {
244
+ const found = prev.find((f) => f.id === id)
245
+ if (found?.url) {
246
+ URL.revokeObjectURL(found.url)
247
+ }
248
+ return prev.filter((f) => f.id !== id)
249
+ })
250
+ }, [])
251
+
252
+ const clear = useCallback(() => {
253
+ setAttachmentFiles((prev) => {
254
+ for (const f of prev) {
255
+ if (f.url) {
256
+ URL.revokeObjectURL(f.url)
257
+ }
258
+ }
259
+ return []
260
+ })
261
+ }, [])
262
+
263
+ // Keep a ref to attachments for cleanup on unmount (avoids stale closure)
264
+ const attachmentsRef = useRef(attachmentFiles)
265
+
266
+ useEffect(() => {
267
+ attachmentsRef.current = attachmentFiles
268
+ }, [attachmentFiles])
269
+
270
+ // Cleanup blob URLs on unmount to prevent memory leaks
271
+ useEffect(
272
+ () => () => {
273
+ for (const f of attachmentsRef.current) {
274
+ if (f.url) {
275
+ URL.revokeObjectURL(f.url)
276
+ }
277
+ }
278
+ },
279
+ [],
280
+ )
281
+
282
+ const openFileDialog = useCallback(() => {
283
+ openRef.current?.()
284
+ }, [])
285
+
286
+ const attachments = useMemo<AttachmentsContext>(
287
+ () => ({
288
+ add,
289
+ clear,
290
+ fileInputRef,
291
+ files: attachmentFiles,
292
+ openFileDialog,
293
+ remove,
294
+ }),
295
+ [attachmentFiles, add, remove, clear, openFileDialog],
296
+ )
297
+
298
+ const __registerFileInput = useCallback(
299
+ (ref: RefObject<HTMLInputElement | null>, open: () => void) => {
300
+ fileInputRef.current = ref.current
301
+ openRef.current = open
302
+ },
303
+ [],
304
+ )
305
+
306
+ const controller = useMemo<PromptInputControllerProps>(
307
+ () => ({
308
+ __registerFileInput,
309
+ attachments,
310
+ textInput: {
311
+ clear: clearInput,
312
+ setInput: setTextInput,
313
+ value: textInput,
314
+ },
315
+ }),
316
+ [textInput, clearInput, attachments, __registerFileInput],
317
+ )
318
+
319
+ return (
320
+ <PromptInputController.Provider value={controller}>
321
+ <ProviderAttachmentsContext.Provider value={attachments}>
322
+ {children}
323
+ </ProviderAttachmentsContext.Provider>
324
+ </PromptInputController.Provider>
325
+ )
326
+ }
327
+
328
+ // ============================================================================
329
+ // Component Context & Hooks
330
+ // ============================================================================
331
+
332
+ const LocalAttachmentsContext = createContext<AttachmentsContext | null>(null)
333
+
334
+ export const usePromptInputAttachments = () => {
335
+ // Prefer local context (inside PromptInput) as it has validation, fall back to provider
336
+ const provider = useOptionalProviderAttachments()
337
+ const local = useContext(LocalAttachmentsContext)
338
+ const context = local ?? provider
339
+ if (!context) {
340
+ throw new Error(
341
+ 'usePromptInputAttachments must be used within a PromptInput or PromptInputProvider',
342
+ )
343
+ }
344
+ return context
345
+ }
346
+
347
+ // ============================================================================
348
+ // Referenced Sources (Local to PromptInput)
349
+ // ============================================================================
350
+
351
+ export interface ReferencedSourcesContext {
352
+ sources: (SourceDocumentUIPart & { id: string })[]
353
+ add: (sources: SourceDocumentUIPart[] | SourceDocumentUIPart) => void
354
+ remove: (id: string) => void
355
+ clear: () => void
356
+ }
357
+
358
+ export const LocalReferencedSourcesContext = createContext<ReferencedSourcesContext | null>(null)
359
+
360
+ export const usePromptInputReferencedSources = () => {
361
+ const ctx = useContext(LocalReferencedSourcesContext)
362
+ if (!ctx) {
363
+ throw new Error(
364
+ 'usePromptInputReferencedSources must be used within a LocalReferencedSourcesContext.Provider',
365
+ )
366
+ }
367
+ return ctx
368
+ }
369
+
370
+ export type PromptInputActionAddAttachmentsProps = ComponentProps<typeof DropdownMenuItem> & {
371
+ label?: string
372
+ }
373
+
374
+ export const PromptInputActionAddAttachments = ({
375
+ label = 'Add photos or files',
376
+ ...props
377
+ }: PromptInputActionAddAttachmentsProps) => {
378
+ const attachments = usePromptInputAttachments()
379
+
380
+ const handleSelect = useCallback(
381
+ (e: any) => {
382
+ e.preventDefault()
383
+ attachments.openFileDialog()
384
+ },
385
+ [attachments],
386
+ )
387
+
388
+ return (
389
+ <DropdownMenuItem {...props} onSelect={handleSelect}>
390
+ <ImageIcon className="mr-2 size-4" /> {label}
391
+ </DropdownMenuItem>
392
+ )
393
+ }
394
+
395
+ export type PromptInputActionAddScreenshotProps = ComponentProps<typeof DropdownMenuItem> & {
396
+ label?: string
397
+ }
398
+
399
+ export const PromptInputActionAddScreenshot = ({
400
+ label = 'Take screenshot',
401
+ onSelect,
402
+ ...props
403
+ }: PromptInputActionAddScreenshotProps) => {
404
+ const attachments = usePromptInputAttachments()
405
+
406
+ const handleSelect = useCallback(
407
+ async (event: any) => {
408
+ onSelect?.(event)
409
+ if (event.defaultPrevented) {
410
+ return
411
+ }
412
+
413
+ try {
414
+ const screenshot = await captureScreenshot()
415
+ if (screenshot) {
416
+ attachments.add([screenshot])
417
+ }
418
+ } catch (error) {
419
+ if (
420
+ error instanceof DOMException &&
421
+ (error.name === 'NotAllowedError' || error.name === 'AbortError')
422
+ ) {
423
+ return
424
+ }
425
+ throw error
426
+ }
427
+ },
428
+ [onSelect, attachments],
429
+ )
430
+
431
+ return (
432
+ <DropdownMenuItem {...props} onSelect={handleSelect}>
433
+ <Monitor className="mr-2 size-4" />
434
+ {label}
435
+ </DropdownMenuItem>
436
+ )
437
+ }
438
+
439
+ export interface PromptInputMessage {
440
+ text: string
441
+ files: FileUIPart[]
442
+ }
443
+
444
+ export type PromptInputProps = Omit<HTMLAttributes<HTMLFormElement>, 'onSubmit' | 'onError'> & {
445
+ // e.g., "image/*" or leave undefined for any
446
+ accept?: string
447
+ multiple?: boolean
448
+ // When true, accepts drops anywhere on document. Default false (opt-in).
449
+ globalDrop?: boolean
450
+ // Render a hidden input with given name and keep it in sync for native form posts. Default false.
451
+ syncHiddenInput?: boolean
452
+ // Minimal constraints
453
+ maxFiles?: number
454
+ // bytes
455
+ maxFileSize?: number
456
+ onError?: (err: { code: 'max_files' | 'max_file_size' | 'accept'; message: string }) => void
457
+ onSubmit: (message: PromptInputMessage, event: FormEvent<HTMLFormElement>) => void | Promise<void>
458
+ }
459
+
460
+ export const PromptInput = ({
461
+ className,
462
+ accept,
463
+ multiple,
464
+ globalDrop,
465
+ syncHiddenInput,
466
+ maxFiles,
467
+ maxFileSize,
468
+ onError,
469
+ onSubmit,
470
+ children,
471
+ ...props
472
+ }: PromptInputProps) => {
473
+ // Try to use a provider controller if present
474
+ const controller = useOptionalPromptInputController()
475
+ const usingProvider = !!controller
476
+
477
+ // Refs
478
+ const inputRef = useRef<HTMLInputElement | null>(null)
479
+ const formRef = useRef<HTMLFormElement | null>(null)
480
+
481
+ // ----- Local attachments (only used when no provider)
482
+ const [items, setItems] = useState<(FileUIPart & { id: string })[]>([])
483
+ const files = usingProvider ? controller.attachments.files : items
484
+
485
+ // ----- Local referenced sources (always local to PromptInput)
486
+ const [referencedSources, setReferencedSources] = useState<
487
+ (SourceDocumentUIPart & { id: string })[]
488
+ >([])
489
+
490
+ // Keep a ref to files for cleanup on unmount (avoids stale closure)
491
+ const filesRef = useRef(files)
492
+
493
+ useEffect(() => {
494
+ filesRef.current = files
495
+ }, [files])
496
+
497
+ const openFileDialogLocal = useCallback(() => {
498
+ inputRef.current?.click()
499
+ }, [])
500
+
501
+ const matchesAccept = useCallback(
502
+ (f: File) => {
503
+ if (!accept || accept.trim() === '') {
504
+ return true
505
+ }
506
+
507
+ const patterns = accept
508
+ .split(',')
509
+ .map((s) => s.trim())
510
+ .filter(Boolean)
511
+
512
+ return patterns.some((pattern) => {
513
+ if (pattern.endsWith('/*')) {
514
+ // e.g: image/* -> image/
515
+ const prefix = pattern.slice(0, -1)
516
+ return f.type.startsWith(prefix)
517
+ }
518
+ return f.type === pattern
519
+ })
520
+ },
521
+ [accept],
522
+ )
523
+
524
+ const addLocal = useCallback(
525
+ (fileList: File[] | FileList) => {
526
+ const incoming = [...fileList]
527
+ const accepted = incoming.filter((f) => matchesAccept(f))
528
+ if (incoming.length && accepted.length === 0) {
529
+ onError?.({
530
+ code: 'accept',
531
+ message: 'No files match the accepted types.',
532
+ })
533
+ return
534
+ }
535
+ const withinSize = (f: File) => (maxFileSize ? f.size <= maxFileSize : true)
536
+ const sized = accepted.filter(withinSize)
537
+ if (accepted.length > 0 && sized.length === 0) {
538
+ onError?.({
539
+ code: 'max_file_size',
540
+ message: 'All files exceed the maximum size.',
541
+ })
542
+ return
543
+ }
544
+
545
+ setItems((prev) => {
546
+ const capacity =
547
+ typeof maxFiles === 'number' ? Math.max(0, maxFiles - prev.length) : undefined
548
+ const capped = typeof capacity === 'number' ? sized.slice(0, capacity) : sized
549
+ if (typeof capacity === 'number' && sized.length > capacity) {
550
+ onError?.({
551
+ code: 'max_files',
552
+ message: 'Too many files. Some were not added.',
553
+ })
554
+ }
555
+ const next: (FileUIPart & { id: string })[] = []
556
+ for (const file of capped) {
557
+ next.push({
558
+ filename: file.name,
559
+ id: nanoid(),
560
+ mediaType: file.type,
561
+ type: 'file',
562
+ url: URL.createObjectURL(file),
563
+ })
564
+ }
565
+ return [...prev, ...next]
566
+ })
567
+ },
568
+ [matchesAccept, maxFiles, maxFileSize, onError],
569
+ )
570
+
571
+ const removeLocal = useCallback(
572
+ (id: string) =>
573
+ setItems((prev) => {
574
+ const found = prev.find((file) => file.id === id)
575
+ if (found?.url) {
576
+ URL.revokeObjectURL(found.url)
577
+ }
578
+ return prev.filter((file) => file.id !== id)
579
+ }),
580
+ [],
581
+ )
582
+
583
+ // Wrapper that validates files before calling provider's add
584
+ const addWithProviderValidation = useCallback(
585
+ (fileList: File[] | FileList) => {
586
+ const incoming = [...fileList]
587
+ const accepted = incoming.filter((f) => matchesAccept(f))
588
+ if (incoming.length && accepted.length === 0) {
589
+ onError?.({
590
+ code: 'accept',
591
+ message: 'No files match the accepted types.',
592
+ })
593
+ return
594
+ }
595
+ const withinSize = (f: File) => (maxFileSize ? f.size <= maxFileSize : true)
596
+ const sized = accepted.filter(withinSize)
597
+ if (accepted.length > 0 && sized.length === 0) {
598
+ onError?.({
599
+ code: 'max_file_size',
600
+ message: 'All files exceed the maximum size.',
601
+ })
602
+ return
603
+ }
604
+
605
+ const currentCount = files.length
606
+ const capacity =
607
+ typeof maxFiles === 'number' ? Math.max(0, maxFiles - currentCount) : undefined
608
+ const capped = typeof capacity === 'number' ? sized.slice(0, capacity) : sized
609
+ if (typeof capacity === 'number' && sized.length > capacity) {
610
+ onError?.({
611
+ code: 'max_files',
612
+ message: 'Too many files. Some were not added.',
613
+ })
614
+ }
615
+
616
+ if (capped.length > 0) {
617
+ controller?.attachments.add(capped)
618
+ }
619
+ },
620
+ [matchesAccept, maxFileSize, maxFiles, onError, files.length, controller],
621
+ )
622
+
623
+ const clearAttachments = useCallback(
624
+ () =>
625
+ usingProvider
626
+ ? controller?.attachments.clear()
627
+ : setItems((prev) => {
628
+ for (const file of prev) {
629
+ if (file.url) {
630
+ URL.revokeObjectURL(file.url)
631
+ }
632
+ }
633
+ return []
634
+ }),
635
+ [usingProvider, controller],
636
+ )
637
+
638
+ const clearReferencedSources = useCallback(() => setReferencedSources([]), [])
639
+
640
+ const add = usingProvider ? addWithProviderValidation : addLocal
641
+ const remove = usingProvider ? controller.attachments.remove : removeLocal
642
+ const openFileDialog = usingProvider ? controller.attachments.openFileDialog : openFileDialogLocal
643
+
644
+ const clear = useCallback(() => {
645
+ clearAttachments()
646
+ clearReferencedSources()
647
+ }, [clearAttachments, clearReferencedSources])
648
+
649
+ // Let provider know about our hidden file input so external menus can call openFileDialog()
650
+ useEffect(() => {
651
+ if (!usingProvider) {
652
+ return
653
+ }
654
+ controller.__registerFileInput(inputRef, () => inputRef.current?.click())
655
+ }, [usingProvider, controller])
656
+
657
+ // Note: File input cannot be programmatically set for security reasons
658
+ // The syncHiddenInput prop is no longer functional
659
+ useEffect(() => {
660
+ if (syncHiddenInput && inputRef.current && files.length === 0) {
661
+ inputRef.current.value = ''
662
+ }
663
+ }, [files, syncHiddenInput])
664
+
665
+ // Attach drop handlers on nearest form and document (opt-in)
666
+ useEffect(() => {
667
+ const form = formRef.current
668
+ if (!form) {
669
+ return
670
+ }
671
+ if (globalDrop) {
672
+ // when global drop is on, let the document-level handler own drops
673
+ return
674
+ }
675
+
676
+ const onDragOver = (e: DragEvent) => {
677
+ if (e.dataTransfer?.types?.includes('Files')) {
678
+ e.preventDefault()
679
+ }
680
+ }
681
+ const onDrop = (e: DragEvent) => {
682
+ if (e.dataTransfer?.types?.includes('Files')) {
683
+ e.preventDefault()
684
+ }
685
+ if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
686
+ add(e.dataTransfer.files)
687
+ }
688
+ }
689
+ form.addEventListener('dragover', onDragOver)
690
+ form.addEventListener('drop', onDrop)
691
+ return () => {
692
+ form.removeEventListener('dragover', onDragOver)
693
+ form.removeEventListener('drop', onDrop)
694
+ }
695
+ }, [add, globalDrop])
696
+
697
+ useEffect(() => {
698
+ if (!globalDrop) {
699
+ return
700
+ }
701
+
702
+ const onDragOver = (e: DragEvent) => {
703
+ if (e.dataTransfer?.types?.includes('Files')) {
704
+ e.preventDefault()
705
+ }
706
+ }
707
+ const onDrop = (e: DragEvent) => {
708
+ if (e.dataTransfer?.types?.includes('Files')) {
709
+ e.preventDefault()
710
+ }
711
+ if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
712
+ add(e.dataTransfer.files)
713
+ }
714
+ }
715
+ document.addEventListener('dragover', onDragOver)
716
+ document.addEventListener('drop', onDrop)
717
+ return () => {
718
+ document.removeEventListener('dragover', onDragOver)
719
+ document.removeEventListener('drop', onDrop)
720
+ }
721
+ }, [add, globalDrop])
722
+
723
+ useEffect(
724
+ () => () => {
725
+ if (!usingProvider) {
726
+ for (const f of filesRef.current) {
727
+ if (f.url) {
728
+ URL.revokeObjectURL(f.url)
729
+ }
730
+ }
731
+ }
732
+ },
733
+ [usingProvider],
734
+ )
735
+
736
+ const handleChange: ChangeEventHandler<HTMLInputElement> = useCallback(
737
+ (event) => {
738
+ if (event.currentTarget.files) {
739
+ add(event.currentTarget.files)
740
+ }
741
+ // Reset input value to allow selecting files that were previously removed
742
+ event.currentTarget.value = ''
743
+ },
744
+ [add],
745
+ )
746
+
747
+ const attachmentsCtx = useMemo<AttachmentsContext>(
748
+ () => ({
749
+ add,
750
+ clear: clearAttachments,
751
+ fileInputRef: inputRef,
752
+ files: files.map((item) => ({ ...item, id: item.id })),
753
+ openFileDialog,
754
+ remove,
755
+ }),
756
+ [files, add, remove, clearAttachments, openFileDialog],
757
+ )
758
+
759
+ const refsCtx = useMemo<ReferencedSourcesContext>(
760
+ () => ({
761
+ add: (incoming: SourceDocumentUIPart[] | SourceDocumentUIPart) => {
762
+ const array = Array.isArray(incoming) ? incoming : [incoming]
763
+ setReferencedSources((prev) => [...prev, ...array.map((s) => ({ ...s, id: nanoid() }))])
764
+ },
765
+ clear: clearReferencedSources,
766
+ remove: (id: string) => {
767
+ setReferencedSources((prev) => prev.filter((s) => s.id !== id))
768
+ },
769
+ sources: referencedSources,
770
+ }),
771
+ [referencedSources, clearReferencedSources],
772
+ )
773
+
774
+ const handleSubmit: FormEventHandler<HTMLFormElement> = useCallback(
775
+ async (event) => {
776
+ event.preventDefault()
777
+
778
+ const form = event.currentTarget
779
+ const text = usingProvider
780
+ ? controller.textInput.value
781
+ : (() => {
782
+ const formData = new FormData(form)
783
+ return (formData.get('message') as string) || ''
784
+ })()
785
+
786
+ // Reset form immediately after capturing text to avoid race condition
787
+ // where user input during async blob conversion would be lost
788
+ if (!usingProvider) {
789
+ form.reset()
790
+ }
791
+
792
+ try {
793
+ // Convert blob URLs to data URLs asynchronously
794
+ const convertedFiles: FileUIPart[] = await Promise.all(
795
+ files.map(async ({ id: _id, ...item }) => {
796
+ if (item.url?.startsWith('blob:')) {
797
+ const dataUrl = await convertBlobUrlToDataUrl(item.url)
798
+ // If conversion failed, keep the original blob URL
799
+ return {
800
+ ...item,
801
+ url: dataUrl ?? item.url,
802
+ }
803
+ }
804
+ return item
805
+ }),
806
+ )
807
+
808
+ const result = onSubmit({ files: convertedFiles, text }, event)
809
+
810
+ // Handle both sync and async onSubmit
811
+ if (result instanceof Promise) {
812
+ try {
813
+ await result
814
+ clear()
815
+ if (usingProvider) {
816
+ controller.textInput.clear()
817
+ }
818
+ } catch {
819
+ // Don't clear on error - user may want to retry
820
+ }
821
+ } else {
822
+ // Sync function completed without throwing, clear inputs
823
+ clear()
824
+ if (usingProvider) {
825
+ controller.textInput.clear()
826
+ }
827
+ }
828
+ } catch {
829
+ // Don't clear on error - user may want to retry
830
+ }
831
+ },
832
+ [usingProvider, controller, files, onSubmit, clear],
833
+ )
834
+
835
+ // Render with or without local provider
836
+ const inner = (
837
+ <>
838
+ <input
839
+ accept={accept}
840
+ aria-label="Upload files"
841
+ className="hidden"
842
+ multiple={multiple}
843
+ onChange={handleChange}
844
+ ref={inputRef}
845
+ title="Upload files"
846
+ type="file"
847
+ />
848
+ <form className={cn('w-full', className)} onSubmit={handleSubmit} ref={formRef} {...props}>
849
+ <InputGroup className="overflow-hidden">{children}</InputGroup>
850
+ </form>
851
+ </>
852
+ )
853
+
854
+ const withReferencedSources = (
855
+ <LocalReferencedSourcesContext.Provider value={refsCtx}>
856
+ {inner}
857
+ </LocalReferencedSourcesContext.Provider>
858
+ )
859
+
860
+ // Always provide LocalAttachmentsContext so children get validated add function
861
+ return (
862
+ <LocalAttachmentsContext.Provider value={attachmentsCtx}>
863
+ {withReferencedSources}
864
+ </LocalAttachmentsContext.Provider>
865
+ )
866
+ }
867
+
868
+ export type PromptInputBodyProps = HTMLAttributes<HTMLDivElement>
869
+
870
+ export const PromptInputBody = ({ className, ...props }: PromptInputBodyProps) => (
871
+ <div className={cn('contents', className)} {...props} />
872
+ )
873
+
874
+ export type PromptInputTextareaProps = ComponentProps<typeof InputGroupTextarea>
875
+
876
+ export const PromptInputTextarea = ({
877
+ onChange,
878
+ onKeyDown,
879
+ className,
880
+ placeholder = 'What would you like to know?',
881
+ ...props
882
+ }: PromptInputTextareaProps) => {
883
+ const controller = useOptionalPromptInputController()
884
+ const attachments = usePromptInputAttachments()
885
+ const [isComposing, setIsComposing] = useState(false)
886
+
887
+ const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = useCallback(
888
+ (e) => {
889
+ // Call the external onKeyDown handler first
890
+ onKeyDown?.(e)
891
+
892
+ // If the external handler prevented default, don't run internal logic
893
+ if (e.defaultPrevented) {
894
+ return
895
+ }
896
+
897
+ if (e.key === 'Enter') {
898
+ if (isComposing || e.nativeEvent.isComposing) {
899
+ return
900
+ }
901
+ if (e.shiftKey) {
902
+ return
903
+ }
904
+ e.preventDefault()
905
+
906
+ // Check if the submit button is disabled before submitting
907
+ const { form } = e.currentTarget
908
+ const submitButton = form?.querySelector(
909
+ 'button[type="submit"]',
910
+ ) as HTMLButtonElement | null
911
+ if (submitButton?.disabled) {
912
+ return
913
+ }
914
+
915
+ form?.requestSubmit()
916
+ }
917
+
918
+ // Remove last attachment when Backspace is pressed and textarea is empty
919
+ if (e.key === 'Backspace' && e.currentTarget.value === '' && attachments.files.length > 0) {
920
+ e.preventDefault()
921
+ const lastAttachment = attachments.files.at(-1)
922
+ if (lastAttachment) {
923
+ attachments.remove(lastAttachment.id)
924
+ }
925
+ }
926
+ },
927
+ [onKeyDown, isComposing, attachments],
928
+ )
929
+
930
+ const handlePaste: ClipboardEventHandler<HTMLTextAreaElement> = useCallback(
931
+ (event) => {
932
+ const items = event.clipboardData?.items
933
+
934
+ if (!items) {
935
+ return
936
+ }
937
+
938
+ const files: File[] = []
939
+
940
+ for (const item of items) {
941
+ if (item.kind === 'file') {
942
+ const file = item.getAsFile()
943
+ if (file) {
944
+ files.push(file)
945
+ }
946
+ }
947
+ }
948
+
949
+ if (files.length > 0) {
950
+ event.preventDefault()
951
+ attachments.add(files)
952
+ }
953
+ },
954
+ [attachments],
955
+ )
956
+
957
+ const handleCompositionEnd = useCallback(() => setIsComposing(false), [])
958
+ const handleCompositionStart = useCallback(() => setIsComposing(true), [])
959
+
960
+ const controlledProps = controller
961
+ ? {
962
+ onChange: (e: ChangeEvent<HTMLTextAreaElement>) => {
963
+ controller.textInput.setInput(e.currentTarget.value)
964
+ onChange?.(e)
965
+ },
966
+ value: controller.textInput.value,
967
+ }
968
+ : {
969
+ onChange,
970
+ }
971
+
972
+ return (
973
+ <InputGroupTextarea
974
+ className={cn('field-sizing-content max-h-48 min-h-16', className)}
975
+ name="message"
976
+ onCompositionEnd={handleCompositionEnd}
977
+ onCompositionStart={handleCompositionStart}
978
+ onKeyDown={handleKeyDown}
979
+ onPaste={handlePaste}
980
+ placeholder={placeholder}
981
+ {...props}
982
+ {...controlledProps}
983
+ />
984
+ )
985
+ }
986
+
987
+ export type PromptInputHeaderProps = Omit<ComponentProps<typeof InputGroupAddon>, 'align'>
988
+
989
+ export const PromptInputHeader = ({ className, ...props }: PromptInputHeaderProps) => (
990
+ <InputGroupAddon
991
+ align="block-end"
992
+ className={cn('order-first flex-wrap gap-1', className)}
993
+ {...props}
994
+ />
995
+ )
996
+
997
+ export type PromptInputFooterProps = Omit<ComponentProps<typeof InputGroupAddon>, 'align'>
998
+
999
+ export const PromptInputFooter = ({ className, ...props }: PromptInputFooterProps) => (
1000
+ <InputGroupAddon
1001
+ align="block-end"
1002
+ className={cn('justify-between gap-1', className)}
1003
+ {...props}
1004
+ />
1005
+ )
1006
+
1007
+ export type PromptInputToolsProps = HTMLAttributes<HTMLDivElement>
1008
+
1009
+ export const PromptInputTools = ({ className, ...props }: PromptInputToolsProps) => (
1010
+ <div className={cn('flex min-w-0 items-center gap-1', className)} {...props} />
1011
+ )
1012
+
1013
+ export type PromptInputButtonTooltip =
1014
+ | string
1015
+ | {
1016
+ content: ReactNode
1017
+ shortcut?: string
1018
+ side?: ComponentProps<typeof TooltipContent>['side']
1019
+ }
1020
+
1021
+ export type PromptInputButtonProps = ComponentProps<typeof InputGroupButton> & {
1022
+ tooltip?: PromptInputButtonTooltip
1023
+ }
1024
+
1025
+ export const PromptInputButton = ({
1026
+ variant = 'ghost',
1027
+ className,
1028
+ size,
1029
+ tooltip,
1030
+ ...props
1031
+ }: PromptInputButtonProps) => {
1032
+ const newSize = size ?? (Children.count(props.children) > 1 ? 'sm' : 'icon-sm')
1033
+
1034
+ const button = (
1035
+ <InputGroupButton
1036
+ className={cn(className)}
1037
+ size={newSize}
1038
+ type="button"
1039
+ variant={variant}
1040
+ {...props}
1041
+ />
1042
+ )
1043
+
1044
+ if (!tooltip) {
1045
+ return button
1046
+ }
1047
+
1048
+ const tooltipContent = typeof tooltip === 'string' ? tooltip : tooltip.content
1049
+ const shortcut = typeof tooltip === 'string' ? undefined : tooltip.shortcut
1050
+ const side = typeof tooltip === 'string' ? 'top' : (tooltip.side ?? 'top')
1051
+
1052
+ return (
1053
+ <Tooltip>
1054
+ <TooltipTrigger>{button}</TooltipTrigger>
1055
+ <TooltipContent side={side}>
1056
+ {tooltipContent}
1057
+ {shortcut && <span className="ml-2 text-muted-foreground">{shortcut}</span>}
1058
+ </TooltipContent>
1059
+ </Tooltip>
1060
+ )
1061
+ }
1062
+
1063
+ export type PromptInputActionMenuProps = ComponentProps<typeof DropdownMenu>
1064
+ export const PromptInputActionMenu = (props: PromptInputActionMenuProps) => (
1065
+ <DropdownMenu {...props} />
1066
+ )
1067
+
1068
+ export type PromptInputActionMenuTriggerProps = PromptInputButtonProps
1069
+
1070
+ export const PromptInputActionMenuTrigger = ({
1071
+ className,
1072
+ children,
1073
+ ...props
1074
+ }: PromptInputActionMenuTriggerProps) => (
1075
+ <DropdownMenuTrigger>
1076
+ <PromptInputButton className={className} {...props}>
1077
+ {children ?? <PlusIcon className="size-4" />}
1078
+ </PromptInputButton>
1079
+ </DropdownMenuTrigger>
1080
+ )
1081
+
1082
+ export type PromptInputActionMenuContentProps = ComponentProps<typeof DropdownMenuContent>
1083
+ export const PromptInputActionMenuContent = ({
1084
+ className,
1085
+ ...props
1086
+ }: PromptInputActionMenuContentProps) => (
1087
+ <DropdownMenuContent align="start" className={cn(className)} {...props} />
1088
+ )
1089
+
1090
+ export type PromptInputActionMenuItemProps = ComponentProps<typeof DropdownMenuItem>
1091
+ export const PromptInputActionMenuItem = ({
1092
+ className,
1093
+ ...props
1094
+ }: PromptInputActionMenuItemProps) => <DropdownMenuItem className={cn(className)} {...props} />
1095
+
1096
+ // Note: Actions that perform side-effects (like opening a file dialog)
1097
+ // are provided in opt-in modules (e.g., prompt-input-attachments).
1098
+
1099
+ export type PromptInputSubmitProps = ComponentProps<typeof InputGroupButton> & {
1100
+ status?: ChatStatus
1101
+ onStop?: () => void
1102
+ }
1103
+
1104
+ export const PromptInputSubmit = ({
1105
+ className,
1106
+ variant = 'default',
1107
+ size = 'icon-sm',
1108
+ status,
1109
+ onStop,
1110
+ onClick,
1111
+ children,
1112
+ ...props
1113
+ }: PromptInputSubmitProps) => {
1114
+ const isGenerating = status === 'submitted' || status === 'streaming'
1115
+
1116
+ let Icon = <CornerDownLeftIcon className="size-4" />
1117
+
1118
+ if (status === 'submitted') {
1119
+ Icon = <Spinner />
1120
+ } else if (status === 'streaming') {
1121
+ Icon = <SquareIcon className="size-4" />
1122
+ } else if (status === 'error') {
1123
+ Icon = <XIcon className="size-4" />
1124
+ }
1125
+
1126
+ const handleClick = useCallback(
1127
+ (e: any) => {
1128
+ if (isGenerating && onStop) {
1129
+ e.preventDefault()
1130
+ onStop()
1131
+ return
1132
+ }
1133
+ onClick?.(e)
1134
+ },
1135
+ [isGenerating, onStop, onClick],
1136
+ )
1137
+
1138
+ return (
1139
+ <InputGroupButton
1140
+ aria-label={isGenerating ? 'Stop' : 'Submit'}
1141
+ className={cn(className)}
1142
+ onClick={handleClick}
1143
+ size={size}
1144
+ type={isGenerating && onStop ? 'button' : 'submit'}
1145
+ variant={variant}
1146
+ {...props}
1147
+ >
1148
+ {children ?? Icon}
1149
+ </InputGroupButton>
1150
+ )
1151
+ }
1152
+
1153
+ export type PromptInputSelectProps = ComponentProps<typeof Select>
1154
+
1155
+ export const PromptInputSelect = (props: PromptInputSelectProps) => <Select {...props} />
1156
+
1157
+ export type PromptInputSelectTriggerProps = ComponentProps<typeof SelectTrigger>
1158
+
1159
+ export const PromptInputSelectTrigger = ({
1160
+ className,
1161
+ ...props
1162
+ }: PromptInputSelectTriggerProps) => (
1163
+ <SelectTrigger
1164
+ className={cn(
1165
+ 'border-none bg-transparent font-medium text-muted-foreground shadow-none transition-colors',
1166
+ 'hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground',
1167
+ className,
1168
+ )}
1169
+ {...props}
1170
+ />
1171
+ )
1172
+
1173
+ export type PromptInputSelectContentProps = ComponentProps<typeof SelectContent>
1174
+
1175
+ export const PromptInputSelectContent = ({
1176
+ className,
1177
+ ...props
1178
+ }: PromptInputSelectContentProps) => <SelectContent className={cn(className)} {...props} />
1179
+
1180
+ export type PromptInputSelectItemProps = ComponentProps<typeof SelectItem>
1181
+
1182
+ export const PromptInputSelectItem = ({ className, ...props }: PromptInputSelectItemProps) => (
1183
+ <SelectItem className={cn(className)} {...props} />
1184
+ )
1185
+
1186
+ export type PromptInputSelectValueProps = ComponentProps<typeof SelectValue>
1187
+
1188
+ export const PromptInputSelectValue = ({ className, ...props }: PromptInputSelectValueProps) => (
1189
+ <SelectValue className={cn(className)} {...props} />
1190
+ )
1191
+
1192
+ export type PromptInputHoverCardProps = ComponentProps<typeof HoverCard>
1193
+
1194
+ export const PromptInputHoverCard = (props: PromptInputHoverCardProps) => <HoverCard {...props} />
1195
+
1196
+ export type PromptInputHoverCardTriggerProps = ComponentProps<typeof HoverCardTrigger>
1197
+
1198
+ export const PromptInputHoverCardTrigger = (props: PromptInputHoverCardTriggerProps) => (
1199
+ <HoverCardTrigger {...props} />
1200
+ )
1201
+
1202
+ export type PromptInputHoverCardContentProps = ComponentProps<typeof HoverCardContent>
1203
+
1204
+ export const PromptInputHoverCardContent = ({
1205
+ align = 'start',
1206
+ ...props
1207
+ }: PromptInputHoverCardContentProps) => <HoverCardContent align={align} {...props} />
1208
+
1209
+ export type PromptInputTabsListProps = HTMLAttributes<HTMLDivElement>
1210
+
1211
+ export const PromptInputTabsList = ({ className, ...props }: PromptInputTabsListProps) => (
1212
+ <div className={cn(className)} {...props} />
1213
+ )
1214
+
1215
+ export type PromptInputTabProps = HTMLAttributes<HTMLDivElement>
1216
+
1217
+ export const PromptInputTab = ({ className, ...props }: PromptInputTabProps) => (
1218
+ <div className={cn(className)} {...props} />
1219
+ )
1220
+
1221
+ export type PromptInputTabLabelProps = HTMLAttributes<HTMLHeadingElement>
1222
+
1223
+ export const PromptInputTabLabel = ({ className, ...props }: PromptInputTabLabelProps) => (
1224
+ // Content provided via children in props
1225
+ // oxlint-disable-next-line eslint-plugin-jsx-a11y(heading-has-content)
1226
+ <h3 className={cn('mb-2 px-3 font-medium text-muted-foreground text-xs', className)} {...props} />
1227
+ )
1228
+
1229
+ export type PromptInputTabBodyProps = HTMLAttributes<HTMLDivElement>
1230
+
1231
+ export const PromptInputTabBody = ({ className, ...props }: PromptInputTabBodyProps) => (
1232
+ <div className={cn('space-y-1', className)} {...props} />
1233
+ )
1234
+
1235
+ export type PromptInputTabItemProps = HTMLAttributes<HTMLDivElement>
1236
+
1237
+ export const PromptInputTabItem = ({ className, ...props }: PromptInputTabItemProps) => (
1238
+ <div
1239
+ className={cn('flex items-center gap-2 px-3 py-2 text-xs hover:bg-muted', className)}
1240
+ {...props}
1241
+ />
1242
+ )
1243
+
1244
+ export type PromptInputCommandProps = ComponentProps<typeof Command>
1245
+
1246
+ export const PromptInputCommand = ({ className, ...props }: PromptInputCommandProps) => (
1247
+ <Command className={cn(className)} {...props} />
1248
+ )
1249
+
1250
+ export type PromptInputCommandInputProps = ComponentProps<typeof CommandInput>
1251
+
1252
+ export const PromptInputCommandInput = ({ className, ...props }: PromptInputCommandInputProps) => (
1253
+ <CommandInput className={cn(className)} {...props} />
1254
+ )
1255
+
1256
+ export type PromptInputCommandListProps = ComponentProps<typeof CommandList>
1257
+
1258
+ export const PromptInputCommandList = ({ className, ...props }: PromptInputCommandListProps) => (
1259
+ <CommandList className={cn(className)} {...props} />
1260
+ )
1261
+
1262
+ export type PromptInputCommandEmptyProps = ComponentProps<typeof CommandEmpty>
1263
+
1264
+ export const PromptInputCommandEmpty = ({ className, ...props }: PromptInputCommandEmptyProps) => (
1265
+ <CommandEmpty className={cn(className)} {...props} />
1266
+ )
1267
+
1268
+ export type PromptInputCommandGroupProps = ComponentProps<typeof CommandGroup>
1269
+
1270
+ export const PromptInputCommandGroup = ({ className, ...props }: PromptInputCommandGroupProps) => (
1271
+ <CommandGroup className={cn(className)} {...props} />
1272
+ )
1273
+
1274
+ export type PromptInputCommandItemProps = ComponentProps<typeof CommandItem>
1275
+
1276
+ export const PromptInputCommandItem = ({ className, ...props }: PromptInputCommandItemProps) => (
1277
+ <CommandItem className={cn(className)} {...props} />
1278
+ )
1279
+
1280
+ export type PromptInputCommandSeparatorProps = ComponentProps<typeof CommandSeparator>
1281
+
1282
+ export const PromptInputCommandSeparator = ({
1283
+ className,
1284
+ ...props
1285
+ }: PromptInputCommandSeparatorProps) => <CommandSeparator className={cn(className)} {...props} />