@anthusai/papyrus 0.0.0 → 1.0.0-next.10

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