{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "composer",
  "type": "registry:ui",
  "title": "Composer",
  "description": "The box a person writes a message in: a field that grows with the text, a list of attachments, and a toolbar with slots for an attach button, a voice button and send (which becomes stop while a reply is on its way).",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react",
    "radix-ui"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chip",
    "@rivier-ui/cn",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/composer.tsx",
      "type": "registry:ui",
      "target": "components/ui/composer.tsx",
      "content": "\"use client\";\n/**\n * @name composer\n * @category ui\n * @description The box a person writes a message in: a field that grows with the text, a list of attachments, and a toolbar with slots for an attach button, a voice button and send (which becomes stop while a reply is on its way).\n * @when Under a thread, or anywhere a person sends free text to an assistant or to other people. It owns the text and the keys (Enter sends, Shift+Enter makes a new line, nothing is sent while an input method is composing); the project owns the files, the microphone and the sending. For one line with no attachments (a search box) use input-group; for a long form field use textarea.\n * @example\n * <Composer onSubmit={send} busy={replying} onStop={stop}>\n *   <ComposerAttachments aria-label=\"Attachments\">\n *     {files.map((file) => (\n *       <ComposerAttachment key={file.name} onRemove={() => remove(file)} removeLabel={`Remove ${file.name}`}>{file.name}</ComposerAttachment>\n *     ))}\n *   </ComposerAttachments>\n *   <ComposerInput aria-label=\"Message\" placeholder=\"Ask anything\" />\n *   <ComposerToolbar>\n *     <ComposerAttachButton aria-label=\"Attach a file\" onFiles={add} accept=\"image/*\" multiple />\n *     <ComposerVoiceButton pressed={listening} onPressedChange={setListening} />\n *     <ComposerSubmit />\n *   </ComposerToolbar>\n * </Composer>\n */\nimport { Toggle as TogglePrimitive } from \"radix-ui\";\nimport { ArrowUp, AudioLines, Mic, Paperclip, Square } from \"lucide-react\";\nimport {\n  createContext,\n  use,\n  useId,\n  useLayoutEffect,\n  useRef,\n  type ChangeEvent,\n  type ComponentProps,\n  type FormEvent,\n  type KeyboardEvent,\n  type ReactNode,\n  type RefObject,\n} from \"react\";\nimport { Chip, ChipRemove } from \"@/components/ui/chip\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\ntype ComposerContextValue = {\n  value: string;\n  setValue: (value: string) => void;\n  disabled: boolean;\n  busy: boolean;\n  /** Whether there is something to send and sending is allowed. */\n  canSubmit: boolean;\n  submit: () => void;\n  stop: () => void;\n  inputRef: RefObject<HTMLTextAreaElement | null>;\n};\n\nconst ComposerContext = createContext<ComposerContextValue | null>(null);\n\nfunction useComposerContext(part: string): ComposerContextValue {\n  const context = use(ComposerContext);\n  if (!context) throw new Error(`<${part}> must be used inside <Composer>.`);\n  return context;\n}\n\n/** The composer's text and actions, for a project's own part (a character count, a custom send control). */\nexport function useComposer(): Pick<ComposerContextValue, \"value\" | \"setValue\" | \"disabled\" | \"busy\" | \"canSubmit\" | \"submit\" | \"stop\"> {\n  const { value, setValue, disabled, busy, canSubmit, submit, stop } = useComposerContext(\"useComposer\");\n  return { value, setValue, disabled, busy, canSubmit, submit, stop };\n}\n\nexport type ComposerProps = Omit<ComponentProps<\"form\">, \"onSubmit\" | \"defaultValue\"> & {\n  /** The controlled text. */\n  value?: string;\n  /** The starting text when uncontrolled. */\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Called with the trimmed text when the person sends. The field is then cleared (see `clearOnSubmit`) and takes focus again. */\n  onSubmit?: (text: string) => void;\n  /** A reply is on its way: send becomes stop, and Enter does not send. The person can keep typing. */\n  busy?: boolean;\n  /** Called when the person presses stop while `busy`. */\n  onStop?: () => void;\n  disabled?: boolean;\n  /** Empty the field after sending. Default true. Turn it off to clear it yourself once the message is accepted. */\n  clearOnSubmit?: boolean;\n  /** Allow sending with no text: set it when there are attachments to send. */\n  allowEmpty?: boolean;\n};\n\n/**\n * A form. It looks like one field: the border and the focus ring are on the frame, and the parts inside\n * have none of their own. After sending, focus goes back to the field, so the person can keep writing.\n */\nexport function Composer({\n  className,\n  value,\n  defaultValue = \"\",\n  onValueChange,\n  onSubmit,\n  busy = false,\n  onStop,\n  disabled = false,\n  clearOnSubmit = true,\n  allowEmpty = false,\n  children,\n  ...props\n}: ComposerProps) {\n  const [text, setText] = useControllableState({ value, defaultValue, onChange: onValueChange });\n  const inputRef = useRef<HTMLTextAreaElement>(null);\n  const canSubmit = !disabled && !busy && (allowEmpty || text.trim() !== \"\");\n\n  const submit = (): void => {\n    if (!canSubmit) return;\n    onSubmit?.(text.trim());\n    if (clearOnSubmit) setText(\"\");\n    inputRef.current?.focus();\n  };\n\n  return (\n    <ComposerContext value={{ value: text, setValue: setText, disabled, busy, canSubmit, submit, stop: () => onStop?.(), inputRef }}>\n      <form\n        data-slot=\"composer\"\n        data-busy={busy ? \"\" : undefined}\n        data-disabled={disabled ? \"\" : undefined}\n        aria-busy={busy || undefined}\n        onSubmit={(event: FormEvent<HTMLFormElement>) => {\n          event.preventDefault();\n          submit();\n        }}\n        className={cn(\n          \"flex w-full min-w-0 flex-col gap-1 rounded-surface border border-input bg-background p-2 text-foreground has-[textarea:focus-visible]:outline-2 has-[textarea:focus-visible]:outline-offset-2 has-[textarea:focus-visible]:outline-ring data-[disabled]:opacity-50\",\n          className,\n        )}\n        {...props}\n      >\n        {children}\n      </form>\n    </ComposerContext>\n  );\n}\n\nexport type ComposerInputProps = Omit<ComponentProps<\"textarea\">, \"value\" | \"defaultValue\" | \"rows\"> & {\n  /** The most lines it grows to before it scrolls inside. Default 8. */\n  maxRows?: number;\n  /** Enter sends (default). Turn it off where Enter should always make a new line; the send button still works. */\n  submitOnEnter?: boolean;\n};\n\n/**\n * The field. It starts one line tall and grows with what is typed, up to `maxRows`, then scrolls.\n * `dir=\"auto\"` lets a message in a right-to-left language read correctly whatever the page's direction.\n * Name it with `aria-label` (default \"Message\") or a label; a placeholder is not a name.\n */\nexport function ComposerInput({ className, maxRows = 8, submitOnEnter = true, onKeyDown, onChange, \"aria-label\": ariaLabel, \"aria-labelledby\": ariaLabelledBy, ...props }: ComposerInputProps) {\n  const { value, setValue, disabled, canSubmit, submit, inputRef } = useComposerContext(\"ComposerInput\");\n\n  // Fit the height to the text. Read and written in one pass before paint, so the field never flickers.\n  useLayoutEffect(() => {\n    const field = inputRef.current;\n    if (!field) return;\n    const fit = (): void => {\n      const style = getComputedStyle(field);\n      const line = parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.5;\n      const frame = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom) + parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);\n      const limit = line * maxRows + frame;\n      field.style.height = \"auto\";\n      const wanted = field.scrollHeight + parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);\n      field.style.height = `${Math.min(wanted, limit)}px`;\n      field.style.overflowY = wanted > limit ? \"auto\" : \"hidden\";\n    };\n    fit();\n    if (typeof ResizeObserver === \"undefined\") return;\n    // A narrower field wraps onto more lines.\n    let width = field.clientWidth;\n    const observer = new ResizeObserver(() => {\n      if (field.clientWidth === width) return;\n      width = field.clientWidth;\n      fit();\n    });\n    observer.observe(field);\n    return () => observer.disconnect();\n  }, [value, maxRows, inputRef]);\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>): void => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented || event.key !== \"Enter\" || !submitOnEnter) return;\n    // Enter that confirms a choice in an input method (Japanese, Chinese, Korean) is not \"send\". 229 is what older browsers report.\n    if (event.shiftKey || event.altKey || event.nativeEvent.isComposing || event.keyCode === 229) return;\n    event.preventDefault();\n    if (canSubmit) submit();\n  };\n\n  return (\n    <textarea\n      ref={inputRef}\n      data-slot=\"composer-input\"\n      dir=\"auto\"\n      rows={1}\n      aria-label={ariaLabel ?? (ariaLabelledBy ? undefined : \"Message\")}\n      aria-labelledby={ariaLabelledBy}\n      enterKeyHint={submitOnEnter ? \"send\" : \"enter\"}\n      disabled={disabled}\n      value={value}\n      onChange={(event: ChangeEvent<HTMLTextAreaElement>) => {\n        onChange?.(event);\n        setValue(event.target.value);\n      }}\n      onKeyDown={handleKeyDown}\n      className={cn(\n        \"block w-full min-w-0 resize-none bg-transparent px-2 py-1.5 text-base leading-normal text-foreground outline-none placeholder:text-muted-foreground disabled:pointer-events-none\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\n/**\n * The files to be sent with the message, as a named list above the field. The project owns the files: it\n * renders one ComposerAttachment for each. Render it only when there is something in it (an empty list is\n * announced as \"list, 0 items\").\n */\nexport function ComposerAttachments({ className, \"aria-label\": ariaLabel = \"Attachments\", ...props }: ComponentProps<\"ul\">) {\n  return <ul data-slot=\"composer-attachments\" aria-label={ariaLabel} className={cn(\"flex max-w-full flex-wrap gap-2 px-1 pt-1 pb-1.5\", className)} {...props} />;\n}\n\nexport type ComposerAttachmentProps = ComponentProps<\"li\"> & {\n  /** Removes this file. Leave it out for a file that cannot be removed. */\n  onRemove?: () => void;\n  /** The remove button's name: say which file (\"Remove plan.pdf\"). */\n  removeLabel?: string;\n};\n\n/** One file: a chip with its name (and a small picture or icon before it, if you like) and a cross to remove it. */\nexport function ComposerAttachment({ className, onRemove, removeLabel = \"Remove\", children, ...props }: ComposerAttachmentProps) {\n  const { inputRef } = useComposerContext(\"ComposerAttachment\");\n  return (\n    <li data-slot=\"composer-attachment\" className={cn(\"flex max-w-full min-w-0\", className)} {...props}>\n      <Chip variant=\"muted\" className=\"min-w-0 shrink\">\n        <span className=\"inline-flex min-w-0 items-center gap-1.5 truncate\">{children}</span>\n        {onRemove ? (\n          <ChipRemove\n            aria-label={removeLabel}\n            onClick={() => {\n              onRemove();\n              // The chip is about to go: keep focus in the composer.\n              inputRef.current?.focus();\n            }}\n          />\n        ) : null}\n      </Chip>\n    </li>\n  );\n}\n\n/** The row under the field. Controls gather at the start; ComposerSubmit pushes itself to the end. */\nexport function ComposerToolbar({ className, ...props }: ComponentProps<\"div\">) {\n  return <div data-slot=\"composer-toolbar\" className={cn(\"flex min-w-0 items-center gap-1\", className)} {...props} />;\n}\n\nconst toolButton =\n  \"inline-flex size-(--control-h) shrink-0 items-center justify-center rounded-control text-muted-foreground transition-[background-color,color,opacity] duration-instant ease-out hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0\";\n\nexport type ComposerAttachButtonProps = Omit<ComponentProps<\"button\">, \"type\"> & {\n  /** Given the files the person picked. When set, the button opens the device's file picker; when not, handle `onClick` and open your own. */\n  onFiles?: (files: File[]) => void;\n  /** File types the picker offers (\"image/*,.pdf\"). */\n  accept?: string;\n  /** Let the person pick several files. */\n  multiple?: boolean;\n};\n\n/** Opens a file picker. An icon button, so it needs a name: `aria-label`, \"Attach a file\" by default. */\nexport function ComposerAttachButton({ className, children, onFiles, accept, multiple, onClick, disabled, \"aria-label\": ariaLabel = \"Attach a file\", ...props }: ComposerAttachButtonProps) {\n  const context = useComposerContext(\"ComposerAttachButton\");\n  const fileRef = useRef<HTMLInputElement>(null);\n  return (\n    <>\n      <button\n        type=\"button\"\n        data-slot=\"composer-attach-button\"\n        aria-label={ariaLabel}\n        disabled={disabled ?? context.disabled}\n        onClick={(event) => {\n          onClick?.(event);\n          if (!event.defaultPrevented && onFiles) fileRef.current?.click();\n        }}\n        className={cn(toolButton, className)}\n        {...props}\n      >\n        {children ?? <Paperclip aria-hidden=\"true\" strokeWidth={1.5} />}\n      </button>\n      {onFiles ? (\n        <input\n          ref={fileRef}\n          type=\"file\"\n          hidden\n          tabIndex={-1}\n          aria-hidden=\"true\"\n          accept={accept}\n          multiple={multiple}\n          onChange={(event) => {\n            const files = [...(event.target.files ?? [])];\n            // Cleared, so that picking the same file again still reports a change.\n            event.target.value = \"\";\n            if (files.length > 0) onFiles(files);\n          }}\n        />\n      ) : null}\n    </>\n  );\n}\n\nexport type ComposerVoiceButtonProps = Omit<ComponentProps<typeof TogglePrimitive.Root>, \"children\"> & {\n  /** The button's name. It stays the same in both states; the state is carried by `aria-pressed` and the words below. */\n  label?: string;\n  /** The state in words, for screen readers and beside the icon while listening. Translate them with the interface. */\n  stateLabels?: { idle?: string; listening?: string };\n  /** The icons for each state, when the defaults (a microphone, sound lines) are not wanted. */\n  icons?: { idle?: ReactNode; listening?: ReactNode };\n};\n\n/**\n * A toggle for voice input. The project owns the microphone: this only shows and switches the state\n * (`pressed`, `defaultPressed`, `onPressedChange`). While listening it changes its ground, its icon and\n * shows the word, so the state is never carried by colour alone.\n */\nexport function ComposerVoiceButton({ className, label = \"Voice input\", stateLabels, icons, disabled, pressed, defaultPressed = false, onPressedChange, ...props }: ComposerVoiceButtonProps) {\n  const context = useComposerContext(\"ComposerVoiceButton\");\n  const [listening, setListening] = useControllableState({ value: pressed, defaultValue: defaultPressed, onChange: onPressedChange });\n  const stateId = useId();\n  const state = listening ? (stateLabels?.listening ?? \"Listening\") : (stateLabels?.idle ?? \"Not listening\");\n  return (\n    <>\n      <TogglePrimitive.Root\n        data-slot=\"composer-voice-button\"\n        aria-label={label}\n        aria-describedby={stateId}\n        pressed={listening}\n        onPressedChange={setListening}\n        disabled={disabled ?? context.disabled}\n        className={cn(toolButton, \"data-[state=on]:bg-primary data-[state=on]:text-primary-foreground data-[state=on]:hover:opacity-90\", className)}\n        {...props}\n      >\n        {listening ? (icons?.listening ?? <AudioLines aria-hidden=\"true\" strokeWidth={1.5} />) : (icons?.idle ?? <Mic aria-hidden=\"true\" strokeWidth={1.5} />)}\n      </TogglePrimitive.Root>\n      <span id={stateId} data-slot=\"composer-voice-state\" className={cn(\"truncate text-sm text-muted-foreground\", !listening && \"sr-only\")}>\n        {state}\n      </span>\n    </>\n  );\n}\n\nexport type ComposerSubmitProps = Omit<ComponentProps<\"button\">, \"type\" | \"children\"> & {\n  /** The names of the two states. Translate them with the interface. */\n  labels?: { send?: string; stop?: string };\n  /** The icons of the two states. */\n  icons?: { send?: ReactNode; stop?: ReactNode };\n};\n\n/**\n * Send, or stop while a reply is on its way. One button that changes its name and icon, so focus stays on\n * it through the change. Send is disabled while there is nothing to send.\n */\nexport function ComposerSubmit({ className, labels, icons, onClick, ...props }: ComposerSubmitProps) {\n  const { busy, canSubmit, disabled, stop } = useComposerContext(\"ComposerSubmit\");\n  return (\n    <button\n      type={busy ? \"button\" : \"submit\"}\n      data-slot=\"composer-submit\"\n      data-state={busy ? \"stop\" : \"send\"}\n      aria-label={busy ? (labels?.stop ?? \"Stop\") : (labels?.send ?? \"Send\")}\n      disabled={busy ? disabled : !canSubmit}\n      onClick={(event) => {\n        onClick?.(event);\n        if (busy && !event.defaultPrevented) {\n          event.preventDefault();\n          stop();\n        }\n      }}\n      className={cn(\n        \"ms-auto inline-flex size-(--control-h) shrink-0 items-center justify-center rounded-control bg-primary text-primary-foreground transition-[opacity,scale] duration-instant ease-out hover:opacity-90 active:scale-[0.98] disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none motion-reduce:active:scale-100 [&_svg]:size-4 [&_svg]:shrink-0\",\n        className,\n      )}\n      {...props}\n    >\n      {busy ? (icons?.stop ?? <Square aria-hidden=\"true\" strokeWidth={1.5} className=\"fill-current\" />) : (icons?.send ?? <ArrowUp aria-hidden=\"true\" strokeWidth={2} />)}\n    </button>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Under a thread, or anywhere a person sends free text to an assistant or to other people. It owns the text and the keys (Enter sends, Shift+Enter makes a new line, nothing is sent while an input method is composing); the project owns the files, the microphone and the sending. For one line with no attachments (a search box) use input-group; for a long form field use textarea.",
    "example": "<Composer onSubmit={send} busy={replying} onStop={stop}>\n  <ComposerAttachments aria-label=\"Attachments\">\n    {files.map((file) => (\n      <ComposerAttachment key={file.name} onRemove={() => remove(file)} removeLabel={`Remove ${file.name}`}>{file.name}</ComposerAttachment>\n    ))}\n  </ComposerAttachments>\n  <ComposerInput aria-label=\"Message\" placeholder=\"Ask anything\" />\n  <ComposerToolbar>\n    <ComposerAttachButton aria-label=\"Attach a file\" onFiles={add} accept=\"image/*\" multiple />\n    <ComposerVoiceButton pressed={listening} onPressedChange={setListening} />\n    <ComposerSubmit />\n  </ComposerToolbar>\n</Composer>",
    "client": true
  }
}
