Prompt Input
The composer. A growing textarea, file attachments, a toolbar and a submit button that knows the stream's state.
Installation
Copy and paste the following code into your project.
1'use client';23import * as React from 'react';4import { cn } from '../lib/cn';5import { useControllableState } from '../lib/use-controllable-state';67type IconProps = React.SVGProps<SVGSVGElement> & {8 size?: number | string;9};1011function PaperclipIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {12 return (13 <svg14 xmlns="http://www.w3.org/2000/svg"15 width={size}16 height={size}17 viewBox="0 0 24 24"18 fill="none"19 stroke="currentColor"20 strokeWidth={strokeWidth}21 strokeLinecap="round"22 strokeLinejoin="round"23 aria-hidden="true"24 {...props}25 >26 <path d="M20 11.5 12.5 19a4.5 4.5 0 0 1-6.4-6.4l7.6-7.6a3 3 0 0 1 4.3 4.3l-7.6 7.6a1.5 1.5 0 0 1-2.1-2.1l7-7" />27 </svg>28 );29}3031function SendIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {32 return (33 <svg34 xmlns="http://www.w3.org/2000/svg"35 width={size}36 height={size}37 viewBox="0 0 24 24"38 fill="none"39 stroke="currentColor"40 strokeWidth={strokeWidth}41 strokeLinecap="round"42 strokeLinejoin="round"43 aria-hidden="true"44 {...props}45 >46 <path d="M4 12h15" />47 <path d="m13 6 6 6-6 6" />48 </svg>49 );50}5152function SquareIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {53 return (54 <svg55 xmlns="http://www.w3.org/2000/svg"56 width={size}57 height={size}58 viewBox="0 0 24 24"59 fill="none"60 stroke="currentColor"61 strokeWidth={strokeWidth}62 strokeLinecap="round"63 strokeLinejoin="round"64 aria-hidden="true"65 {...props}66 >67 <rect x="7" y="7" width="10" height="10" rx="2" />68 </svg>69 );70}7172function LoaderIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {73 return (74 <svg75 xmlns="http://www.w3.org/2000/svg"76 width={size}77 height={size}78 viewBox="0 0 24 24"79 fill="none"80 stroke="currentColor"81 strokeWidth={strokeWidth}82 strokeLinecap="round"83 strokeLinejoin="round"84 aria-hidden="true"85 {...props}86 >87 <path d="M12 3a9 9 0 1 0 9 9" />88 </svg>89 );90}9192function AlertIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {93 return (94 <svg95 xmlns="http://www.w3.org/2000/svg"96 width={size}97 height={size}98 viewBox="0 0 24 24"99 fill="none"100 stroke="currentColor"101 strokeWidth={strokeWidth}102 strokeLinecap="round"103 strokeLinejoin="round"104 aria-hidden="true"105 {...props}106 >107 <circle cx="12" cy="12" r="9" />108 <path d="M12 8v4" />109 <path d="M12 16h.01" />110 </svg>111 );112}113114function XIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {115 return (116 <svg117 xmlns="http://www.w3.org/2000/svg"118 width={size}119 height={size}120 viewBox="0 0 24 24"121 fill="none"122 stroke="currentColor"123 strokeWidth={strokeWidth}124 strokeLinecap="round"125 strokeLinejoin="round"126 aria-hidden="true"127 {...props}128 >129 <path d="M18 6 6 18" />130 <path d="m6 6 12 12" />131 </svg>132 );133}134135type PromptInputStatus = 'ready' | 'submitted' | 'streaming' | 'error';136type PromptInputErrorCode = 'max_files' | 'max_file_size' | 'accept';137138interface PromptInputError {139 code: PromptInputErrorCode;140 message: string;141}142143interface PromptInputFile {144 id: string;145 filename: string;146 mediaType: string;147 size: number;148 url: string;149 file: File;150}151152interface PromptInputMessage {153 text: string;154 files: PromptInputFile[];155}156157interface PromptInputContextValue {158 text: string;159 setText: (text: string) => void;160 files: PromptInputFile[];161 add: (files: FileList | File[]) => void;162 remove: (id: string) => void;163 clear: () => void;164 openFileDialog: () => void;165 dragging: boolean;166 accept: string | undefined;167 id: string;168 status: PromptInputStatus | undefined;169 disabled: boolean;170 reportSubmitStatus: (status: PromptInputStatus | undefined) => void;171}172173const PromptInputContext = React.createContext<PromptInputContextValue | null>(null);174175const usePromptInput = (): PromptInputContextValue => {176 const context = React.use(PromptInputContext);177 if (!context) {178 throw new Error('PromptInput components must be used within PromptInput');179 }180 return context;181};182183const usePromptInputAttachments = () => {184 const { files, add, remove, clear, openFileDialog } = usePromptInput();185 return { files, add, remove, clear, openFileDialog };186};187188function matchesAccept(file: File, accept?: string): boolean {189 if (!accept) return true;190 return accept.split(',').some((rule) => {191 const pattern = rule.trim();192 if (!pattern) return false;193 if (pattern.startsWith('.')) return file.name.toLowerCase().endsWith(pattern.toLowerCase());194 if (pattern.endsWith('/*')) return file.type.startsWith(pattern.slice(0, -1));195 return file.type === pattern;196 });197}198199interface PromptInputProps extends Omit<200 React.FormHTMLAttributes<HTMLFormElement>,201 'onSubmit' | 'onError' | 'value' | 'defaultValue'202> {203 onSubmit?: (204 message: PromptInputMessage,205 event: React.FormEvent<HTMLFormElement>,206 ) => void | boolean | Promise<void | boolean>;207 value?: string;208 defaultValue?: string;209 onValueChange?: (value: string) => void;210 accept?: string;211 multiple?: boolean;212 maxFiles?: number;213 maxFileSize?: number;214 globalDrop?: boolean;215 clearOnSubmit?: boolean;216 onError?: (error: PromptInputError) => void;217 status?: PromptInputStatus;218 disabled?: boolean;219}220221type PromptInputHeaderProps = React.HTMLAttributes<HTMLDivElement>;222type PromptInputBodyProps = React.HTMLAttributes<HTMLDivElement>;223type PromptInputFooterProps = React.HTMLAttributes<HTMLDivElement>;224type PromptInputToolsProps = React.HTMLAttributes<HTMLDivElement>;225type PromptInputAttachmentsProps = React.HTMLAttributes<HTMLDivElement>;226227interface PromptInputTextareaProps extends Omit<228 React.TextareaHTMLAttributes<HTMLTextAreaElement>,229 'value' | 'onChange'230> {231 minRows?: number;232 maxRows?: number;233 label?: string;234 submitOnEnter?: boolean;235}236237interface PromptInputButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {238 label?: string;239 variant?: 'ghost' | 'outline';240}241242interface PromptInputAddAttachmentsProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {243 label?: string;244}245246interface PromptInputSubmitProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {247 status?: PromptInputStatus;248 label?: string;249 stopLabel?: string;250 onStop?: () => void;251}252253const PromptInputRoot = ({254 className,255 onSubmit,256 accept,257 multiple = false,258 maxFiles,259 maxFileSize,260 globalDrop = false,261 clearOnSubmit = true,262 onError,263 value: controlledText,264 defaultValue = '',265 onValueChange,266 status,267 disabled = false,268 children,269 ref,270 ...props271}: PromptInputProps & { ref?: React.Ref<HTMLFormElement> }) => {272 const [text, setText] = useControllableState({273 value: controlledText,274 defaultValue,275 onChange: onValueChange,276 });277 const [files, setFiles] = React.useState<PromptInputFile[]>([]);278 const filesRef = React.useRef<PromptInputFile[]>(files);279 const [dragging, setDragging] = React.useState(false);280 const inputRef = React.useRef<HTMLInputElement>(null);281 const id = React.useId();282 const counterRef = React.useRef(0);283 const handedOffRef = React.useRef(new Set<string>());284 const submitStatusRef = React.useRef<PromptInputStatus | undefined>(undefined);285286 const release = React.useCallback((entry: PromptInputFile) => {287 if (handedOffRef.current.has(entry.url)) return;288 URL.revokeObjectURL(entry.url);289 }, []);290291 const reportSubmitStatus = React.useCallback((next: PromptInputStatus | undefined) => {292 submitStatusRef.current = next;293 }, []);294295 const add = React.useCallback(296 (incoming: FileList | File[]) => {297 const next = [...filesRef.current];298299 for (const file of Array.from(incoming)) {300 if (!matchesAccept(file, accept)) {301 onError?.({ code: 'accept', message: `${file.name} is not an accepted file type.` });302 continue;303 }304 if (maxFileSize !== undefined && file.size > maxFileSize) {305 onError?.({ code: 'max_file_size', message: `${file.name} is too large.` });306 continue;307 }308 if (maxFiles !== undefined && next.length >= maxFiles) {309 onError?.({ code: 'max_files', message: `You can attach up to ${maxFiles} files.` });310 break;311 }312313 counterRef.current += 1;314 next.push({315 id: `${file.name}-${file.size}-${file.lastModified}-${counterRef.current}`,316 filename: file.name,317 mediaType: file.type,318 size: file.size,319 url: URL.createObjectURL(file),320 file,321 });322323 if (!multiple) break;324 }325326 const accepted = multiple ? next : next.slice(-1);327 for (const entry of next) {328 if (!accepted.includes(entry)) release(entry);329 }330331 filesRef.current = accepted;332 setFiles(accepted);333 },334 [accept, maxFileSize, maxFiles, multiple, onError, release],335 );336337 const remove = React.useCallback(338 (fileId: string) => {339 const target = filesRef.current.find((entry) => entry.id === fileId);340 if (target) release(target);341 filesRef.current = filesRef.current.filter((entry) => entry.id !== fileId);342 setFiles(filesRef.current);343 },344 [release],345 );346347 const clear = React.useCallback(() => {348 for (const entry of filesRef.current) release(entry);349 filesRef.current = [];350 setFiles(filesRef.current);351 }, [release]);352353 React.useEffect(354 () => () => {355 for (const entry of filesRef.current) release(entry);356 },357 [release],358 );359360 const openFileDialog = React.useCallback(() => {361 inputRef.current?.click();362 }, []);363364 React.useEffect(() => {365 if (!globalDrop) return;366367 const onWindowDrop = (event: DragEvent) => {368 if (!event.dataTransfer?.files.length) return;369 event.preventDefault();370 add(event.dataTransfer.files);371 setDragging(false);372 };373 const onWindowDragOver = (event: DragEvent) => event.preventDefault();374375 window.addEventListener('drop', onWindowDrop);376 window.addEventListener('dragover', onWindowDragOver);377 return () => {378 window.removeEventListener('drop', onWindowDrop);379 window.removeEventListener('dragover', onWindowDragOver);380 };381 }, [add, globalDrop]);382383 const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {384 event.preventDefault();385 const current = status ?? submitStatusRef.current;386 if (disabled || current === 'streaming' || current === 'submitted') return;387 if (!text.trim() && files.length === 0) return;388 const submitted = files;389 for (const entry of submitted) handedOffRef.current.add(entry.url);390 const result = onSubmit?.({ text, files: submitted }, event);391 if (!clearOnSubmit) return;392 const reset = (outcome: void | boolean) => {393 if (outcome === false) return;394 setText('');395 filesRef.current = filesRef.current.filter((entry) => !submitted.includes(entry));396 setFiles(filesRef.current);397 };398 if (result instanceof Promise) {399 result.then(reset, () => undefined);400 } else {401 reset(result);402 }403 };404405 const value = React.useMemo<PromptInputContextValue>(406 () => ({407 text,408 setText,409 files,410 add,411 remove,412 clear,413 openFileDialog,414 dragging,415 accept,416 id,417 status,418 disabled,419 reportSubmitStatus,420 }),421 [422 text,423 setText,424 files,425 add,426 remove,427 clear,428 openFileDialog,429 dragging,430 accept,431 id,432 status,433 disabled,434 reportSubmitStatus,435 ],436 );437438 return (439 <PromptInputContext value={value}>440 <form441 ref={ref}442 onSubmit={handleSubmit}443 data-dragging={dragging ? '' : undefined}444 onDragOver={(event) => {445 event.preventDefault();446 setDragging(true);447 }}448 onDragLeave={(event) => {449 if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;450 setDragging(false);451 }}452 onDrop={(event) => {453 event.preventDefault();454 setDragging(false);455 if (event.dataTransfer.files.length > 0) add(event.dataTransfer.files);456 }}457 className={cn(458 'bg-card focus-within:ring-ring flex w-full flex-col rounded-xl shadow-sm transition-shadow focus-within:ring-2',459 dragging && 'ring-ring bg-muted/40 ring-2',460 className,461 )}462 {...props}463 >464 <input465 ref={inputRef}466 type="file"467 accept={accept}468 multiple={multiple}469 tabIndex={-1}470 hidden471 onChange={(event) => {472 if (event.target.files) add(event.target.files);473 event.target.value = '';474 }}475 />476 {children}477 </form>478 </PromptInputContext>479 );480};481482PromptInputRoot.displayName = 'PromptInput';483484const PromptInputHeader = ({485 className,486 ref,487 ...props488}: PromptInputHeaderProps & { ref?: React.Ref<HTMLDivElement> }) => {489 return <div ref={ref} className={cn('flex flex-col gap-2 px-3 pt-3', className)} {...props} />;490};491492PromptInputHeader.displayName = 'PromptInputHeader';493494const PromptInputBody = ({495 className,496 ref,497 ...props498}: PromptInputBodyProps & { ref?: React.Ref<HTMLDivElement> }) => {499 return <div ref={ref} className={cn('flex w-full min-w-0 flex-col', className)} {...props} />;500};501502PromptInputBody.displayName = 'PromptInputBody';503504const PromptInputFooter = ({505 className,506 ref,507 ...props508}: PromptInputFooterProps & { ref?: React.Ref<HTMLDivElement> }) => {509 return (510 <div511 ref={ref}512 className={cn('flex items-center justify-between gap-2 px-2 pt-1 pb-2', className)}513 {...props}514 />515 );516};517518PromptInputFooter.displayName = 'PromptInputFooter';519520const PromptInputTools = ({521 className,522 ref,523 ...props524}: PromptInputToolsProps & { ref?: React.Ref<HTMLDivElement> }) => {525 return <div ref={ref} className={cn('flex items-center gap-1', className)} {...props} />;526};527528PromptInputTools.displayName = 'PromptInputTools';529530const PromptInputAttachments = ({531 className,532 children,533 ref,534 ...props535}: PromptInputAttachmentsProps & { ref?: React.Ref<HTMLDivElement> }) => {536 const { files, remove, id } = usePromptInput();537 const listRef = React.useRef<HTMLDivElement | null>(null);538539 const setRefs = React.useCallback(540 (node: HTMLDivElement | null) => {541 listRef.current = node;542 if (typeof ref === 'function') ref(node);543 else if (ref) ref.current = node;544 },545 [ref],546 );547548 const removeAndRefocus = (fileId: string, index: number) => {549 const buttons = Array.from(550 listRef.current?.querySelectorAll<HTMLButtonElement>('[data-prompt-input-remove]') ?? [],551 );552 const next = buttons[index + 1] ?? buttons[index - 1];553 remove(fileId);554 if (next) next.focus();555 else document.getElementById(`${id}-textarea`)?.focus();556 };557558 if (files.length === 0) return null;559560 return (561 <div ref={setRefs} className={cn('flex flex-wrap items-center gap-2', className)} {...props}>562 {children ??563 files.map((file, index) => (564 <span565 key={file.id}566 className="bg-secondary text-secondary-foreground flex h-8 max-w-48 items-center gap-1.5 rounded-full py-1 ps-2.5 pe-1 text-xs"567 >568 <span className="truncate">{file.filename}</span>569 <button570 type="button"571 aria-label={`Remove ${file.filename}`}572 data-prompt-input-remove=""573 onClick={() => removeAndRefocus(file.id, index)}574 className="text-muted-foreground hover:text-foreground focus-visible:ring-ring relative flex size-5 shrink-0 items-center justify-center rounded-full transition-colors after:absolute after:-inset-2 focus-visible:ring-2 focus-visible:outline-none"575 >576 <XIcon size={12} />577 </button>578 </span>579 ))}580 </div>581 );582};583584PromptInputAttachments.displayName = 'PromptInputAttachments';585586const PromptInputTextarea = ({587 className,588 minRows = 1,589 maxRows = 8,590 label = 'Message',591 submitOnEnter,592 disabled,593 onKeyDown,594 ref,595 ...props596}: PromptInputTextareaProps & { ref?: React.Ref<HTMLTextAreaElement> }) => {597 const { text, setText, id, disabled: rootDisabled } = usePromptInput();598 const innerRef = React.useRef<HTMLTextAreaElement>(null);599600 React.useImperativeHandle(ref, () => innerRef.current as HTMLTextAreaElement);601602 const resize = React.useCallback(() => {603 const node = innerRef.current;604 if (!node) return;605 node.style.height = 'auto';606 const style = getComputedStyle(node);607 const lineHeight = Number.parseFloat(style.lineHeight) || 20;608 const paddingY =609 (Number.parseFloat(style.paddingTop) || 0) + (Number.parseFloat(style.paddingBottom) || 0);610 const borderY =611 (Number.parseFloat(style.borderTopWidth) || 0) +612 (Number.parseFloat(style.borderBottomWidth) || 0);613 const limit = lineHeight * maxRows + paddingY;614 node.style.height = `${Math.min(node.scrollHeight, limit) + borderY}px`;615 }, [maxRows]);616617 React.useLayoutEffect(() => {618 resize();619 }, [text, resize]);620621 React.useEffect(() => {622 const node = innerRef.current;623 if (!node || typeof ResizeObserver === 'undefined') return;624 let width = node.clientWidth;625 const observer = new ResizeObserver(() => {626 if (node.clientWidth === width) return;627 width = node.clientWidth;628 resize();629 });630 observer.observe(node);631 return () => observer.disconnect();632 }, [resize]);633634 const shouldSubmitOnEnter = () => {635 if (submitOnEnter !== undefined) return submitOnEnter;636 if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return true;637 return !window.matchMedia('(pointer: coarse)').matches;638 };639640 return (641 <textarea642 ref={innerRef}643 id={`${id}-textarea`}644 rows={minRows}645 value={text}646 aria-label={label}647 enterKeyHint={submitOnEnter ? 'send' : undefined}648 disabled={disabled ?? (rootDisabled || undefined)}649 onChange={(event) => setText(event.target.value)}650 onKeyDown={(event) => {651 onKeyDown?.(event);652 if (event.defaultPrevented) return;653 if (event.key !== 'Enter' || event.shiftKey) return;654 if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return;655 if (!shouldSubmitOnEnter()) return;656 event.preventDefault();657 event.currentTarget.form?.requestSubmit();658 }}659 className={cn(660 'text-foreground placeholder:text-muted-foreground w-full resize-none bg-transparent px-3 py-3 text-base leading-relaxed outline-none md:text-sm',661 className,662 )}663 {...props}664 />665 );666};667668PromptInputTextarea.displayName = 'PromptInputTextarea';669670const PromptInputButton = ({671 className,672 label,673 variant = 'ghost',674 children,675 ref,676 ...props677}: PromptInputButtonProps & { ref?: React.Ref<HTMLButtonElement> }) => {678 return (679 <button680 ref={ref}681 type="button"682 aria-label={label}683 title={label}684 className={cn(685 'text-muted-foreground hover:text-foreground focus-visible:ring-ring inline-flex h-8 items-center justify-center gap-1.5 rounded-full px-2 text-xs transition-colors focus-visible:ring-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-40 [&>svg]:size-4 [&>svg]:shrink-0',686 variant === 'ghost' && 'hover:bg-muted',687 variant === 'outline' && 'hover:bg-muted',688 className,689 )}690 {...props}691 >692 {children}693 </button>694 );695};696697PromptInputButton.displayName = 'PromptInputButton';698699const PromptInputAddAttachments = ({700 className,701 label = 'Add files',702 children,703 onClick,704 ref,705 ...props706}: PromptInputAddAttachmentsProps & { ref?: React.Ref<HTMLButtonElement> }) => {707 const { openFileDialog } = usePromptInput();708709 return (710 <PromptInputButton711 ref={ref}712 label={label}713 className={className}714 onClick={(event) => {715 openFileDialog();716 onClick?.(event);717 }}718 {...props}719 >720 {children ?? <PaperclipIcon />}721 </PromptInputButton>722 );723};724725PromptInputAddAttachments.displayName = 'PromptInputAddAttachments';726727const PromptInputSubmit = ({728 className,729 status: statusProp,730 label,731 stopLabel,732 onStop,733 children,734 disabled,735 onClick,736 ref,737 ...props738}: PromptInputSubmitProps & { ref?: React.Ref<HTMLButtonElement> }) => {739 const {740 text,741 files,742 status: rootStatus,743 disabled: rootDisabled,744 reportSubmitStatus,745 } = usePromptInput();746 const status = statusProp ?? rootStatus ?? 'ready';747 const empty = text.trim().length === 0 && files.length === 0;748 const busy = status === 'streaming' || status === 'submitted';749 const name = busy ? (stopLabel ?? label ?? 'Stop generating') : (label ?? 'Send message');750751 React.useEffect(() => {752 reportSubmitStatus(statusProp);753 return () => reportSubmitStatus(undefined);754 }, [statusProp, reportSubmitStatus]);755756 const icon = () => {757 if (status === 'streaming') return <SquareIcon />;758 if (status === 'error') return <AlertIcon />;759 if (status === 'submitted') return <LoaderIcon className="motion-safe:animate-spin" />;760 return <SendIcon />;761 };762763 const defaultDisabled = busy764 ? !onStop && !onClick765 : rootDisabled || (status === 'ready' && empty);766767 return (768 <button769 ref={ref}770 type={busy ? 'button' : 'submit'}771 aria-label={name}772 title={name}773 data-status={status}774 disabled={disabled ?? defaultDisabled}775 onClick={(event) => {776 onClick?.(event);777 if (busy && !event.defaultPrevented) onStop?.();778 }}779 className={cn(780 'bg-primary text-primary-foreground hover:bg-primary/90 focus-visible:ring-ring inline-flex size-8 shrink-0 items-center justify-center rounded-full transition-colors focus-visible:ring-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-40 [&>svg]:size-4 [&>svg]:shrink-0',781 status === 'error' && 'bg-destructive text-destructive-foreground hover:bg-destructive/90',782 className,783 )}784 {...props}785 >786 {children ?? icon()}787 </button>788 );789};790791PromptInputSubmit.displayName = 'PromptInputSubmit';792793const PromptInput = Object.assign(PromptInputRoot, {794 Header: PromptInputHeader,795 Body: PromptInputBody,796 Footer: PromptInputFooter,797 Tools: PromptInputTools,798 Attachments: PromptInputAttachments,799 Textarea: PromptInputTextarea,800 Button: PromptInputButton,801 AddAttachments: PromptInputAddAttachments,802 Submit: PromptInputSubmit,803});804805export { PromptInput, usePromptInput, usePromptInputAttachments };806export type {807 PromptInputAddAttachmentsProps,808 PromptInputAttachmentsProps,809 PromptInputBodyProps,810 PromptInputButtonProps,811 PromptInputError,812 PromptInputErrorCode,813 PromptInputFile,814 PromptInputFooterProps,815 PromptInputHeaderProps,816 PromptInputMessage,817 PromptInputProps,818 PromptInputStatus,819 PromptInputSubmitProps,820 PromptInputTextareaProps,821 PromptInputToolsProps,822};
Update the import paths to match your project structure.
Anatomy
1import { PromptInput } from '@/ai/prompt-input';
1<PromptInput onSubmit={(message) => sendMessage(message.text, message.files)}>2 <PromptInput.Header>3 <PromptInput.Attachments />4 </PromptInput.Header>5 <PromptInput.Body>6 <PromptInput.Textarea placeholder="Ask anythingโฆ" />7 </PromptInput.Body>8 <PromptInput.Footer>9 <PromptInput.Tools>10 <PromptInput.AddAttachments />11 </PromptInput.Tools>12 <PromptInput.Submit status={status} />13 </PromptInput.Footer>14</PromptInput>
The root is a real
form. Submitting calls onSubmit with { text, files } and then clears itself, which you can turn off with clearOnSubmit={false} if your app owns the reset.Composition
Use the following composition to build a
PromptInput:PromptInputโโโ PromptInput.Headerโ โโโ PromptInput.Attachmentsโโโ PromptInput.Bodyโ โโโ PromptInput.Textareaโโโ PromptInput.Footerโโโ PromptInput.Toolsโ โโโ PromptInput.AddAttachmentsโ โโโ PromptInput.Buttonโโโ PromptInput.Submit
Keyboard
Enter sends, Shift and Enter make a newline, and composition input from an IME is left alone so an unconfirmed candidate never gets submitted by accident. The textarea grows with the text up to
maxRows and then scrolls.On touch screens Enter adds a newline instead, since the on-screen keyboard has no easy Shift and people send with the button. Set
submitOnEnter on the textarea to force either behavior; with true the keyboard also shows a send key. Enter never sends while the prompt is disabled or the status is submitted or streaming.The textarea is named "Message" for screen readers. Pass
label to change it, for example to translate it.Files
Files arrive three ways: the clip button, a drop anywhere on the composer, and a drop anywhere on the page when
globalDrop is set. accept, maxFiles and maxFileSize are checked before a file is kept, and anything rejected goes to onError with a code you can show.1'use client';23import { PromptInput } from '@/ai/prompt-input';45export function Attachments() {6 return (7 <div className="w-full max-w-lg">8 <PromptInput accept="image/*,.pdf,.md" multiple maxFiles={4} globalDrop>9 <PromptInput.Header>10 <PromptInput.Attachments />11 </PromptInput.Header>12 <PromptInput.Body>13 <PromptInput.Textarea placeholder="Drop a file anywhere, or use the clipโฆ" />14 </PromptInput.Body>15 <PromptInput.Footer>16 <PromptInput.Tools>17 <PromptInput.AddAttachments />18 <PromptInput.Button label="Model">gpt-5</PromptInput.Button>19 </PromptInput.Tools>20 <PromptInput.Submit />21 </PromptInput.Footer>22 </PromptInput>23 </div>24 );25}
Each accepted file becomes a
PromptInputFile with an object URL ready to preview and the original File for upload. Once a file goes out through onSubmit its URL belongs to you, so it keeps working in the sent message; call URL.revokeObjectURL when you are done with it. Files removed before sending, or still in the input when it unmounts, are cleaned up for you.1interface PromptInputFile {2 id: string;3 filename: string;4 mediaType: string;5 size: number;6 url: string;7 file: File;8}
usePromptInputAttachments() exposes files, add, remove, clear and openFileDialog, which is how you build your own strip with Attachments instead of the built-in chips.Status
status on the submit button covers the full round trip: ready sends, submitted spins, streaming turns into a stop square and error goes destructive. While it is submitted or streaming the button stops being a submit button: it reads "Stop generating" and calls onStop.1<PromptInput.Submit status={status} onStop={stop} />
You can also set
status and disabled on the root, which every part reads.1'use client';23import { useState } from 'react';4import { PromptInput, type PromptInputStatus } from '@/ai/prompt-input';56const STATUSES: PromptInputStatus[] = ['ready', 'submitted', 'streaming', 'error'];78export function Statuses() {9 const [status, setStatus] = useState<PromptInputStatus>('ready');1011 return (12 <div className="flex w-full max-w-lg flex-col gap-3">13 <div className="flex flex-wrap gap-2">14 {STATUSES.map((value) => (15 <button16 key={value}17 type="button"18 onClick={() => setStatus(value)}19 data-active={status === value ? '' : undefined}20 className="bg-card hover:bg-muted data-active:bg-muted rounded-full px-3 py-1 text-xs shadow-sm transition-colors"21 >22 {value}23 </button>24 ))}25 </div>26 <PromptInput>27 <PromptInput.Body>28 <PromptInput.Textarea placeholder="The submit button reflects the statusโฆ" />29 </PromptInput.Body>30 <PromptInput.Footer>31 <PromptInput.Tools>32 <PromptInput.AddAttachments />33 </PromptInput.Tools>34 <PromptInput.Submit status={status} onStop={() => setStatus('ready')} />35 </PromptInput.Footer>36 </PromptInput>37 </div>38 );39}
API Reference
PromptInput
| Prop | Type | Default | Description |
|---|---|---|---|
onSubmit | (message: PromptInputMessage, event: FormEvent) => void | - | Called with the text and the files |
accept | string | - | File types to accept |
multiple | boolean | false | Allow more than one file |
maxFiles | number | - | Cap on attached files |
maxFileSize | number | - | Cap in bytes per file |
globalDrop | boolean | false | Accept a drop anywhere on the page |
clearOnSubmit | boolean | true | Reset the text and the files after submit |
onError | (error: { code, message }) => void | - | Called when a file is rejected |
status | 'ready' | 'submitted' | 'streaming' | 'error' | - | Status shared with the submit button, blocks sending while busy |
disabled | boolean | false | Disables the textarea and the submit button |
className | string | - | Additional CSS classes |
PromptInput.Textarea
| Prop | Type | Default | Description |
|---|---|---|---|
minRows | number | 1 | Rows before it grows |
maxRows | number | 8 | Rows before it scrolls |
label | string | 'Message' | Accessible name |
submitOnEnter | boolean | true with a mouse, false on touch | Whether Enter sends |
className | string | - | Additional CSS classes |
PromptInput.Submit
| Prop | Type | Default | Description |
|---|---|---|---|
status | 'ready' | 'submitted' | 'streaming' | 'error' | 'ready' | Icon, colour and disabling |
label | string | 'Send message' | Accessible name |
stopLabel | string | 'Stop generating' | Accessible name while busy, falls back to label when you pass one |
onStop | () => void | - | Called when the stop button is pressed |
className | string | - | Additional CSS classes |
PromptInput.Button
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | - | Accessible name and title |
variant | 'ghost' | 'outline' | 'ghost' | Visual treatment |
className | string | - | Additional CSS classes |
PromptInput.AddAttachments
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | 'Add files' | Accessible name |
className | string | - | Additional CSS classes |
PromptInput.Header / .Body / .Footer / .Tools / .Attachments
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional CSS classes |
Found something to improve?
Notice a bug, typo, or missing detail on this page? Help us make the documentation better by opening a GitHub issue.