# Animated Prompt Composer for UI SDK (/docs/components/prompt-composer)

The input box of an AI chat. It grows with the message, takes files by the paperclip, a drop or a paste, opens orders, people or commands at the caret after @ and /, and its Send key turns into a spinner and then Stop while the reply comes in.

<ComponentPreview slug="prompt-composer" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport { AtSign, ListChecks, Package, PenLine, RotateCcw, Truck, UserRound } from \&#x22;lucide-react\&#x22;\nimport * as React from \&#x22;react\&#x22;\n\nimport { Button } from \&#x22;@/components/keyframery/button\&#x22;\nimport {\n  createPromptComposerMenuController,\n  PromptComposer,\n  type PromptComposerItem,\n  type PromptComposerStatus,\n  type PromptComposerSubmit,\n} from \&#x22;@/components/keyframery/prompt-composer\&#x22;\nimport { Tooltip, TooltipContent, TooltipTrigger } from \&#x22;@/components/keyframery/tooltip\&#x22;\n\nconst icon = (Glyph: typeof Package) => <Glyph strokeWidth={1.75} />\n\nconst mentions: PromptComposerItem[] = [\n  { value: \&#x22;4821\&#x22;, label: \&#x22;Order #4821\&#x22;, description: \&#x22;Shipped\&#x22;, group: \&#x22;Orders\&#x22;, icon: icon(Package), keywords: [\&#x22;4821\&#x22;, \&#x22;amara\&#x22;] },\n  { value: \&#x22;4819\&#x22;, label: \&#x22;Order #4819\&#x22;, description: \&#x22;Packing\&#x22;, group: \&#x22;Orders\&#x22;, icon: icon(Package), keywords: [\&#x22;4819\&#x22;, \&#x22;theo\&#x22;] },\n  { value: \&#x22;4807\&#x22;, label: \&#x22;Order #4807\&#x22;, description: \&#x22;Refunded\&#x22;, group: \&#x22;Orders\&#x22;, icon: icon(Package), keywords: [\&#x22;4807\&#x22;] },\n  { value: \&#x22;amara\&#x22;, label: \&#x22;Amara Okafor\&#x22;, description: \&#x22;3 orders\&#x22;, group: \&#x22;Customers\&#x22;, icon: icon(UserRound) },\n  { value: \&#x22;theo\&#x22;, label: \&#x22;Theo Lindqvist\&#x22;, description: \&#x22;1 order\&#x22;, group: \&#x22;Customers\&#x22;, icon: icon(UserRound) },\n]\n\nconst commands: PromptComposerItem[] = [\n  { value: \&#x22;track\&#x22;, label: \&#x22;track\&#x22;, description: \&#x22;Where a parcel is\&#x22;, icon: icon(Truck) },\n  { value: \&#x22;refund\&#x22;, label: \&#x22;refund\&#x22;, description: \&#x22;Start a refund\&#x22;, icon: icon(RotateCcw) },\n  { value: \&#x22;summarize\&#x22;, label: \&#x22;summarize\&#x22;, description: \&#x22;Today's orders\&#x22;, icon: icon(ListChecks) },\n  { value: \&#x22;draft-reply\&#x22;, label: \&#x22;draft-reply\&#x22;, description: \&#x22;Write to a customer\&#x22;, icon: icon(PenLine) },\n]\n\nconst modelList = [\n  { value: \&#x22;fast\&#x22;, label: \&#x22;Fast\&#x22;, description: \&#x22;Quick lookups and short answers\&#x22; },\n  { value: \&#x22;balanced\&#x22;, label: \&#x22;Balanced\&#x22;, description: \&#x22;Everyday questions about orders\&#x22; },\n  { value: \&#x22;deep\&#x22;, label: \&#x22;Thorough\&#x22;, description: \&#x22;Slower; checks every order it names\&#x22; },\n]\n\n/* Stands in for the store's upload: a file goes up in a few steps, at the demo's speed. */\nfunction fakeUpload(_file: File, { onProgress, signal }: { onProgress: (percent: number) => void; signal: AbortSignal }) {\n  const speed = parseFloat(getComputedStyle(document.documentElement).getPropertyValue(\&#x22;--kf-speed\&#x22;)) || 1\n  return new Promise<void>((resolve, reject) => {\n    const steps = [22, 48, 71, 100]\n    const timers = steps.map((p, i) =>\n      setTimeout(() => {\n        onProgress(p)\n        if (p === 100) resolve()\n      }, (250 + i * 260) * speed),\n    )\n    signal.addEventListener(\&#x22;abort\&#x22;, () => {\n      timers.forEach(clearTimeout)\n      reject(signal.reason)\n    })\n  })\n}\n\ntype Turn = { id: number; from: \&#x22;you\&#x22; | \&#x22;assistant\&#x22;; text: string; files?: { name: string; url?: string }[]; stopped?: boolean }\n\nconst opening: Turn[] = [\n  { id: 1, from: \&#x22;you\&#x22;, text: \&#x22;/summarize today\&#x22; },\n  { id: 2, from: \&#x22;assistant\&#x22;, text: \&#x22;38 orders today, £2,914 in sales. Three are waiting on stock, and #4807 was refunded this morning.\&#x22; },\n]\n\nconst answer =\n  \&#x22;That's the stoneware mug from Order #4821, delivered on Tuesday, so it's inside the 30-day window. I can send a replacement today with next-day delivery, or refund £18 to Amara's card. Which would you like?\&#x22;\n\nexport default function PromptComposerDemo({\n  submitOn = \&#x22;enter\&#x22;,\n  counter = \&#x22;tokens\&#x22;,\n  models = true,\n  attachments = true,\n  disabled = false,\n  placeholder = \&#x22;Ask about an order, or type @ or /\&#x22;,\n  maxRows = 6,\n  themeFace = \&#x22;\&#x22;,\n  themeInk = \&#x22;\&#x22;,\n  themeSend = \&#x22;\&#x22;,\n  themeRadius = 18,\n  themeFont = 14,\n  themePadding = 8,\n}: {\n  submitOn?: \&#x22;enter\&#x22; | \&#x22;mod+enter\&#x22;\n  counter?: \&#x22;characters\&#x22; | \&#x22;tokens\&#x22; | \&#x22;none\&#x22;\n  models?: boolean\n  attachments?: boolean\n  disabled?: boolean\n  placeholder?: string\n  maxRows?: number\n  themeFace?: string\n  themeInk?: string\n  themeSend?: string\n  themeRadius?: number\n  themeFont?: number\n  themePadding?: number\n}) {\n  const [turns, setTurns] = React.useState(opening)\n  const [status, setStatus] = React.useState<PromptComposerStatus>(\&#x22;ready\&#x22;)\n  const [text, setText] = React.useState(\&#x22;\&#x22;)\n  const [run, setRun] = React.useState(0)\n  const menu = React.useMemo(() => createPromptComposerMenuController(), [])\n  const root = React.useRef<HTMLDivElement>(null)\n  const timers = React.useRef<ReturnType<typeof setTimeout>[]>([])\n  const clear = () => {\n    timers.current.forEach(clearTimeout)\n    timers.current = []\n  }\n  React.useEffect(() => clear, [])\n\n  const speed = () => (root.current && parseFloat(getComputedStyle(root.current).getPropertyValue(\&#x22;--kf-speed\&#x22;))) || 1\n\n  /* Sent: a moment of waiting, then the answer streams in a few words at a time. */\n  const submit = (message: PromptComposerSubmit) => {\n    clear()\n    const s = speed()\n    const reply = Date.now()\n    setTurns((all) => [...all.slice(-2), { id: reply - 1, from: \&#x22;you\&#x22;, text: message.text, files: message.attachments.map((f) => ({ name: f.name, url: f.type.startsWith(\&#x22;image/\&#x22;) ? URL.createObjectURL(f) : undefined })) }])\n    setStatus(\&#x22;submitted\&#x22;)\n    const words = answer.split(\&#x22; \&#x22;)\n    timers.current.push(\n      setTimeout(() => {\n        setStatus(\&#x22;streaming\&#x22;)\n        setTurns((all) => [...all, { id: reply, from: \&#x22;assistant\&#x22;, text: \&#x22;\&#x22; }])\n        words.forEach((_, i) => {\n          timers.current.push(\n            setTimeout(() => {\n              setTurns((all) => all.map((t) => (t.id === reply ? { ...t, text: words.slice(0, i + 1).join(\&#x22; \&#x22;) } : t)))\n              if (i === words.length - 1) setStatus(\&#x22;ready\&#x22;)\n            }, i * 85 * s),\n          )\n        })\n      }, 900 * s),\n    )\n  }\n\n  const stop = () => {\n    clear()\n    setStatus(\&#x22;ready\&#x22;)\n    setTurns((all) => all.map((t, i) => (i === all.length - 1 && t.from === \&#x22;assistant\&#x22; ? { ...t, stopped: true } : t)))\n  }\n\n  /* For the self-playing loop: drop the customer's photo on the box, and start over. */\n  const dropSlip = async () => {\n    const box = root.current?.querySelector('[data-composer-part=\&#x22;box\&#x22;]')\n    if (!box) return\n    const blob = await fetch(\&#x22;/demo/cup.jpg\&#x22;).then((r) => r.blob())\n    const transfer = new DataTransfer()\n    transfer.items.add(new File([blob], \&#x22;chipped-mug.jpg\&#x22;, { type: \&#x22;image/jpeg\&#x22; }))\n    for (const type of [\&#x22;dragenter\&#x22;, \&#x22;dragover\&#x22;, \&#x22;drop\&#x22;]) box.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer: transfer }))\n  }\n  const reset = () => {\n    clear()\n    setStatus(\&#x22;ready\&#x22;)\n    setText(\&#x22;\&#x22;)\n    setTurns(opening)\n    setRun((r) => r + 1)\n  }\n\n  /* Leave defaults unset so each part keeps its own theme and size fallback. */\n  const theme = {\n    ...(themeFace ? { \&#x22;--prompt-composer-face\&#x22;: themeFace } : null),\n    ...(themeInk ? { \&#x22;--prompt-composer-ink\&#x22;: themeInk } : null),\n    ...(themeSend ? { \&#x22;--prompt-composer-send\&#x22;: themeSend } : null),\n    ...(themeRadius !== 18 ? { \&#x22;--prompt-composer-radius\&#x22;: `${themeRadius}px` } : null),\n    ...(themeFont !== 14 ? { \&#x22;--prompt-composer-font\&#x22;: `${themeFont}px` } : null),\n    ...(themePadding !== 8 ? { \&#x22;--prompt-composer-padding\&#x22;: `${themePadding}px` } : null),\n  } as React.CSSProperties\n\n  return (\n    <div ref={root} style={theme} className=\&#x22;@container flex w-full max-w-[540px] flex-col\&#x22;>\n      <div className=\&#x22;flex h-[210px] flex-col justify-end gap-3.5 overflow-hidden pb-4 [mask-image:linear-gradient(to_bottom,transparent,black_44px)]\&#x22;>\n        {turns.map((turn) =>\n          turn.from === \&#x22;you\&#x22; ? (\n            <div key={turn.id} className=\&#x22;flex flex-col items-end gap-1.5\&#x22;>\n              {turn.files?.map((file) =>\n                file.url ? (\n                  <img key={file.name} src={file.url} alt={file.name} className=\&#x22;size-16 rounded-[12px] object-cover shadow-[inset_0_0_0_1px_rgb(0_0_0/0.06)]\&#x22; />\n                ) : (\n                  <span key={file.name} className=\&#x22;rounded-[10px] bg-muted px-2.5 py-1.5 text-[12px] text-muted-foreground\&#x22;>\n                    {file.name}\n                  </span>\n                ),\n              )}\n              <div className=\&#x22;max-w-[85%] rounded-[16px] rounded-br-[6px] bg-muted px-3.5 py-2.5 text-[13.5px] leading-snug whitespace-pre-wrap\&#x22;>{turn.text}</div>\n            </div>\n          ) : (\n            <p key={turn.id} className=\&#x22;max-w-[92%] text-[13.5px] leading-relaxed text-foreground/90\&#x22;>\n              {turn.text}\n              {turn.stopped && <span className=\&#x22;ms-1.5 text-[12px] text-muted-foreground\&#x22;>Stopped</span>}\n            </p>\n          ),\n        )}\n      </div>\n\n      <PromptComposer\n        key={run}\n        value={text}\n        onValueChange={setText}\n        status={status}\n        onSubmit={submit}\n        onStop={stop}\n        placeholder={placeholder}\n        submitOn={submitOn}\n        counter={counter}\n        maxRows={maxRows}\n        disabled={disabled}\n        accept={attachments ? \&#x22;image/*,.pdf,.csv\&#x22; : false}\n        upload={fakeUpload}\n        models={models ? modelList : undefined}\n        defaultModel=\&#x22;balanced\&#x22;\n        mentions={mentions}\n        commands={commands}\n        menuController={menu}\n        actions={\n          <Tooltip>\n            <TooltipTrigger\n              render={<Button variant=\&#x22;ghost\&#x22; size=\&#x22;icon\&#x22; className=\&#x22;bg-none text-muted-foreground shadow-none hover:text-foreground dark:bg-none dark:shadow-none\&#x22; />}\n              aria-label=\&#x22;Mention an order or customer\&#x22;\n              data-play=\&#x22;mention\&#x22;\n              disabled={disabled}\n              onClick={() => void menu.open({ trigger: \&#x22;@\&#x22; })}\n            >\n              <AtSign strokeWidth={1.75} />\n            </TooltipTrigger>\n            <TooltipContent>Mention an order or customer</TooltipContent>\n          </Tooltip>\n        }\n      />\n\n      <button type=\&#x22;button\&#x22; hidden data-agent-hidden data-play=\&#x22;drop\&#x22; onClick={() => void dropSlip()} />\n      <button type=\&#x22;button\&#x22; hidden data-agent-hidden data-play=\&#x22;reset\&#x22; onClick={reset} />\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;submitOn&#x22;:[3277,3284],&#x22;counter&#x22;:[3298,3306],&#x22;models&#x22;:[3319,3323],&#x22;attachments&#x22;:[3341,3345],&#x22;disabled&#x22;:[3360,3365],&#x22;placeholder&#x22;:[3383,3419],&#x22;maxRows&#x22;:[3433,3434],&#x22;themeFace&#x22;:[3450,3452],&#x22;themeInk&#x22;:[3467,3469],&#x22;themeSend&#x22;:[3485,3487],&#x22;themeRadius&#x22;:[3505,3507],&#x22;themeFont&#x22;:[3523,3525],&#x22;themePadding&#x22;:[3544,3545]},&#x22;root&#x22;:[7024,9764],&#x22;importOffset&#x22;:487}" />

## Installation [#installation]

**React**

**CLI**

```bash
npx shadcn@latest add @keyframery/prompt-composer
```

This adds `components/keyframery/prompt-composer.tsx` and its primitive to your project, and installs UI SDK, along with [button](/docs/components/button), [file-input](/docs/components/file-input), [attachment](/docs/components/attachment), [select](/docs/components/select), [tooltip](/docs/components/tooltip), [trigger-menu](/docs/components/trigger-menu), which it builds on. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.17 @ui-sdk/react@0.1.0-beta.17 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation/manual#add-the-motion-tokens) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "subtle" | "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"subtle"` (the default), `"calm"`, `"springy"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Add what it builds on**

Install [button](/docs/components/button), [file-input](/docs/components/file-input), [attachment](/docs/components/attachment), [select](/docs/components/select), [tooltip](/docs/components/tooltip), [trigger-menu](/docs/components/trigger-menu) the same way first.

**Copy the component**

**components/keyframery/prompt-composer.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/prompt-composer"

/* Theming variables (set on the composer or an ancestor; absent values preserve the theme):
   --prompt-composer-face: Box surface; default: bg-background (dark: bg-card).
   --prompt-composer-ink: Message text; default: text-foreground.
   --prompt-composer-send: Send button; default: bg-primary.
   --prompt-composer-radius: Box corners; default: rounded-[18px].
   --prompt-composer-font: Message size; default: text-[14px].
   --prompt-composer-padding: Box padding; default: p-2.
*/

/* Styled prompt composer: the animated primitive plus the Keyframery look. A field-like box with the
   files on top, the message in the middle and a quiet toolbar along the foot: attach, the model,
   your own actions, a count, and Send, a round primary key that becomes Stop while a reply comes in.
   It is a composition of Keyframery parts: Textarea and Trigger Menu for the text, File Input and
   Attachment for the files, Select for the model, Button and Tooltip for the actions. */

import * as React from "react"

import {
  PromptComposer as PromptComposerRoot,
  PromptComposerAttachments,
  PromptComposerCount,
  PromptComposerDrop,
  PromptComposerDropzone,
  PromptComposerInput,
  PromptComposerSend,
  PromptComposerToolbar,
  type PromptComposerStatus,
  type PromptComposerSubmitOn,
} from "@/components/keyframery/primitives/prompt-composer"
import { FileInput, FileInputTrigger, createFileInputController, formatFileSize } from "@/components/keyframery/primitives/file-input"
import {
  Attachment,
  AttachmentActions,
  AttachmentContent,
  AttachmentDescription,
  AttachmentGroup,
  AttachmentMedia,
  AttachmentProgress,
  AttachmentRemove,
  AttachmentTitle,
} from "@/components/keyframery/attachment"
import { Button } from "@/components/keyframery/button"
import { Select, SelectContent, SelectItem, SelectItemIndicator, SelectItemText, SelectTrigger, SelectValue } from "@/components/keyframery/select"
import { Tooltip, TooltipContent, TooltipShortcut, TooltipTrigger } from "@/components/keyframery/tooltip"
import {
  TriggerMenu,
  TriggerMenuContent,
  TriggerMenuEmpty,
  TriggerMenuGroup,
  TriggerMenuGroupLabel,
  TriggerMenuItem,
  TriggerMenuItemIcon,
  TriggerMenuList,
  TriggerMenuStatus,
  createTriggerMenuController,
  type TriggerDefinition,
  type TriggerMenuData,
} from "@/components/keyframery/trigger-menu"
import { Speed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/** Something @ or / suggests: a person, an order, a file, a command. */
type PromptComposerItem = {
  value: string
  /** What the menu shows and what is inserted after the trigger. */
  label: string
  /** A short detail at the end of the row. */
  description?: string
  icon?: React.ReactNode
  /** Rows with the same group are listed under it. */
  group?: string
  keywords?: string[]
}

type PromptComposerModel = {
  value: string
  label: string
  description?: string
}

type PromptComposerSubmit = {
  /** The message, trimmed. */
  text: string
  /** The files attached to it. */
  attachments: File[]
  /** The chosen model, when there is a model picker. */
  model?: string
}

type UploadContext = { onProgress: (percent: number) => void; signal: AbortSignal }

type FileMeta = { id: string; status: "uploading" | "error" | "done"; progress: number; url?: string; error?: string; abort?: AbortController }

type PromptComposerProps = Omit<React.ComponentProps<"div">, "onSubmit" | "defaultValue" | "children"> &
  SpeedProps & {
    value?: string
    defaultValue?: string
    onValueChange?: (value: string) => void
    /** Send was asked for, with something to send. The composer empties itself afterwards. */
    onSubmit?: (message: PromptComposerSubmit) => void
    /** Stop was pressed while a reply was on its way. */
    onStop?: () => void
    /** `"ready"`, `"submitted"` (spinner), `"streaming"` (Send becomes Stop) or `"error"`. */
    status?: PromptComposerStatus
    placeholder?: string
    /** `"enter"`: Enter sends, Shift+Enter adds a line. `"mod+enter"`: Enter adds a line. Cmd/Ctrl+Enter always sends. */
    submitOn?: PromptComposerSubmitOn
    /** Shows a model picker in the toolbar. */
    models?: PromptComposerModel[]
    model?: string
    defaultModel?: string
    onModelChange?: (model: string) => void
    /** What @ suggests. */
    mentions?: PromptComposerItem[]
    /** What / suggests at the start of the message. */
    commands?: PromptComposerItem[]
    /** Which files can be attached, like `"image/*,.pdf"`. Pass `false` for no attachments. */
    accept?: string | false
    /** The most files at once. */
    maxFiles?: number
    /** Uploads a file as soon as it is attached; the card shows its progress, and Send waits for it. */
    upload?: (file: File, context: UploadContext) => Promise<void>
    /** The most lines before the text scrolls. */
    maxRows?: number
    /** The longest message. */
    maxLength?: number
    /** The count beside Send: characters, an estimate of tokens, or nothing. */
    counter?: "characters" | "tokens" | "none"
    /** Your own buttons, after attach and the model. */
    actions?: React.ReactNode
    /** Shown in the toolbar while `status` is "error". */
    errorMessage?: React.ReactNode
    disabled?: boolean
    /** Reaches the text field, for a controller or focus. */
    inputRef?: React.Ref<HTMLTextAreaElement>
    /** Reaches the trigger menu, to open @ or / from a button. */
    menuController?: ReturnType<typeof createTriggerMenuController>
  }

let nextId = 0
const ids = new WeakMap<File, string>()
const idOf = (file: File) => {
  let id = ids.get(file)
  if (!id) ids.set(file, (id = `kf-file-${++nextId}`))
  return id
}

/* 16px glyphs, drawn like the rest of the library. */
const svg = (d: React.ReactNode) => (
  <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
    {d}
  </svg>
)
const PaperclipIcon = () => svg(<path d="m13.25 7.4-5.1 5.1a3.18 3.18 0 0 1-4.5-4.5l5.43-5.43a2.12 2.12 0 0 1 3 3l-5.42 5.42a1.06 1.06 0 0 1-1.5-1.5l4.84-4.84" />)
const FileIcon = () => svg(<path d="M9.25 1.75h-4.5a1.5 1.5 0 0 0-1.5 1.5v9.5a1.5 1.5 0 0 0 1.5 1.5h6.5a1.5 1.5 0 0 0 1.5-1.5v-7.5ZM9.25 1.75v4h4" />)
const DropIcon = () => svg(<path d="M8 10.25V2.75M4.75 6 8 2.75 11.25 6M2.75 10.5v1.25c0 .83.67 1.5 1.5 1.5h7.5c.83 0 1.5-.67 1.5-1.5V10.5" />)

/* Grouped trigger data for UI SDK, from the flat items given as props. */
function toData(items: PromptComposerItem[]): TriggerMenuData<string> {
  const plain = (item: PromptComposerItem) => ({ value: item.value, label: item.label, keywords: item.keywords })
  if (!items.some((item) => item.group)) return items.map(plain)
  const groups: { type: "group"; label: string; items: ReturnType<typeof plain>[] }[] = []
  for (const item of items) {
    const label = item.group ?? ""
    let group = groups.find((g) => g.label === label)
    if (!group) groups.push((group = { type: "group", label, items: [] }))
    group.items.push(plain(item))
  }
  return groups as TriggerMenuData<string>
}

/* One suggestion row: icon, label, detail. */
function MenuRows({ items, lookup }: { items: TriggerMenuData<unknown> | undefined; lookup: (value: string) => PromptComposerItem | undefined }) {
  return (items ?? []).map((entry, index) => {
    if (typeof entry === "string") return null
    if ("type" in entry && entry.type === "separator") return null
    if ("type" in entry && entry.type === "group") {
      return (
        <TriggerMenuGroup key={`group-${entry.label ?? index}`}>
          {entry.label && <TriggerMenuGroupLabel>{entry.label}</TriggerMenuGroupLabel>}
          <MenuRows items={entry.items} lookup={lookup} />
        </TriggerMenuGroup>
      )
    }
    const value = String(entry.value)
    const item = lookup(value)
    return (
      <TriggerMenuItem<unknown> key={value} value={entry.value} label={entry.label} keywords={entry.keywords}>
        {item?.icon && <TriggerMenuItemIcon>{item.icon}</TriggerMenuItemIcon>}
        <span className="min-w-0 flex-1 truncate">{entry.label}</span>
        {item?.description && (
          <span className="shrink-0 text-[12px] text-muted-foreground tabular-nums group-data-highlighted/item:text-current/70">{item.description}</span>
        )}
      </TriggerMenuItem>
    )
  })
}

function useControllable<T>(value: T | undefined, fallback: T, onChange?: (value: T) => void) {
  const [own, setOwn] = React.useState(fallback)
  const controlled = value !== undefined
  const current = controlled ? value : own
  const set = React.useCallback(
    (next: T) => {
      if (!controlled) setOwn(next)
      onChange?.(next)
    },
    [controlled, onChange],
  )
  return [current, set] as const
}

function PromptComposer({
  speed,
  value,
  defaultValue = "",
  onValueChange,
  onSubmit,
  onStop,
  status = "ready",
  placeholder = "Write a message…",
  submitOn = "enter",
  models,
  model,
  defaultModel,
  onModelChange,
  mentions,
  commands,
  accept,
  maxFiles,
  upload,
  maxRows = 8,
  maxLength,
  counter = "characters",
  actions,
  errorMessage = "Something went wrong. Send it again.",
  disabled = false,
  inputRef,
  menuController,
  className,
  style,
  "aria-label": ariaLabel = "Message composer",
  ...props
}: PromptComposerProps) {
  const [text, setText] = useControllable(value, defaultValue, onValueChange)
  const [chosenModel, setChosenModel] = useControllable(model, defaultModel ?? models?.[0]?.value ?? "", onModelChange)
  const [files, setFiles] = React.useState<File[]>([])
  const [meta, setMeta] = React.useState<Record<string, FileMeta>>({})
  const fileInput = React.useMemo(() => createFileInputController(), [])
  const metaRef = React.useRef(meta)
  metaRef.current = meta

  /* Free the previews when the composer goes. */
  React.useEffect(
    () => () => {
      for (const m of Object.values(metaRef.current)) {
        m.abort?.abort()
        if (m.url) URL.revokeObjectURL(m.url)
      }
    },
    [],
  )

  const patch = (id: string, change: Partial<FileMeta>) => setMeta((all) => (all[id] ? { ...all, [id]: { ...all[id], ...change } } : all))

  /* New files get an id, a preview if they are pictures, and an upload if there is one. */
  const onFilesChange = (next: File[]) => {
    const added = next.filter((file) => !metaRef.current[idOf(file)])
    setFiles(next)
    if (!added.length) return
    const entries: Record<string, FileMeta> = {}
    for (const file of added) {
      const id = idOf(file)
      const abort = upload ? new AbortController() : undefined
      entries[id] = {
        id,
        status: upload ? "uploading" : "done",
        progress: 0,
        url: file.type.startsWith("image/") ? URL.createObjectURL(file) : undefined,
        abort,
      }
      if (upload && abort) {
        upload(file, { signal: abort.signal, onProgress: (p) => patch(id, { progress: Math.max(0, Math.min(100, p)) }) })
          .then(() => patch(id, { status: "done", progress: 100 }))
          .catch((error: unknown) => {
            if (abort.signal.aborted) return
            patch(id, { status: "error", error: error instanceof Error ? error.message : "Upload failed" })
          })
      }
    }
    setMeta((all) => ({ ...all, ...entries }))
  }

  /* After its card has left: drop the file and its preview. */
  const removeFile = (id: string | undefined) => {
    const file = files.find((f) => idOf(f) === id)
    if (!file) return
    const m = metaRef.current[idOf(file)]
    m?.abort?.abort()
    if (m?.url) URL.revokeObjectURL(m.url)
    setMeta((all) => {
      const { [idOf(file)]: _gone, ...rest } = all
      return rest
    })
    fileInput.removeFile(file)
  }

  const trimmed = text.trim()
  const uploading = files.some((f) => meta[idOf(f)]?.status === "uploading")
  const failed = files.some((f) => meta[idOf(f)]?.status === "error")
  const over = maxLength !== undefined && text.length > maxLength
  const empty = (!trimmed && files.length === 0) || uploading || failed || over
  const busy = status === "submitted" || status === "streaming"

  const send = () => {
    if (disabled || empty || busy) return
    onSubmit?.({ text: trimmed, attachments: files, ...(models?.length ? { model: chosenModel } : null) })
    setText("")
    for (const f of files) {
      const m = metaRef.current[idOf(f)]
      if (m?.url) URL.revokeObjectURL(m.url)
    }
    setMeta({})
    fileInput.clear()
  }

  /* The suggestions, and how to find a row's icon and detail again. */
  const triggers = React.useMemo(() => {
    const list: TriggerDefinition<string>[] = []
    if (mentions?.length) list.push({ char: "@", spaces: 1, items: toData(mentions) })
    if (commands?.length) list.push({ char: "/", boundary: "start", items: toData(commands) })
    return list
  }, [mentions, commands])
  const lookup = (trigger: string | null) => (v: string) => (trigger === "/" ? commands : mentions)?.find((item) => item.value === v)

  const count =
    counter === "tokens"
      ? `≈ ${Math.ceil(text.length / 4).toLocaleString()} ${Math.ceil(text.length / 4) === 1 ? "token" : "tokens"}`
      : maxLength !== undefined
        ? `${text.length.toLocaleString()} / ${maxLength.toLocaleString()}`
        : text.length.toLocaleString()
  const near = maxLength !== undefined && text.length >= maxLength * 0.9

  const sendLabel = busy ? "Stop" : "Send"
  const canPress = busy ? Boolean(onStop) && !disabled : !empty && !disabled

  const field = (
    <PromptComposerInput
      ref={inputRef}
      aria-label="Message"
      placeholder={placeholder}
      value={text}
      onValueChange={(next) => setText(next)}
      disabled={disabled}
      rows={1}
      className={cn(
        "block w-full min-w-0 resize-none border-0 bg-transparent px-2 pt-1.5 pb-1 text-[length:var(--prompt-composer-font,14px)] leading-[1.45] text-[color:var(--prompt-composer-ink,var(--foreground))] outline-none",
        "min-h-[calc(1.45em+0.625rem)] max-h-[calc(var(--prompt-composer-rows,8)*1.45em+0.625rem)] overflow-y-auto [scrollbar-width:thin]",
        "placeholder:text-muted-foreground/80 disabled:cursor-not-allowed",
      )}
    />
  )

  return (
    <Speed speed={speed}>
      <FileInput
        multiple
        accept={accept || undefined}
        maxFiles={maxFiles}
        value={files}
        onValueChange={(next) => onFilesChange([...next])}
        disabled={disabled || accept === false}
        controller={fileInput}
        className={cn("@container/prompt-composer w-full min-w-0", className)}
        style={{ ...style, "--prompt-composer-rows": maxRows } as React.CSSProperties}
        {...props}
      >
        <TriggerMenu<string> triggers={triggers} controller={menuController}>
          <PromptComposerRoot
            aria-label={ariaLabel}
            status={status}
            submitOn={submitOn}
            empty={empty}
            disabled={disabled}
            onSubmit={send}
            onStop={() => onStop?.()}
            className="w-full"
          >
            <PromptComposerDropzone
              className={cn(
                "flex flex-col gap-1 rounded-[var(--prompt-composer-radius,18px)] bg-[var(--prompt-composer-face,var(--background))] p-[var(--prompt-composer-padding,0.5rem)] dark:bg-[var(--prompt-composer-face,var(--card))]",
                "[--line:rgb(0_0_0/0.1)] dark:[--line:rgb(255_255_255/0.1)]",
                "shadow-[0_0_0_1px_var(--line),0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.12)] dark:shadow-[0_0_0_1px_var(--line),0_8px_24px_-12px_rgb(0_0_0/0.6)]",
                "hover:[--line:rgb(0_0_0/0.16)] dark:hover:[--line:rgb(255_255_255/0.16)]",
                "has-[textarea:focus-visible]:[--line:var(--ring)] has-[textarea:focus-visible]:ring-[3px] has-[textarea:focus-visible]:ring-ring/20",
                "data-dragging:[--line:color-mix(in_oklab,var(--foreground)_35%,transparent)]",
                "group-data-disabled/prompt-composer:opacity-60",
              )}
            >
              <PromptComposerAttachments>
                <AttachmentGroup aria-label="Attached files" className="pb-1.5">
                  {files.map((file) => {
                    const m = meta[idOf(file)]
                    const id = idOf(file)
                    return (
                      <Attachment
                        key={id}
                        value={id}
                        size="sm"
                        status={m?.status ?? "done"}
                        progress={m?.progress ?? 0}
                        onRemove={removeFile}
                        className="max-w-60"
                      >
                        <AttachmentMedia variant={m?.url ? "image" : "icon"}>{m?.url ? <img src={m.url} alt="" /> : <FileIcon />}</AttachmentMedia>
                        <AttachmentContent>
                          <AttachmentTitle>{file.name}</AttachmentTitle>
                          <AttachmentDescription>
                            {m?.status === "uploading" ? `Uploading · ${Math.round(m.progress)}%` : m?.status === "error" ? (m.error ?? "Upload failed") : formatFileSize(file.size)}
                          </AttachmentDescription>
                        </AttachmentContent>
                        <AttachmentProgress />
                        <AttachmentActions>
                          <AttachmentRemove aria-label={`Remove ${file.name}`} />
                        </AttachmentActions>
                      </Attachment>
                    )
                  })}
                </AttachmentGroup>
              </PromptComposerAttachments>

              {field}

              <PromptComposerToolbar className="flex min-w-0 items-center gap-1">
                {accept !== false && (
                  <Tooltip>
                    <TooltipTrigger
                      render={
                        <FileInputTrigger
                          render={<Button variant="ghost" size="icon" className="bg-none text-muted-foreground shadow-none hover:text-foreground dark:bg-none dark:shadow-none" />}
                        />
                      }
                      aria-label="Attach files"
                    >
                      <PaperclipIcon />
                    </TooltipTrigger>
                    <TooltipContent>Attach files</TooltipContent>
                  </Tooltip>
                )}
                {models && models.length > 0 && (
                  <Select<string> value={chosenModel} onValueChange={(v) => v != null && setChosenModel(v)} items={models.map((m) => ({ value: m.value, label: m.label }))} disabled={disabled}>
                    <SelectTrigger
                      aria-label="Model"
                      className={cn(
                        "h-8 w-auto max-w-44 shrink-0 gap-1 rounded-[9px] bg-transparent px-2.5 text-[13px] font-medium text-muted-foreground shadow-none dark:bg-transparent dark:shadow-none",
                        "hover:bg-accent hover:text-foreground hover:shadow-none dark:hover:shadow-none data-open:bg-accent data-open:text-foreground data-open:shadow-none dark:data-open:shadow-none",
                        "[&>svg:last-child]:size-3.5",
                      )}
                    >
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent className="w-64">
                      {models.map((m) => (
                        <SelectItem key={m.value} value={m.value} label={m.label} className="items-start py-2">
                          <span className="flex min-w-0 flex-1 flex-col gap-1">
                            <SelectItemText className="flex-none">{m.label}</SelectItemText>
                            {m.description && <span className="text-[12px] leading-4 text-muted-foreground">{m.description}</span>}
                          </span>
                          <SelectItemIndicator className="mt-px" />
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                )}
                {actions}

                <span className="ms-auto flex min-w-0 items-center gap-2.5 ps-2">
                  {status === "error" ? (
                    <span role="alert" className="truncate text-[12px] text-destructive">
                      {errorMessage}
                    </span>
                  ) : (
                    counter !== "none" && (
                      <PromptComposerCount
                        near={near}
                        over={over}
                        aria-hidden={text.length === 0 || undefined}
                        className={cn(
                          "truncate text-[12px] text-muted-foreground/80 tabular-nums @max-[24rem]/prompt-composer:hidden",
                          text.length === 0 && "opacity-0",
                          "data-near:text-foreground data-over:text-destructive",
                        )}
                      >
                        {count}
                      </PromptComposerCount>
                    )
                  )}
                  <Tooltip shortcut={busy ? undefined : submitOn === "enter" ? "enter" : "mod+enter"}>
                    <TooltipTrigger
                      render={
                        <PromptComposerSend
                          className={cn(
                            "size-8 shrink-0 cursor-pointer rounded-full bg-[var(--prompt-composer-send,var(--primary))] text-primary-foreground outline-none",
                            "shadow-[inset_0_1px_0_rgb(255_255_255/0.16),0_1px_2px_rgb(0_0_0/0.22)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.18),0_1px_2px_rgb(0_0_0/0.5)]",
                            "not-data-disabled:hover:bg-[color-mix(in_oklab,var(--prompt-composer-send,var(--primary)),var(--background)_12%)]",
                            "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
                            "data-disabled:cursor-not-allowed data-disabled:opacity-35 data-disabled:shadow-none",
                            "[&_svg]:size-4",
                          )}
                          aria-label={sendLabel}
                          data-composer-part="send"
                          disabled={!canPress}
                          focusableWhenDisabled
                          onClick={busy ? () => onStop?.() : send}
                        />
                      }
                    />
                    <TooltipContent>
                      {busy ? "Stop the reply" : "Send"}
                      {!busy && <TooltipShortcut />}
                    </TooltipContent>
                  </Tooltip>
                </span>
              </PromptComposerToolbar>

              <PromptComposerDrop className="grid place-items-center rounded-[inherit] outline-1 -outline-offset-[5px] outline-dashed outline-foreground/25 bg-[color-mix(in_oklab,var(--prompt-composer-face,var(--background))_88%,transparent)] backdrop-blur-[2px] dark:bg-[color-mix(in_oklab,var(--prompt-composer-face,var(--card))_88%,transparent)]">
                <span className="flex items-center gap-2 text-[13px] font-medium text-foreground [&_svg]:size-4 [&_svg]:text-muted-foreground">
                  <DropIcon />
                  Drop files to attach
                </span>
              </PromptComposerDrop>
            </PromptComposerDropzone>
          </PromptComposerRoot>

          <TriggerMenuContent className="w-72">
            <TriggerMenuEmpty>Nothing matches</TriggerMenuEmpty>
            <TriggerMenuList>{(state) => <MenuRows items={state.items} lookup={lookup(state.trigger)} />}</TriggerMenuList>
          </TriggerMenuContent>
          <TriggerMenuStatus />
        </TriggerMenu>
      </FileInput>
    </Speed>
  )
}

export { PromptComposer, createTriggerMenuController as createPromptComposerMenuController }
export type { PromptComposerItem, PromptComposerModel, PromptComposerProps, PromptComposerSubmit }
```

**components/keyframery/primitives/prompt-composer.tsx**

```tsx
"use client"

/* Animated prompt composer, on UI SDK's core. UI SDK ships no composer, so its root is defined in
   `@/components/core/prompt-composer` with `definePrimitive` and rendered here; the field is UI SDK's
   textarea with its trigger menu, the files are UI SDK's file input, the buttons are UI SDK buttons.
   This file adds motion only. Colours, radii, shadows and spacing stay yours (style `data-status`,
   `data-empty` and `data-dragging`).

   Feedback (always on):
   - Send and Stop: the arrow, the spinner and the stop square cross-fade in place with a small
     scale as the status changes. With flourish they also turn and blur through the swap and land
     with a pop.
   - Files: the row above the text opens to its height when the first file arrives and closes when
     the last one leaves (each file pops in and out by itself: the attachment primitive).
   - Dragging files over it: the drop layer fades in over the box.
   - The counter changes colour as it nears the limit.
   Flourish (scaled by --kf-flourish): the swap's turn, blur and pop; the drop layer's rise; the box
   leaning toward the files while they are over it. */

import { Button } from "@/components/keyframery/primitives/button"
import { FileInputDropzone } from "@ui-sdk/react/file-input"
import { createParts } from "@ui-sdk/react/primitive"
import { Textarea } from "@ui-sdk/react/textarea"
import { TriggerMenuInput } from "@ui-sdk/react/trigger-menu"
import * as React from "react"

import { promptComposer } from "@/components/keyframery/core/prompt-composer-core"
import { cn } from "@/lib/utils"

const parts = createParts(promptComposer, { root: "div", attachments: "div", toolbar: "div", drop: "div", count: "span" })

type ClassName<S> = string | ((state: S) => string | undefined) | undefined
function withClass<S>(base: string, className: ClassName<S>) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* The root. Everything that follows the status is styled from it (`group/prompt-composer`). */
function PromptComposer({ className, ...props }: React.ComponentProps<typeof parts.Root>) {
  return <parts.Root className={withClass("group/prompt-composer relative", className)} {...props} />
}

/* The box: a UI SDK drop zone, so files dropped on it or pasted into the text are attached.
   It leans toward files dragged over it. */
function PromptComposerDropzone({ className, ...props }: React.ComponentProps<typeof FileInputDropzone>) {
  return (
    <FileInputDropzone
      data-composer-part="box"
      className={withClass(
        cn(
          "group/prompt-composer-box relative isolate",
          "[transition:scale_calc(420ms*var(--kf-speed,1))_var(--ease-spring),box-shadow_calc(180ms*var(--kf-speed,1))_var(--ease-house),background-color_calc(180ms*var(--kf-speed,1))_var(--ease-house)]",
          "data-dragging:scale-[calc(1+0.012*var(--kf-flourish,1))]",
          "motion-reduce:[transition:none]!",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* Shown over the box while files are dragged over it. Fades in; its content rises a little. */
function PromptComposerDrop({ className, ...props }: React.ComponentProps<typeof parts.Drop>) {
  return (
    <parts.Drop
      className={withClass(
        cn(
          "pointer-events-none absolute inset-0 z-20 opacity-0",
          "transition-opacity duration-[calc(160ms*var(--kf-speed,1))] ease-house",
          "group-data-dragging/prompt-composer-box:opacity-100 group-data-dragging/prompt-composer-box:duration-[calc(220ms*var(--kf-speed,1))]",
          "*:translate-y-[calc(0.375rem*var(--kf-flourish,1))] *:transition-[translate] *:duration-[calc(420ms*var(--kf-speed,1))] *:ease-spring",
          "group-data-dragging/prompt-composer-box:*:translate-y-0",
          "motion-reduce:transition-none! motion-reduce:*:transition-none!",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* The row of files above the text. It opens to its height when the first file arrives and closes
   as the last one leaves, so the text below moves instead of jumping. Put the files inside. */
function PromptComposerAttachments({ className, children, ...props }: React.ComponentProps<typeof parts.Attachments>) {
  return (
    <parts.Attachments
      className={withClass(
        cn(
          "grid grid-rows-[0fr] [transition:grid-template-rows_calc(320ms*var(--kf-speed,1))_var(--ease-house)]",
          "has-[[data-slot=attachment]:not([data-removing])]:grid-rows-[1fr] has-[[data-slot=attachment]:not([data-removing])]:[transition-duration:calc(380ms*var(--kf-speed,1))]",
          "motion-reduce:[transition:none]!",
        ),
        className,
      )}
      {...props}
    >
      {(state) => <div className="min-h-0 overflow-hidden">{typeof children === "function" ? children(state) : children}</div>}
    </parts.Attachments>
  )
}

const PromptComposerToolbar = parts.Toolbar

/* The text field: UI SDK's trigger menu input (so @ and / open suggestions at the caret) rendered as
   UI SDK's textarea (so it grows with its text and an agent can read and set it). */
function PromptComposerInput({
  className,
  ...props
}: React.ComponentProps<typeof Textarea>) {
  const { value, defaultValue, onValueChange, autoResize = true, controller, ...rest } = props
  return (
    <TriggerMenuInput
      {...(rest as React.ComponentProps<typeof TriggerMenuInput>)}
      data-slot="prompt-composer-input"
      render={<Textarea autoResize={autoResize} value={value} defaultValue={defaultValue} onValueChange={onValueChange} controller={controller} />}
      className={withClass("transition-[color] duration-[calc(150ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none!", className as ClassName<unknown>)}
    />
  )
}

/* One glyph of the send button. All three are there; `--kf-glyph` (1 shown, 0 hidden) follows the
   root's `data-status`. A glyph leaves quickly and the next one arrives a beat later. */
const glyph = cn(
  "absolute inset-0 grid place-items-center",
  "opacity-(--kf-glyph) [scale:calc(1-(1-var(--kf-glyph))*(0.1+0.4*var(--kf-flourish,1)))] [rotate:calc((1-var(--kf-glyph))*-45deg*var(--kf-flourish,1))] [filter:blur(calc((1-var(--kf-glyph))*3px*var(--kf-flourish,1)))]",
  "[transition-property:opacity,scale,rotate,filter] [transition-timing-function:var(--ease-house),var(--ease-pop),var(--ease-spring),var(--ease-house)]",
  "[transition-duration:calc((140ms+var(--kf-glyph)*80ms)*var(--kf-speed,1)),calc((160ms+var(--kf-glyph)*260ms)*var(--kf-speed,1)),calc((160ms+var(--kf-glyph)*260ms)*var(--kf-speed,1)),calc((140ms+var(--kf-glyph)*100ms)*var(--kf-speed,1))]",
  "[transition-delay:calc(var(--kf-glyph)*60ms*var(--kf-speed,1))]",
  "motion-reduce:[transition:none]!",
)

function SendGlyphs() {
  return (
    <>
      <span
        data-slot="prompt-composer-send-icon"
        data-icon="send"
        className={cn(glyph, "[--kf-glyph:1] group-data-[status=submitted]/prompt-composer:[--kf-glyph:0] group-data-[status=streaming]/prompt-composer:[--kf-glyph:0]")}
      >
        <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
          <path d="M8 13V3.5M3.75 7.5 8 3.25l4.25 4.25" />
        </svg>
      </span>
      <span data-slot="prompt-composer-send-icon" data-icon="wait" className={cn(glyph, "[--kf-glyph:0] group-data-[status=submitted]/prompt-composer:[--kf-glyph:1]")}>
        <svg
          viewBox="0 0 16 16"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.75"
          strokeLinecap="round"
          className="animate-spin [animation-duration:calc(800ms*var(--kf-speed,1))] motion-reduce:[animation-duration:calc(2400ms*var(--kf-speed,1))]"
        >
          <circle cx="8" cy="8" r="5.25" opacity="0.3" />
          <path d="M8 2.75A5.25 5.25 0 0 1 13.25 8" />
        </svg>
      </span>
      <span data-slot="prompt-composer-send-icon" data-icon="stop" className={cn(glyph, "[--kf-glyph:0] group-data-[status=streaming]/prompt-composer:[--kf-glyph:1]")}>
        <svg viewBox="0 0 16 16" fill="currentColor">
          <rect x="4.25" y="4.25" width="7.5" height="7.5" rx="1.75" />
        </svg>
      </span>
    </>
  )
}

/* Send, which becomes Stop while a reply is on its way. A UI SDK button; with no children it shows
   the arrow, the spinner ("submitted") or the stop square ("streaming"), from the root's status. */
function PromptComposerSend({ className, children, ...props }: React.ComponentProps<typeof Button>) {
  return (
    <Button data-slot="prompt-composer-send" pendingIndicator={null} className={withClass("relative", className)} {...props}>
      {children ?? <SendGlyphs />}
    </Button>
  )
}

/* The count beside Send. Its colour eases as it nears the limit (`data-near`, `data-over`). */
function PromptComposerCount({ className, ...props }: React.ComponentProps<typeof parts.Count>) {
  return (
    <parts.Count
      className={withClass("transition-[color,opacity] duration-[calc(200ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none!", className)}
      {...props}
    />
  )
}

export {
  PromptComposer,
  PromptComposerAttachments,
  PromptComposerCount,
  PromptComposerDrop,
  PromptComposerDropzone,
  PromptComposerInput,
  PromptComposerSend,
  PromptComposerToolbar,
}
export type { PromptComposerStatus, PromptComposerSubmitOn } from "@/components/keyframery/core/prompt-composer-core"
```

**components/keyframery/core/prompt-composer-core.ts**

```ts
/* The input box of an AI chat, as a UI SDK primitive. UI SDK ships no composer, so its root is
   defined with its core: the same definition renders in React, Vue, Svelte, Solid and web components.
   The text field is UI SDK's textarea (with a trigger menu for @ and /), the files are UI SDK's file
   input, the buttons are UI SDK buttons; this primitive adds what ties them together:

   - The keys. Enter sends and Shift+Enter starts a line (`submitOn: "enter"`), or Enter starts a
     line and Cmd/Ctrl+Enter sends (`submitOn: "mod+enter"`). Cmd/Ctrl+Enter always sends. Nothing
     sends while an input method is composing, and a key a part inside already used (the trigger
     menu choosing a suggestion with Enter) is left alone.
   - The state the look follows: `data-status` ("ready", "submitted", "streaming", "error"),
     `data-empty` while there is nothing to send, `data-disabled`.
   - The agent: it can `submit` what is in the box and `stop` a reply. Screen readers hear when a
     reply starts and stops, since the Send button changing into Stop is easy to miss. */

import { announce, definePrimitive, isComposing } from "@ui-sdk/core"

type PromptComposerStatus = "ready" | "submitted" | "streaming" | "error"

type PromptComposerSubmitOn = "enter" | "mod+enter"

type PromptComposerOptions = {
  /** Where the conversation is: `"ready"`, `"submitted"` (sent, waiting for the reply), `"streaming"` (the reply is coming in) or `"error"`. */
  status?: PromptComposerStatus
  /** Which key sends: `"enter"` (Shift+Enter for a new line) or `"mod+enter"` (Enter for a new line). Cmd/Ctrl+Enter always sends. */
  submitOn?: PromptComposerSubmitOn
  /** Nothing to send: no text and no files. */
  empty?: boolean
  /** Turns the whole composer off. */
  disabled?: boolean
  /** Asked to send: a key, the agent, or `submit()`. */
  onSubmit?: (details: { event?: Event }) => void
  /** Asked to stop the reply. */
  onStop?: (details: { event?: Event }) => void
}

type PromptComposerState = {
  status: PromptComposerStatus
  empty: boolean
  disabled: boolean
}

const statusOf = (status: string | undefined): PromptComposerStatus =>
  status === "submitted" || status === "streaming" || status === "error" ? status : "ready"

/* Enter pressed while a suggestion list was open at the caret belongs to that list, even when the
   list has closed by the time the key reaches the root (it chose an item). Noted on the way down. */
const menuKeys = new WeakSet<Event>()
const listOpen = (target: EventTarget | null) =>
  target instanceof HTMLElement && (target.hasAttribute("data-open") || target.getAttribute("aria-expanded") === "true")

const busy = (status: PromptComposerStatus) => status === "submitted" || status === "streaming"

const isApple = () => typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent)

const promptComposer = definePrimitive({
  name: "prompt-composer",
  options: {
    status: "string",
    submitOn: "string",
    empty: "boolean",
    disabled: "boolean",
    onSubmit: "callback",
    onStop: "callback",
  },
  state: (options: PromptComposerOptions): PromptComposerState => ({
    status: statusOf(options.status),
    empty: options.empty ?? true,
    disabled: options.disabled ?? false,
  }),
  sync: (options) => ({
    status: statusOf(options.status),
    empty: options.empty ?? true,
    disabled: options.disabled ?? false,
  }),
  controlled: ["status", "empty"],
  api: (context) => {
    const canSubmit = () => {
      const { status, empty, disabled } = context.store.get()
      return !disabled && !empty && !busy(status)
    }
    return {
      /** Sends what is in the composer, unless it is empty, disabled or a reply is on its way. */
      submit(event?: Event) {
        if (!canSubmit()) return false
        context.options().onSubmit?.({ event })
        return true
      },
      /** Stops the reply that is on its way. */
      stop(event?: Event) {
        const { status, disabled } = context.store.get()
        if (disabled || !busy(status)) return false
        context.options().onStop?.({ event })
        return true
      },
      internal: {
        /* Enter, from the field inside. A part that used the key already prevented it. */
        keydown(event: KeyboardEvent, submit: (event?: Event) => boolean) {
          if (event.key !== "Enter" || event.defaultPrevented || menuKeys.has(event)) return
          if (isComposing(event) || event.keyCode === 229) return
          if (!(event.target instanceof HTMLTextAreaElement)) return
          const mod = isApple() ? event.metaKey : event.ctrlKey
          const submitOn = context.options().submitOn === "mod+enter" ? "mod+enter" : "enter"
          const sends = mod ? !event.shiftKey : submitOn === "enter" && !event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey
          if (!sends) return
          /* The send key never adds a line, even when there is nothing to send yet. */
          event.preventDefault()
          submit(event)
        },
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, PromptComposerState>({
      role: "group",
      state: (state) => ({ ...state }),
      attrs: (state) => ({
        "data-status": state.status,
        "data-empty": state.empty ? "" : undefined,
        "data-disabled": state.disabled ? "" : undefined,
        "aria-busy": busy(state.status) ? "true" : undefined,
      }),
      on: { keydown: (event, { api }) => api.internal.keydown(event as KeyboardEvent, api.submit) },
      /* Says when a reply starts or fails, and notes keys meant for an open suggestion list. */
      bind: (el) => {
        const noteMenuKey = (event: KeyboardEvent) => {
          if (event.key === "Enter" && listOpen(event.target)) menuKeys.add(event)
        }
        el.addEventListener("keydown", noteMenuKey, true)
        let was = el.getAttribute("data-status")
        const observer = new MutationObserver(() => {
          const now = el.getAttribute("data-status")
          if (now === was) return
          const before = was
          was = now
          if (now === "streaming" && before !== "streaming") announce(el.getAttribute("data-announce-streaming") ?? "Replying", { priority: "polite" })
          if (now === "error") announce(el.getAttribute("data-announce-error") ?? "The reply failed", { priority: "assertive" })
        })
        observer.observe(el, { attributes: true, attributeFilter: ["data-status"] })
        return () => {
          observer.disconnect()
          el.removeEventListener("keydown", noteMenuKey, true)
        }
      },
    }),
    /* The files above the text. It holds attachments, which name themselves. */
    attachments: slot({}),
    /* The row of actions along the foot: attach, the model, your own, the count and Send. */
    toolbar: slot({}),
    /* What shows over the box while files are dragged over it. Decorative: the drop zone is announced by the file input. */
    drop: slot({
      attrs: () => ({ "aria-hidden": "true" }),
    }),
    /* The length of the message, beside Send. `near` and `over` the limit show as data attributes. */
    count: slot<{ near?: boolean; over?: boolean }>({
      props: { near: "boolean", over: "boolean" },
      attrs: (_state, part) => ({
        "data-near": part.props.near ? "" : undefined,
        "data-over": part.props.over ? "" : undefined,
        "aria-live": part.props.near || part.props.over ? "polite" : undefined,
      }),
    }),
  }),
  agent: { actions: ["submit", "stop"] },
})

export { promptComposer, type PromptComposerOptions, type PromptComposerStatus, type PromptComposerSubmitOn }
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

**Vue**

```bash
npx shadcn-vue@latest add https://keyframery.com/r/vue/prompt-composer.json
```

This adds `components/keyframery/prompt-composer/` (one file per part, with the same part names as React) to your Vue or Nuxt project, installs UI SDK for Vue and adds the motion tokens to your global CSS. See [Install for Vue](/docs/installation/vue).

## Usage [#usage]

**React**

```tsx
import { PromptComposer } from "@/components/keyframery/prompt-composer"

export default function Usage() {
  return <PromptComposer placeholder="Ask anything…" onSubmit={({ text, attachments }) => console.log(text, attachments)} />
}
```

**Vue**

```vue
<script setup lang="ts">
import { PromptComposer } from "@/components/keyframery/prompt-composer"
</script>

<template>
  <PromptComposer placeholder="Ask anything…" @submit="console.log(text, attachments)" />
</template>
```

## Examples [#examples]

### Mentions and commands [#mentions-and-commands]

`mentions` open at the caret after @ and `commands` after / at the start of the message. Each item can carry an icon, a detail and a group; choosing one inserts its label.

<ExamplePreview name="prompt-composer/mentions">
**React**

  ```tsx
  import { PromptComposer, type PromptComposerItem } from "@/components/keyframery/prompt-composer"

  const mentions: PromptComposerItem[] = [
    { value: "4821", label: "Order #4821", description: "Shipped", group: "Orders" },
    { value: "4819", label: "Order #4819", description: "Packing", group: "Orders" },
    { value: "amara", label: "Amara Okafor", description: "3 orders", group: "Customers" },
  ]

  const commands: PromptComposerItem[] = [
    { value: "track", label: "track", description: "Where a parcel is" },
    { value: "refund", label: "refund", description: "Start a refund" },
  ]

  export default function PromptComposerMentions() {
    return (
      <PromptComposer
        className="max-w-[480px]"
        placeholder="Type @ for an order, / for a command"
        mentions={mentions}
        commands={commands}
        accept={false}
        counter="none"
      />
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { PromptComposer, type PromptComposerItem } from "@/components/keyframery/prompt-composer"

  const mentions: PromptComposerItem[] = [
    { value: "4821", label: "Order #4821", description: "Shipped", group: "Orders" },
    { value: "4819", label: "Order #4819", description: "Packing", group: "Orders" },
    { value: "amara", label: "Amara Okafor", description: "3 orders", group: "Customers" },
  ]
  const commands: PromptComposerItem[] = [
    { value: "track", label: "track", description: "Where a parcel is" },
    { value: "refund", label: "refund", description: "Start a refund" },
  ]
  </script>

  <template>
    <PromptComposer
      class="max-w-[480px]"
      placeholder="Type @ for an order, / for a command"
      :mentions="mentions"
      :commands="commands"
      :accept="false"
      counter="none"
    />
  </template>
  ```
</ExamplePreview>

### Send and Stop [#send-and-stop]

Pass the chat's `status`: "submitted" turns Send into a spinner and "streaming" into Stop, which calls `onStop`. A model picker shows when you pass `models`.

<ExamplePreview name="prompt-composer/streaming">
**React**

  ```tsx
  import * as React from "react"

  import { PromptComposer, type PromptComposerStatus } from "@/components/keyframery/prompt-composer"

  const models = [
    { value: "fast", label: "Fast", description: "Quick lookups" },
    { value: "thorough", label: "Thorough", description: "Checks every order it names" },
  ]

  export default function PromptComposerStreaming() {
    const [status, setStatus] = React.useState<PromptComposerStatus>("ready")
    const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined)
    React.useEffect(() => () => clearTimeout(timer.current), [])

    return (
      <PromptComposer
        className="max-w-[480px]"
        status={status}
        models={models}
        onSubmit={() => {
          setStatus("submitted")
          timer.current = setTimeout(() => {
            setStatus("streaming")
            timer.current = setTimeout(() => setStatus("ready"), 4000)
          }, 800)
        }}
        onStop={() => {
          clearTimeout(timer.current)
          setStatus("ready")
        }}
      />
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { onBeforeUnmount, ref } from "vue"

  import { PromptComposer, type PromptComposerStatus } from "@/components/keyframery/prompt-composer"

  const models = [
    { value: "fast", label: "Fast", description: "Quick lookups" },
    { value: "thorough", label: "Thorough", description: "Checks every order it names" },
  ]

  const status = ref<PromptComposerStatus>("ready")
  let timer: ReturnType<typeof setTimeout> | undefined
  onBeforeUnmount(() => clearTimeout(timer))

  function onSubmit() {
    status.value = "submitted"
    timer = setTimeout(() => {
      status.value = "streaming"
      timer = setTimeout(() => status.value = "ready", 4000)
    }, 800)
  }

  function onStop() {
    clearTimeout(timer)
    status.value = "ready"
  }
  </script>

  <template>
    <PromptComposer class="max-w-[480px]" :status="status" :models="models" @submit="onSubmit" @stop="onStop" />
  </template>
  ```
</ExamplePreview>

### Uploads [#uploads]

Give `upload` and each file uploads as soon as it is attached, by the paperclip, a drop or a paste. Its card shows the progress, and Send waits until every file is up. `maxLength` makes the count read against the limit.

<ExamplePreview name="prompt-composer/uploads">
**React**

  ```tsx
  import { PromptComposer } from "@/components/keyframery/prompt-composer"

  /* Stands in for your upload: reports progress, then resolves. */
  function upload(_file: File, { onProgress, signal }: { onProgress: (percent: number) => void; signal: AbortSignal }) {
    return new Promise<void>((resolve, reject) => {
      let percent = 0
      const tick = setInterval(() => {
        percent += 20
        onProgress(percent)
        if (percent >= 100) {
          clearInterval(tick)
          resolve()
        }
      }, 300)
      signal.addEventListener("abort", () => {
        clearInterval(tick)
        reject(signal.reason)
      })
    })
  }

  export default function PromptComposerUploads() {
    return <PromptComposer className="max-w-[480px]" accept="image/*,.pdf" maxFiles={4} upload={upload} maxLength={2000} placeholder="Describe the problem and attach a photo" />
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { PromptComposer } from "@/components/keyframery/prompt-composer"

  /* Stands in for your upload: reports progress, then resolves. */
  function upload(_file: File, { onProgress, signal }: { onProgress: (percent: number) => void; signal: AbortSignal }) {
    return new Promise<void>((resolve, reject) => {
      let percent = 0
      const tick = setInterval(() => {
        percent += 20
        onProgress(percent)
        if (percent >= 100) {
          clearInterval(tick)
          resolve()
        }
      }, 300)
      signal.addEventListener("abort", () => {
        clearInterval(tick)
        reject(signal.reason)
      })
    })
  }
  </script>

  <template>
    <PromptComposer
      class="max-w-[480px]"
      accept="image/*,.pdf"
      :max-files="4"
      :upload="upload"
      :max-length="2000"
      placeholder="Describe the problem and attach a photo"
    />
  </template>
  ```
</ExamplePreview>

## Motion [#motion]

| Move          | What you see                                                                                                                                         |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Fade**      | Send, the spinner and Stop cross-fade in place as the status changes; with more motion they also turn and blur through the swap and land with a pop. |
| **Press**     | Send, Stop and the toolbar buttons give under the pointer and spring back on release.                                                                |
| **Height**    | The row of files opens to its height when the first file arrives and closes as the last one leaves, so the text moves instead of jumping.            |
| **Pop**       | Each file pops in from smaller, its upload line fills along its foot, and it shrinks away when removed while the files after it close the gap.       |
| **Unfold**    | The suggestions unfold from the caret, their rows cascade in, and one highlight glides between them as you arrow through.                            |
| **Rise**      | While files are dragged over the box, a drop layer fades in over it and its label rises; the box leans toward the files.                             |
| **Direction** | The model picker's choice rises into place, and on a phone the models open as a sheet from the bottom.                                               |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this prompt composer moves, pass `speed`:

```tsx
<PromptComposer speed="fast">
  …
</PromptComposer>
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable                    | What it changes | Default                     |
| --------------------------- | --------------- | --------------------------- |
| `--prompt-composer-face`    | Box surface     | --background (dark: --card) |
| `--prompt-composer-ink`     | Message text    | --foreground                |
| `--prompt-composer-send`    | Send button     | --primary                   |
| `--prompt-composer-radius`  | Box corners     | 18px                        |
| `--prompt-composer-font`    | Message size    | 14px                        |
| `--prompt-composer-padding` | Box padding     | 0.5rem                      |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### PromptComposer [#promptcomposer]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast the component moves. `\&#x22;fast\&#x22;` (0.6×), `\&#x22;normal\&#x22;` (1×), `\&#x22;slow\&#x22;` (1.4×), or a multiplier like `0.8`. Popups follow it too.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onValueChange&#x22;,&#x22;type&#x22;:&#x22;(value: string) => void&#x22;,&#x22;full&#x22;:&#x22;(value: string) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onSubmit&#x22;,&#x22;type&#x22;:&#x22;(message: PromptComposerSubmit) => void&#x22;,&#x22;full&#x22;:&#x22;(message: PromptComposerSubmit) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Called with { text, attachments, model } when Send is pressed, a send key is used or an agent submits. The composer empties itself afterwards.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onStop&#x22;,&#x22;type&#x22;:&#x22;() => void&#x22;,&#x22;full&#x22;:&#x22;() => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Called when Stop is pressed while a reply is on its way.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;status&#x22;,&#x22;type&#x22;:&#x22;\&#x22;error\&#x22; | \&#x22;streaming\&#x22; | \&#x22;ready\&#x22; | \&#x22;submitted\&#x22;&#x22;,&#x22;full&#x22;:&#x22;PromptComposerStatus&#x22;,&#x22;default&#x22;:&#x22;\&#x22;ready\&#x22;&#x22;,&#x22;description&#x22;:&#x22;\&#x22;ready\&#x22;, \&#x22;submitted\&#x22; (Send shows a spinner), \&#x22;streaming\&#x22; (Send becomes Stop) or \&#x22;error\&#x22; (shows errorMessage).&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;submitOn&#x22;,&#x22;type&#x22;:&#x22;\&#x22;enter\&#x22; | \&#x22;mod+enter\&#x22;&#x22;,&#x22;full&#x22;:&#x22;PromptComposerSubmitOn&#x22;,&#x22;default&#x22;:&#x22;\&#x22;enter\&#x22;&#x22;,&#x22;description&#x22;:&#x22;\&#x22;enter\&#x22; (Shift+Enter for a new line) or \&#x22;mod+enter\&#x22; (Enter for a new line). Cmd/Ctrl+Enter always sends.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;models&#x22;,&#x22;type&#x22;:&#x22;PromptComposerModel[]&#x22;,&#x22;full&#x22;:&#x22;PromptComposerModel[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Shows a model picker: { value, label, description? }. Use model, defaultModel and onModelChange to control it.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;model&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultModel&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onModelChange&#x22;,&#x22;type&#x22;:&#x22;(model: string) => void&#x22;,&#x22;full&#x22;:&#x22;(model: string) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;mentions&#x22;,&#x22;type&#x22;:&#x22;PromptComposerItem[]&#x22;,&#x22;full&#x22;:&#x22;PromptComposerItem[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Items @ suggests: { value, label, description?, icon?, group?, keywords? }. Choosing one inserts @ and its label.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;commands&#x22;,&#x22;type&#x22;:&#x22;PromptComposerItem[]&#x22;,&#x22;full&#x22;:&#x22;PromptComposerItem[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Items / suggests at the start of the message, in the same shape as mentions.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;accept&#x22;,&#x22;type&#x22;:&#x22;string | false&#x22;,&#x22;full&#x22;:&#x22;string | false&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Which files can be attached, like \&#x22;image/*,.pdf\&#x22;. false hides the paperclip and turns off drops and pastes.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;maxFiles&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The most files at once.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;upload&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(file: File, context: UploadContext) => Promise<void>&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;(file, { onProgress, signal }) => Promise. Each file uploads as soon as it is attached; Send waits for it.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;maxRows&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:&#x22;8&#x22;,&#x22;description&#x22;:&#x22;How many lines the message grows to before it scrolls. Default 8.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;maxLength&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The longest message.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;counter&#x22;,&#x22;type&#x22;:&#x22;\&#x22;none\&#x22; | \&#x22;characters\&#x22; | \&#x22;tokens\&#x22;&#x22;,&#x22;full&#x22;:&#x22;\&#x22;none\&#x22; | \&#x22;characters\&#x22; | \&#x22;tokens\&#x22;&#x22;,&#x22;default&#x22;:&#x22;\&#x22;characters\&#x22;&#x22;,&#x22;description&#x22;:&#x22;\&#x22;characters\&#x22;, \&#x22;tokens\&#x22; (an estimate) or \&#x22;none\&#x22;. With maxLength the count reads against the limit.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;actions&#x22;,&#x22;type&#x22;:&#x22;ReactNode&#x22;,&#x22;full&#x22;:&#x22;ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Your own buttons, placed after attach and the model picker.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;errorMessage&#x22;,&#x22;type&#x22;:&#x22;ReactNode&#x22;,&#x22;full&#x22;:&#x22;ReactNode&#x22;,&#x22;default&#x22;:&#x22;\&#x22;Something went wrong. Send it again.\&#x22;&#x22;,&#x22;description&#x22;:&#x22;Shown in the toolbar while `status` is \&#x22;error\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;inputRef&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;((instance: HTMLTextAreaElement | null) => void | (() => void | { [UNDEFINED_VOID_ONLY]: never; }) | React.DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES[keyof React.DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES]) | React.RefObject<HTMLTextAreaElement | null>&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Reaches the text field, for a controller or focus.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;menuController&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;{ isOpen: () => boolean; setOpen: (open: boolean, options?: TriggerMenuChangeOptions<TriggerMenuOpenChangeReason>) => boolean; open: (options?: TriggerMenuChangeOptions<TriggerMenuOpenChangeReason> & { trigger?: string; signal?: AbortSignal; }) => Promise<PopupResult<TriggerMenuOpenChangeReason, never>>; close: (options?: TriggerMenuChangeOptions<TriggerMenuOpenChangeReason>) => boolean; getQuery: () => string; getMatch: () => TriggerMatch | null; insert: (content: string | TokenInsert) => void; focus: () => void; }&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A controller from createPromptComposerMenuController, to open @ or / from a button.&#x22;,&#x22;required&#x22;:false}]" />

### PromptComposerCount [#promptcomposercount]

Renders a `<span>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;near&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;over&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false}]" />

### PromptComposerDropzone [#promptcomposerdropzone]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;target&#x22;,&#x22;type&#x22;:&#x22;\&#x22;document\&#x22; | \&#x22;element\&#x22;&#x22;,&#x22;full&#x22;:&#x22;FileInputDropzoneTarget&#x22;,&#x22;default&#x22;:&#x22;\&#x22;element\&#x22;&#x22;,&#x22;description&#x22;:&#x22;Where it takes drops. `\&#x22;document\&#x22;` takes files dropped anywhere on the page, and the zone shows `data-dragging` while files are over the window, so it can be a full-page overlay.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;pasteTarget&#x22;,&#x22;type&#x22;:&#x22;string | Element | (() => Element | null)&#x22;,&#x22;full&#x22;:&#x22;string | Element | (() => Element | null)&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Somewhere else to take pasted files from, on top of pastes while focus is inside the zone: `\&#x22;document\&#x22;`, an element, a CSS selector, or a function that returns an element, like a prompt's text area. Text pastes are left alone.&#x22;,&#x22;required&#x22;:false}]" />

### PromptComposerInput [#promptcomposerinput]

Renders a `<textarea>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;value&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The value, for a controlled field.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultValue&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The value it starts with. A form reset returns here.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onValueChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(value: string, details: ChangeDetails<InputValueChangeReason>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Called when the user changes the value: typing (`\&#x22;input-change\&#x22;`), a Clear part (`\&#x22;clear-press\&#x22;`), a form reset (`\&#x22;reset\&#x22;`) or a controller (`\&#x22;imperative\&#x22;`). `details.cancel()` keeps the value as it was.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;controller&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;{ getValue: () => string; setValue: (value: string, options?: ChangeOptions<InputValueChangeReason>) => boolean; clear: (options?: ChangeOptions<InputValueChangeReason>) => boolean; focus: () => void; }&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Reads and writes the field from anywhere. Create one with `createInputController()`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;autoResize&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;false&#x22;,&#x22;description&#x22;:&#x22;Grows and shrinks with the text. Bound it with CSS `min-height` and `max-height`; past the maximum, it scrolls.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onSubmit&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(value: string, details: TextareaSubmitDetails) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Runs on the submit shortcut, unless an input method is composing. Without it, the shortcut submits the form the textarea is in. With neither, the key is left alone, so Enter adds a line.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;submitShortcut&#x22;,&#x22;type&#x22;:&#x22;\&#x22;enter\&#x22; | \&#x22;mod+enter\&#x22;&#x22;,&#x22;full&#x22;:&#x22;\&#x22;enter\&#x22; | \&#x22;mod+enter\&#x22;&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Which keys submit: `\&#x22;enter\&#x22;`, with Shift+Enter for a new line, or `\&#x22;mod+enter\&#x22;`, with Enter for a new line. Without it, Enter always starts a new line.&#x22;,&#x22;required&#x22;:false}]" />

### PromptComposerSend [#promptcomposersend]

Renders a `<button>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;pendingIndicator&#x22;,&#x22;type&#x22;:&#x22;ReactNode&#x22;,&#x22;full&#x22;:&#x22;ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;What rises in while the button is pending. Defaults to a spinner; pass `null` for none.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;focusableWhenDisabled&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;false&#x22;,&#x22;description&#x22;:&#x22;Keeps a disabled button in the tab order with `aria-disabled` instead of the native attribute, so it can hold focus while it becomes disabled and host a tooltip that says why. Presses still do nothing.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;type&#x22;,&#x22;type&#x22;:&#x22;\&#x22;button\&#x22; | \&#x22;reset\&#x22; | \&#x22;submit\&#x22;&#x22;,&#x22;full&#x22;:&#x22;\&#x22;button\&#x22; | \&#x22;reset\&#x22; | \&#x22;submit\&#x22;&#x22;,&#x22;default&#x22;:&#x22;\&#x22;button\&#x22;&#x22;,&#x22;description&#x22;:&#x22;What a native button does in a form: `\&#x22;submit\&#x22;` submits it and `\&#x22;reset\&#x22;` resets it. Ignored when the button renders as something else.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;pendingAnnouncement&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:&#x22;\&#x22;Loading\&#x22;&#x22;,&#x22;description&#x22;:&#x22;What screen readers hear once the button has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onClick&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(event: React.MouseEvent<HTMLElement>, details: ButtonActionDetails) => unknown&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Runs when the button is pressed. Return a Promise to make the button pending until it settles: it gets `aria-busy`, `aria-disabled` and `data-pending`, keeps focus, ignores presses meanwhile, so a form can't submit twice, and says `pendingAnnouncement` after a second. The event's element is whatever `render` renders, like a link. `details.source` says how it was pressed, for changes made after an `await`.&#x22;,&#x22;required&#x22;:false}]" />

### Other parts [#other-parts]

These take the props of the element they render, and nothing else:

* `PromptComposerAttachments`: a `<div>`
* `PromptComposerDrop`: a `<div>`
* `PromptComposerToolbar`: a `<div>`

## Keyboard [#keyboard]

| Key                                | What it does                                                                                                                                                                             |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <kbd>Enter</kbd>                   | Sends the message. With submitOn="mod+enter" it starts a new line instead. While suggestions are open, it inserts the highlighted one. Nothing sends while an input method is composing. |
| <kbd>Shift+Enter</kbd>             | Starts a new line.                                                                                                                                                                       |
| <kbd>Cmd+Enter or Ctrl+Enter</kbd> | Always sends.                                                                                                                                                                            |
| <kbd>@ or /</kbd>                  | Opens mentions at the caret, or commands at the start of the message.                                                                                                                    |
| <kbd>ArrowDown, ArrowUp</kbd>      | Move through the open suggestions; Tab or Enter inserts one, Escape closes them.                                                                                                         |
| <kbd>Tab</kbd>                     | Moves from the message to attach, the model, your actions and Send.                                                                                                                      |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a prompt composer, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/prompt-composer-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/prompt-composer`.

## Questions

### How does the animated Prompt Composer for UI SDK move?

Fade: Send, the spinner and Stop cross-fade in place as the status changes; with more motion they also turn and blur through the swap and land with a pop. Press: Send, Stop and the toolbar buttons give under the pointer and spring back on release. Height: The row of files opens to its height when the first file arrives and closes as the last one leaves, so the text moves instead of jumping. Pop: Each file pops in from smaller, its upload line fills along its foot, and it shrinks away when removed while the files after it close the gap. Unfold: The suggestions unfold from the caret, their rows cascade in, and one highlight glides between them as you arrow through. Rise: While files are dragged over the box, a drop layer fades in over it and its label rises; the box leans toward the files. Direction: The model picker's choice rises into place, and on a phone the models open as a sheet from the bottom.

### Do I need Motion or Framer Motion for the animated Prompt Composer?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no prompt composer. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/prompt-composer-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Prompt Composer when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
