{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"ai-chat-composer","title":"AI Chat Composer","description":"A message composer for AI chats: one row with actions around the text that opens into a column once the text wraps or attachments are added, with an expand action and a send button.","dependencies":["@base-ui/react","cn","lucide-react"],"registryDependencies":["@sortui/button","@sortui/spinner"],"files":[{"path":"components/ui/ai-chat-composer.tsx","content":"\"use client\"\n\nimport * as React from \"react\"\nimport {\n  ArrowUpIcon,\n  MaximizeIcon,\n  AudioLinesIcon,\n  MinimizeIcon,\n  SquareIcon,\n  XIcon,\n} from \"lucide-react\"\nimport { Popover as PopoverPrimitive } from \"@base-ui/react/popover\"\nimport { cn } from \"cn\"\n\nimport { Button } from \"@/components/ui/button\"\nimport { Spinner } from \"@/components/ui/spinner\"\n\nconst EXPAND_FROM_LINE = 5\nconst WAVEFORM_BARS = 64\nconst LOUD_BAR_HEIGHT = 8\nconst WAVEFORM_INTERVAL = 60\nconst MIN_TRANSCRIBING_TIME = 2000\n\ntype AIChatComposerContextValue = {\n  rootRef: React.RefObject<HTMLDivElement | null>\n  textareaRef: React.RefObject<HTMLTextAreaElement | null>\n  multiline: boolean\n  setMultiline: (multiline: boolean) => void\n  maximized: boolean\n  setMaximized: (maximized: boolean) => void\n  setEmpty: (empty: boolean) => void\n  dictation: Dictation\n}\n\nconst AIChatComposerContext =\n  React.createContext<AIChatComposerContextValue | null>(null)\n\nfunction useAIChatComposer() {\n  const context = React.useContext(AIChatComposerContext)\n  if (!context) {\n    throw new Error(\"AIChatComposer parts must be used within AIChatComposer.\")\n  }\n  return context\n}\n\nfunction assignRefs<T>(node: T | null, refs: (React.Ref<T> | undefined)[]) {\n  const cleanups = refs.map((ref) => {\n    if (typeof ref === \"function\") {\n      const cleanup = ref(node)\n      return typeof cleanup === \"function\" ? cleanup : () => ref(null)\n    }\n    if (ref) ref.current = node\n    return () => {\n      if (ref) ref.current = null\n    }\n  })\n  return () => cleanups.forEach((cleanup) => cleanup())\n}\n\nfunction isSubmitButton(\n  element: Element\n): element is HTMLButtonElement | HTMLInputElement {\n  return (\n    (element instanceof HTMLButtonElement ||\n      element instanceof HTMLInputElement) &&\n    (element.type === \"submit\" || element.type === \"image\")\n  )\n}\n\nfunction submitForm(form: HTMLFormElement) {\n  const button = Array.from(form.elements).find(isSubmitButton)\n  if (button?.matches(\":disabled, [aria-disabled='true']\")) return\n  form.requestSubmit(button)\n}\n\nfunction insertText(\n  textarea: HTMLTextAreaElement,\n  text: string,\n  start = textarea.selectionStart,\n  end = textarea.selectionEnd\n) {\n  const before = textarea.value.slice(0, start)\n  const after = textarea.value.slice(end)\n  const lead = before === \"\" || /\\s$/.test(before) ? \"\" : \" \"\n  const trail = /^\\s/.test(after) ? \"\" : \" \"\n  textarea.focus()\n  textarea.setRangeText(lead + text + trail, start, end, \"end\")\n  textarea.dispatchEvent(new Event(\"input\", { bubbles: true }))\n}\n\n/** Inserts a token (such as \"/release-notes\") at the caret of a textarea. */\nfunction insertAIChatComposerToken(\n  textarea: HTMLTextAreaElement | null,\n  token: string\n) {\n  if (textarea) insertText(textarea, token)\n}\n\nfunction availableHeight(element: HTMLElement) {\n  for (let node = element.parentElement; node; node = node.parentElement) {\n    if (node === document.body || node === document.documentElement) break\n    const style = getComputedStyle(node)\n    if (style.overflowY === \"visible\") continue\n    return Math.min(\n      node.clientHeight -\n        parseFloat(style.paddingTop) -\n        parseFloat(style.paddingBottom),\n      window.innerHeight\n    )\n  }\n  return window.innerHeight\n}\n\ntype SpeechRecognitionInstance = {\n  continuous: boolean\n  interimResults: boolean\n  lang: string\n  processLocally?: boolean\n  onerror: ((event: { error: string }) => void) | null\n  onresult:\n    | ((event: {\n        results: ArrayLike<ArrayLike<{ transcript: string }>>\n      }) => void)\n    | null\n  onend: (() => void) | null\n  start: () => void\n  stop: () => void\n  abort: () => void\n}\n\ntype SpeechRecognitionConstructor = (new () => SpeechRecognitionInstance) & {\n  available?: (options: {\n    langs: string[]\n    processLocally: boolean\n  }) => Promise<string>\n}\n\nfunction getSpeechRecognition(): SpeechRecognitionConstructor | undefined {\n  if (typeof window === \"undefined\") return undefined\n  const scope = window as unknown as Record<string, unknown>\n  return (scope.SpeechRecognition ?? scope.webkitSpeechRecognition) as\n    SpeechRecognitionConstructor | undefined\n}\n\nfunction subscribeNever() {\n  return () => {}\n}\n\nasync function hasOnDeviceModel(\n  Recognition: SpeechRecognitionConstructor,\n  lang: string\n) {\n  try {\n    const status = await Recognition.available?.({\n      langs: [lang],\n      processLocally: true,\n    })\n    return status === \"available\"\n  } catch {\n    return false\n  }\n}\n\ntype AIChatComposerDictationErrorCode =\n  | \"microphone-blocked\"\n  | \"insecure-context\"\n  | \"no-microphone\"\n  | \"microphone-busy\"\n  | \"recognition-blocked\"\n  | \"recognition-unreachable\"\n  | \"language-not-supported\"\n  | \"unknown\"\n\nconst dictationErrorMessages: Record<AIChatComposerDictationErrorCode, string> =\n  {\n    \"microphone-blocked\":\n      \"Microphone access is blocked. Allow it for this site in the browser's settings, and for the browser in the system's privacy settings.\",\n    \"insecure-context\": \"Microphone access needs a secure (https) page.\",\n    \"no-microphone\": \"No microphone was found.\",\n    \"microphone-busy\": \"The microphone is in use by another app.\",\n    \"recognition-blocked\":\n      \"Speech recognition is blocked or turned off in this browser.\",\n    \"recognition-unreachable\":\n      \"Speech recognition could not reach its service. Chrome needs a connection to Google; Arc, Brave and other Chromium browsers have no access to it.\",\n    \"language-not-supported\":\n      \"Speech recognition does not support this language.\",\n    unknown: \"Dictation stopped unexpectedly.\",\n  }\n\n/** Why dictation could not start or produce text. `code` is stable; `message` is English. */\nclass AIChatComposerDictationError extends Error {\n  code: AIChatComposerDictationErrorCode\n\n  constructor(code: AIChatComposerDictationErrorCode, cause?: unknown) {\n    super(dictationErrorMessages[code], { cause })\n    this.name = \"AIChatComposerDictationError\"\n    this.code = code\n  }\n}\n\nconst dictationErrorCodes: Record<string, AIChatComposerDictationErrorCode> = {\n  NotAllowedError: \"microphone-blocked\",\n  SecurityError: \"insecure-context\",\n  NotFoundError: \"no-microphone\",\n  NotReadableError: \"microphone-busy\",\n  \"audio-capture\": \"no-microphone\",\n  \"not-allowed\": \"recognition-blocked\",\n  \"service-not-allowed\": \"recognition-blocked\",\n  network: \"recognition-unreachable\",\n  \"language-not-supported\": \"language-not-supported\",\n}\n\nfunction toDictationError(reason: unknown) {\n  const name =\n    reason instanceof DOMException || reason instanceof Error\n      ? reason.name\n      : String(reason)\n  return new AIChatComposerDictationError(\n    dictationErrorCodes[name] ?? \"unknown\",\n    reason\n  )\n}\n\ntype DictationState = \"idle\" | \"recording\" | \"transcribing\"\n\ntype DictationOptions = {\n  transcribe?: (audio: Blob) => Promise<string>\n  lang?: string\n  onError?: (error: AIChatComposerDictationError) => void\n}\n\ntype Dictation = {\n  state: DictationState\n  configure: (options: DictationOptions) => void\n  start: () => void\n  stop: () => void\n  send: () => void\n  cancel: () => void\n}\n\ntype DictationSession = {\n  stream: MediaStream\n  audioContext: AudioContext\n  frame: number\n  range: [number, number]\n  recorder?: MediaRecorder\n  chunks: Blob[]\n  recognition?: SpeechRecognitionInstance\n  recognitionEnded?: Promise<void>\n  transcript: string\n  error?: unknown\n}\n\nfunction useDictation(\n  textareaRef: React.RefObject<HTMLTextAreaElement | null>\n) {\n  const [state, setState] = React.useState<DictationState>(\"idle\")\n  const [levels, setLevels] = React.useState<number[]>(() =>\n    Array(WAVEFORM_BARS).fill(0)\n  )\n  const options = React.useRef<DictationOptions>({})\n  const session = React.useRef<DictationSession | null>(null)\n  const generation = React.useRef(0)\n  const starting = React.useRef(false)\n  const sendWhenDone = React.useRef(false)\n\n  const release = React.useCallback((target: DictationSession | null) => {\n    if (!target || session.current !== target) return\n    session.current = null\n    cancelAnimationFrame(target.frame)\n    target.stream.getTracks().forEach((track) => track.stop())\n    void target.audioContext.close()\n  }, [])\n\n  React.useEffect(\n    () => () => {\n      generation.current++\n      session.current?.recognition?.abort()\n      release(session.current)\n    },\n    [release]\n  )\n\n  const reportError = React.useCallback((reason: unknown) => {\n    options.current.onError?.(toDictationError(reason))\n  }, [])\n\n  const start = React.useCallback(async () => {\n    if (session.current || starting.current) return\n    starting.current = true\n    const id = generation.current\n    const textarea = textareaRef.current\n    const end = textarea?.value.length ?? 0\n    const range: [number, number] =\n      textarea && document.activeElement === textarea\n        ? [textarea.selectionStart, textarea.selectionEnd]\n        : [end, end]\n    const { transcribe, lang = navigator.language } = options.current\n    const Recognition = transcribe ? undefined : getSpeechRecognition()\n    let stream: MediaStream | undefined\n    let audioContext: AudioContext | undefined\n    try {\n      const onDevice = Recognition\n        ? await hasOnDeviceModel(Recognition, lang)\n        : false\n      stream = await navigator.mediaDevices.getUserMedia({\n        audio: {\n          echoCancellation: false,\n          noiseSuppression: false,\n          autoGainControl: true,\n        },\n      })\n      if (id !== generation.current) {\n        stream.getTracks().forEach((track) => track.stop())\n        return\n      }\n\n      audioContext = new AudioContext()\n      const analyser = audioContext.createAnalyser()\n      analyser.fftSize = 512\n      audioContext.createMediaStreamSource(stream).connect(analyser)\n      const samples = new Uint8Array(analyser.fftSize)\n\n      const current: DictationSession = {\n        stream,\n        audioContext,\n        frame: 0,\n        range,\n        chunks: [],\n        transcript: \"\",\n      }\n      session.current = current\n\n      let lastSample = 0\n      const sample = (time: number) => {\n        current.frame = requestAnimationFrame(sample)\n        if (time - lastSample < WAVEFORM_INTERVAL) return\n        lastSample = time\n        analyser.getByteTimeDomainData(samples)\n        let sum = 0\n        for (const value of samples) sum += ((value - 128) / 128) ** 2\n        const level = Math.min(1, Math.sqrt(sum / samples.length) * 4)\n        setLevels((previous) => [...previous.slice(1), level])\n      }\n      current.frame = requestAnimationFrame(sample)\n\n      if (transcribe) {\n        const recorder = new MediaRecorder(stream)\n        recorder.ondataavailable = (event) => current.chunks.push(event.data)\n        recorder.start()\n        current.recorder = recorder\n      } else if (Recognition) {\n        const recognition = new Recognition()\n        recognition.continuous = true\n        recognition.interimResults = true\n        recognition.lang = lang\n        if (onDevice) recognition.processLocally = true\n        recognition.onerror = (event) => {\n          if (event.error !== \"no-speech\" && event.error !== \"aborted\") {\n            current.error = event.error\n          }\n        }\n        recognition.onresult = (event) => {\n          current.transcript = Array.from(event.results)\n            .map((result) => result[0].transcript)\n            .join(\"\")\n        }\n        current.recognitionEnded = new Promise((resolve) => {\n          recognition.onend = () => resolve()\n        })\n        recognition.start()\n        current.recognition = recognition\n      }\n\n      setLevels(Array(WAVEFORM_BARS).fill(0))\n      setState(\"recording\")\n    } catch (reason) {\n      if (session.current) {\n        release(session.current)\n      } else {\n        stream?.getTracks().forEach((track) => track.stop())\n        void audioContext?.close()\n      }\n      setState(\"idle\")\n      reportError(reason)\n    } finally {\n      starting.current = false\n    }\n  }, [release, reportError, textareaRef])\n\n  const stop = React.useCallback(async () => {\n    const current = session.current\n    if (!current) return\n    const id = generation.current\n    const shownAt = Date.now()\n    setState(\"transcribing\")\n\n    let words = \"\"\n    try {\n      const { transcribe } = options.current\n      if (current.recorder && transcribe) {\n        const recorder = current.recorder\n        const stopped = new Promise((resolve) => {\n          recorder.onstop = resolve\n        })\n        recorder.stop()\n        await stopped\n        release(current)\n        words = await transcribe(\n          new Blob(current.chunks, { type: recorder.mimeType })\n        )\n      } else if (current.recognition) {\n        current.recognition.stop()\n        await current.recognitionEnded\n        words = current.transcript\n      }\n    } catch (reason) {\n      current.error ??= reason ?? \"unknown\"\n    } finally {\n      release(current)\n    }\n\n    const remaining = MIN_TRANSCRIBING_TIME - (Date.now() - shownAt)\n    if (remaining > 0) {\n      await new Promise((resolve) => setTimeout(resolve, remaining))\n    }\n    if (id !== generation.current) return\n\n    words = words.trim()\n    const textarea = textareaRef.current\n    if (words && textarea) insertText(textarea, words, ...current.range)\n    else if (!words && current.error) reportError(current.error)\n    setState(\"idle\")\n\n    if (sendWhenDone.current) {\n      sendWhenDone.current = false\n      if (words && !current.error && textarea?.form) submitForm(textarea.form)\n    }\n  }, [release, reportError, textareaRef])\n\n  const send = React.useCallback(() => {\n    sendWhenDone.current = true\n    if (state === \"recording\") void stop()\n  }, [state, stop])\n\n  const cancel = React.useCallback(() => {\n    generation.current++\n    sendWhenDone.current = false\n    const current = session.current\n    if (current?.recorder?.state === \"recording\") current.recorder.stop()\n    current?.recognition?.abort()\n    release(current)\n    setState(\"idle\")\n  }, [release])\n\n  const configure = React.useCallback((next: DictationOptions) => {\n    options.current = next\n  }, [])\n\n  const dictation = React.useMemo<Dictation>(\n    () => ({\n      state,\n      configure,\n      start: () => void start(),\n      stop: () => void stop(),\n      send,\n      cancel,\n    }),\n    [state, configure, start, stop, send, cancel]\n  )\n\n  return { dictation, levels }\n}\n\nfunction AIChatComposer({\n  className,\n  style,\n  children,\n  ref,\n  ...props\n}: React.ComponentProps<\"div\">) {\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const textareaRef = React.useRef<HTMLTextAreaElement>(null)\n  const stopRef = React.useRef<HTMLButtonElement>(null)\n  const [multiline, setMultilineState] = React.useState(false)\n  const [maximized, setMaximizedState] = React.useState(false)\n  const [maxHeight, setMaxHeight] = React.useState<number>()\n  const [empty, setEmpty] = React.useState(true)\n  const { dictation, levels } = useDictation(textareaRef)\n  const dictating = dictation.state !== \"idle\"\n  const wasDictating = React.useRef(false)\n\n  const mergedRef = React.useCallback(\n    (node: HTMLDivElement | null) => assignRefs(node, [rootRef, ref]),\n    [ref]\n  )\n\n  const setMultiline = React.useCallback((next: boolean) => {\n    setMultilineState(next)\n    if (!next) setMaximizedState(false)\n  }, [])\n\n  const setMaximized = React.useCallback((next: boolean) => {\n    if (next && rootRef.current) {\n      setMaxHeight(availableHeight(rootRef.current))\n    }\n    setMaximizedState(next)\n  }, [])\n\n  React.useEffect(() => {\n    if (!maximized) return\n    const measure = () => {\n      if (rootRef.current) setMaxHeight(availableHeight(rootRef.current))\n    }\n    window.addEventListener(\"resize\", measure)\n    return () => window.removeEventListener(\"resize\", measure)\n  }, [maximized])\n\n  React.useLayoutEffect(() => {\n    if (dictating === wasDictating.current) return\n    wasDictating.current = dictating\n    const focused = document.activeElement\n    const fallen = !focused || focused === document.body\n    if (!dictating) {\n      if (fallen) textareaRef.current?.focus({ preventScroll: true })\n      return\n    }\n    const hidden =\n      !!focused &&\n      !!rootRef.current?.contains(focused) &&\n      focused.getClientRects().length === 0\n    if (fallen || hidden) stopRef.current?.focus({ preventScroll: true })\n  }, [dictating])\n\n  const context = React.useMemo<AIChatComposerContextValue>(\n    () => ({\n      rootRef,\n      textareaRef,\n      multiline,\n      setMultiline,\n      maximized,\n      setMaximized,\n      setEmpty,\n      dictation,\n    }),\n    [multiline, setMultiline, maximized, setMaximized, dictation]\n  )\n\n  return (\n    <AIChatComposerContext.Provider value={context}>\n      <div\n        ref={mergedRef}\n        data-slot=\"ai-chat-composer\"\n        data-multiline={multiline}\n        data-maximized={maximized}\n        data-empty={empty}\n        data-dictating={dictating}\n        style={\n          maxHeight === undefined\n            ? style\n            : ({\n                \"--ai-chat-composer-max-height\": `${maxHeight}px`,\n                ...style,\n              } as React.CSSProperties)\n        }\n        className={cn(\n          \"group/ai-chat-composer relative grid w-full grid-cols-[auto_minmax(0,1fr)_auto] items-center rounded-xl bg-popover text-xs text-popover-foreground shadow-[0_4px_16px_-4px_oklch(0.371_0_0/0.02),0_0_10px_oklch(0.371_0_0/0.03)] ring-1 ring-field-border [grid-template-areas:'leading_input_trailing'] has-data-measuring:invisible has-data-[slot=ai-chat-composer-header]:[grid-template-areas:'header_header_header'_'input_input_input'_'leading_._trailing'] has-[[data-slot=ai-chat-composer-leading]>[data-slot=badge]]:[grid-template-areas:'header_header_header'_'input_input_input'_'leading_._trailing'] data-[dictating=true]:data-[empty=false]:[grid-template-areas:'header_header_header'_'input_input_input'_'record_record_record'] data-[dictating=true]:data-[empty=true]:[grid-template-areas:'header_header_header'_'record_record_record'] data-[maximized=true]:h-[min(var(--ai-chat-composer-max-height,100dvh),--spacing(160))] data-[maximized=true]:grid-rows-[auto_minmax(0,1fr)_auto] data-[multiline=true]:[grid-template-areas:'header_header_header'_'input_input_input'_'leading_._trailing']\",\n          className\n        )}\n        {...props}\n      >\n        {children}\n        {dictating && (\n          <DictationBar\n            dictation={dictation}\n            levels={levels}\n            stopRef={stopRef}\n          />\n        )}\n      </div>\n    </AIChatComposerContext.Provider>\n  )\n}\n\nfunction DictationBar({\n  dictation,\n  levels,\n  stopRef,\n}: {\n  dictation: Dictation\n  levels: number[]\n  stopRef: React.Ref<HTMLButtonElement>\n}) {\n  const transcribing = dictation.state === \"transcribing\"\n  return (\n    <div\n      data-slot=\"ai-chat-composer-dictation\"\n      className=\"flex min-w-0 items-center [grid-area:record]\"\n    >\n      <div className=\"py-1.5 pl-1.5\">\n        <Button\n          type=\"button\"\n          variant=\"secondary\"\n          size=\"icon-sm\"\n          aria-label=\"Cancel dictation\"\n          className=\"text-muted-foreground hover:text-foreground\"\n          onClick={dictation.cancel}\n        >\n          <XIcon />\n        </Button>\n      </div>\n      {transcribing ? (\n        <div\n          role=\"status\"\n          className=\"flex h-7 min-w-0 flex-1 items-center justify-center px-1.5 text-2xs text-muted-foreground\"\n        >\n          Transcribing…\n        </div>\n      ) : (\n        <div\n          aria-hidden\n          className=\"flex h-7 min-w-0 flex-1 items-center justify-between px-1.5\"\n        >\n          {levels.map((level, index) => {\n            const height = 2 + Math.round(level * 14)\n            return (\n              <span\n                key={index}\n                className={cn(\n                  \"w-0.5 shrink-0 rounded-[1px]\",\n                  height >= LOUD_BAR_HEIGHT\n                    ? \"bg-foreground/30\"\n                    : \"bg-foreground/15\"\n                )}\n                style={{ height }}\n              />\n            )\n          })}\n        </div>\n      )}\n      <div className=\"flex items-center gap-1 py-1.5 pr-1.5\">\n        <Button\n          ref={stopRef}\n          type=\"button\"\n          variant=\"secondary\"\n          size=\"icon-sm\"\n          aria-label=\"Stop dictation\"\n          className=\"text-muted-foreground hover:text-foreground\"\n          aria-disabled={transcribing || undefined}\n          onClick={() => {\n            if (!transcribing) dictation.stop()\n          }}\n        >\n          {transcribing ? <Spinner /> : <SquareIcon />}\n        </Button>\n        <Button\n          type=\"button\"\n          size=\"icon-sm\"\n          aria-label=\"Send\"\n          onClick={dictation.send}\n        >\n          <ArrowUpIcon />\n        </Button>\n      </div>\n    </div>\n  )\n}\n\n/** Content above the text, such as attachments. Rendering it opens the composer. */\nfunction AIChatComposerHeader({\n  className,\n  ...props\n}: React.ComponentProps<\"div\">) {\n  return (\n    <div\n      data-slot=\"ai-chat-composer-header\"\n      className={cn(\n        \"flex min-w-0 flex-wrap items-center gap-2 p-2 [grid-area:header]\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\n\ntype AIChatComposerCommand = {\n  /** Inserted as \"/\" + value, and matched against the typed filter. */\n  value: string\n  label?: React.ReactNode\n  icon?: React.ReactNode\n  /** Consecutive commands with the same group are shown under its label. */\n  group?: string\n  /** Shown next to the menu while the command is highlighted. */\n  description?: React.ReactNode\n  /** Runs instead of inserting a token; the typed \"/…\" is removed. */\n  onSelect?: () => void\n}\n\nconst textBoxClassName =\n  \"group-data-[dictating=true]/ai-chat-composer:group-data-[empty=true]/ai-chat-composer:hidden group-data-[dictating=true]/ai-chat-composer:px-3 px-2 py-2.5 text-sm leading-5 [grid-area:input] group-has-data-[slot=ai-chat-composer-header]/ai-chat-composer:px-3 group-has-[[data-slot=ai-chat-composer-leading]>[data-slot=badge]]/ai-chat-composer:px-3 group-data-[multiline=true]/ai-chat-composer:px-3 data-fade-bottom:[mask-image:linear-gradient(to_bottom,transparent,black_var(--fade-top,0px),black_calc(100%_-_var(--fade-bottom,0px)),transparent)] data-fade-bottom:[--fade-bottom:--spacing(6)] data-fade-top:[mask-image:linear-gradient(to_bottom,transparent,black_var(--fade-top,0px),black_calc(100%_-_var(--fade-bottom,0px)),transparent)] data-fade-top:[--fade-top:--spacing(6)]\"\n\nconst escapeRegExp = (text: string) =>\n  text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\nconst findSlashCommand = (textBeforeCaret: string) =>\n  /(^|\\s)\\/([^\\s/]*)$/.exec(textBeforeCaret)\n\nfunction useTokenPattern(\n  tokens: string[] | undefined,\n  commands: AIChatComposerCommand[] | undefined\n) {\n  return React.useMemo(() => {\n    const all = new Set([\n      ...(tokens ?? []),\n      ...(commands ?? [])\n        .filter((command) => !command.onSelect)\n        .map((command) => \"/\" + command.value),\n    ])\n    if (all.size === 0) return null\n    const alternatives = [...all]\n      .sort((a, b) => b.length - a.length)\n      .map(escapeRegExp)\n      .join(\"|\")\n    return new RegExp(`(^|\\\\s)(${alternatives})(?=\\\\s|$)`, \"g\")\n  }, [tokens, commands])\n}\n\nfunction removeTokenBeforeCaret(\n  textarea: HTMLTextAreaElement,\n  tokenPattern: RegExp\n) {\n  if (textarea.selectionStart !== textarea.selectionEnd) return false\n  if (/\\S/.test(textarea.value.charAt(textarea.selectionEnd))) return false\n  const before = textarea.value.slice(0, textarea.selectionStart)\n  const token = new RegExp(`(?:${tokenPattern.source})$`).exec(before)\n  if (!token) return false\n  textarea.setRangeText(\n    \"\",\n    before.length - token[2].length,\n    before.length,\n    \"end\"\n  )\n  textarea.dispatchEvent(new Event(\"input\", { bubbles: true }))\n  return true\n}\n\nfunction useTextareaLayout(\n  textareaRef: React.RefObject<HTMLTextAreaElement | null>,\n  overlayRef: React.RefObject<HTMLDivElement | null>,\n  initialText: string\n) {\n  const { multiline, setMultiline, maximized, setEmpty } = useAIChatComposer()\n  const [text, setText] = React.useState(initialText)\n  const [long, setLong] = React.useState(false)\n  const [measured, setMeasured] = React.useState(false)\n  const [gutter, setGutter] = React.useState(0)\n  const [scroll, setScroll] = React.useState({\n    fadeTop: false,\n    fadeBottom: false,\n  })\n\n  const measure = React.useCallback(() => {\n    const textarea = textareaRef.current\n    if (!textarea) return\n    if (overlayRef.current) overlayRef.current.scrollTop = textarea.scrollTop\n    if (textarea.value !== text) setText(textarea.value)\n    setEmpty(textarea.value === \"\")\n\n    const style = getComputedStyle(textarea)\n    const nextGutter = Math.max(\n      0,\n      textarea.offsetWidth -\n        textarea.clientWidth -\n        parseFloat(style.borderLeftWidth) -\n        parseFloat(style.borderRightWidth)\n    )\n    if (nextGutter !== gutter) setGutter(nextGutter)\n\n    const next = {\n      fadeTop: textarea.scrollTop > 0,\n      fadeBottom:\n        textarea.scrollTop + textarea.clientHeight < textarea.scrollHeight - 1,\n    }\n    if (\n      next.fadeTop !== scroll.fadeTop ||\n      next.fadeBottom !== scroll.fadeBottom\n    ) {\n      setScroll(next)\n    }\n\n    if (textarea.value === \"\") {\n      setLong(false)\n      setMultiline(false)\n      return\n    }\n    const lines = Math.round(\n      (textarea.scrollHeight -\n        parseFloat(style.paddingTop) -\n        parseFloat(style.paddingBottom)) /\n        parseFloat(style.lineHeight)\n    )\n    if (!multiline && (textarea.value.includes(\"\\n\") || lines > 1)) {\n      setMultiline(true)\n    }\n    if (!maximized) setLong(lines >= EXPAND_FROM_LINE)\n  }, [\n    textareaRef,\n    overlayRef,\n    text,\n    gutter,\n    scroll,\n    multiline,\n    maximized,\n    setMultiline,\n    setEmpty,\n  ])\n\n  const measureRef = React.useRef(measure)\n  React.useLayoutEffect(() => {\n    measureRef.current = measure\n    measure()\n  })\n\n  React.useLayoutEffect(() => setMeasured(true), [])\n\n  React.useEffect(() => {\n    const textarea = textareaRef.current\n    if (!textarea) return\n    let active = true\n    const remeasure = () => {\n      if (active) measureRef.current()\n    }\n    const observer =\n      typeof ResizeObserver === \"undefined\"\n        ? undefined\n        : new ResizeObserver(remeasure)\n    observer?.observe(textarea)\n    void document.fonts?.ready.then(remeasure)\n    return () => {\n      active = false\n      observer?.disconnect()\n    }\n  }, [textareaRef])\n\n  React.useEffect(() => {\n    const form = textareaRef.current?.form\n    if (!form) return\n    const onReset = () => setTimeout(measure)\n    form.addEventListener(\"reset\", onReset)\n    return () => form.removeEventListener(\"reset\", onReset)\n  }, [textareaRef, measure])\n\n  const measuring = !measured && initialText !== \"\"\n\n  return { text, long, measuring, scroll, gutter, measure }\n}\n\nfunction useSlashCommands(\n  textareaRef: React.RefObject<HTMLTextAreaElement | null>,\n  commands: AIChatComposerCommand[] | undefined\n) {\n  const [slash, setSlash] = React.useState<{\n    start: number\n    filter: string\n  } | null>(null)\n  const [dismissedAt, setDismissedAt] = React.useState<number | null>(null)\n  const [highlighted, setHighlighted] = React.useState(0)\n\n  const matches = React.useMemo(() => {\n    if (!slash || !commands) return []\n    const filter = slash.filter.toLowerCase()\n    return commands.filter((command) =>\n      [command.value, typeof command.label === \"string\" ? command.label : \"\"]\n        .join(\" \")\n        .toLowerCase()\n        .includes(filter)\n    )\n  }, [slash, commands])\n  const open = !!slash && slash.start !== dismissedAt && matches.length > 0\n  const active = Math.min(highlighted, Math.max(matches.length - 1, 0))\n\n  const update = React.useCallback(() => {\n    const textarea = textareaRef.current\n    if (!textarea || !commands) return\n    const caret = textarea.selectionStart\n    const match =\n      caret === textarea.selectionEnd\n        ? findSlashCommand(textarea.value.slice(0, caret))\n        : null\n    const next = match\n      ? { start: caret - match[2].length - 1, filter: match[2] }\n      : null\n    setSlash((previous) =>\n      previous?.start === next?.start && previous?.filter === next?.filter\n        ? previous\n        : next\n    )\n    if (!next) setDismissedAt(null)\n    if (next?.filter !== slash?.filter) setHighlighted(0)\n  }, [textareaRef, commands, slash])\n\n  const dismiss = () => {\n    if (slash) setDismissedAt(slash.start)\n  }\n\n  const choose = (command: AIChatComposerCommand) => {\n    const textarea = textareaRef.current\n    if (!textarea || !slash) return\n    const end = textarea.selectionStart\n    if (command.onSelect) {\n      textarea.focus()\n      textarea.setRangeText(\"\", slash.start, end, \"end\")\n      textarea.dispatchEvent(new Event(\"input\", { bubbles: true }))\n      command.onSelect()\n    } else {\n      insertText(textarea, \"/\" + command.value, slash.start, end)\n    }\n    setSlash(null)\n  }\n\n  const handleKeyDown = (event: React.KeyboardEvent) => {\n    if (!open) return false\n    switch (event.key) {\n      case \"ArrowDown\":\n      case \"ArrowUp\": {\n        const step = event.key === \"ArrowDown\" ? 1 : -1\n        setHighlighted((active + step + matches.length) % matches.length)\n        break\n      }\n      case \"Enter\":\n      case \"Tab\":\n        choose(matches[active])\n        break\n      case \"Escape\":\n        event.stopPropagation()\n        dismiss()\n        break\n      default:\n        return false\n    }\n    event.preventDefault()\n    return true\n  }\n\n  return {\n    open,\n    matches,\n    active,\n    slashStart: open ? slash.start : null,\n    update,\n    choose,\n    dismiss,\n    highlight: setHighlighted,\n    handleKeyDown,\n  }\n}\n\nfunction TokenOverlay({\n  text,\n  tokenPattern,\n  markerAt,\n  markerRef,\n  ...props\n}: React.ComponentProps<\"div\"> & {\n  text: string\n  tokenPattern: RegExp | null\n  markerAt: number | null\n  markerRef: React.Ref<HTMLSpanElement>\n}) {\n  const content = React.useMemo(() => {\n    const parts: React.ReactNode[] = []\n    const chips = tokenPattern\n      ? [...text.matchAll(tokenPattern)].map((match) => {\n          const start = match.index + match[1].length\n          return { start, end: start + match[2].length, token: match[2] }\n        })\n      : []\n    const adjacent = (a?: { end: number }, b?: { start: number }) =>\n      !!a && !!b && /^[^\\S\\n]+$/.test(text.slice(a.end, b.start))\n    const marker = <span key=\"marker\" ref={markerRef} />\n    const pushText = (from: number, to: number) => {\n      if (markerAt !== null && markerAt >= from && markerAt < to) {\n        parts.push(text.slice(from, markerAt), marker, text.slice(markerAt, to))\n      } else {\n        parts.push(text.slice(from, to))\n      }\n    }\n\n    let last = 0\n    chips.forEach((chip, index) => {\n      pushText(last, chip.start)\n      if (markerAt === chip.start) parts.push(marker)\n      parts.push(\n        <span\n          key={chip.start}\n          data-slot=\"ai-chat-composer-token\"\n          className={cn(\n            \"rounded-xs bg-blue-100 box-decoration-clone py-[1.5px] text-blue-700 dark:bg-blue-500/25 dark:text-blue-200\",\n            !adjacent(chips[index - 1], chip) && \"-ml-1 pl-1\",\n            !adjacent(chip, chips[index + 1]) && \"-mr-1 pr-1\"\n          )}\n        >\n          {chip.token}\n        </span>\n      )\n      last = chip.end\n    })\n    pushText(last, text.length)\n    if (markerAt === text.length) parts.push(marker)\n    parts.push(\"\\u200b\")\n    return parts\n  }, [text, tokenPattern, markerAt, markerRef])\n\n  return (\n    <div aria-hidden data-slot=\"ai-chat-composer-overlay\" {...props}>\n      {content}\n    </div>\n  )\n}\n\nfunction CommandMenu({\n  open,\n  anchor,\n  listId,\n  commands,\n  active,\n  onHighlight,\n  onChoose,\n  onDismiss,\n}: {\n  open: boolean\n  anchor: PopoverPrimitive.Positioner.Props[\"anchor\"]\n  listId: string\n  commands: AIChatComposerCommand[]\n  active: number\n  onHighlight: (index: number) => void\n  onChoose: (command: AIChatComposerCommand) => void\n  onDismiss: () => void\n}) {\n  const positionerRef = React.useRef<HTMLDivElement>(null)\n  const [descriptionTop, setDescriptionTop] = React.useState(0)\n  const description = commands[active]?.description\n\n  const placeDescription = React.useCallback(() => {\n    const option = document.getElementById(`${listId}-${active}`)\n    const positioner = positionerRef.current\n    if (!option || !positioner) return\n    setDescriptionTop(\n      option.getBoundingClientRect().top -\n        positioner.getBoundingClientRect().top\n    )\n  }, [listId, active])\n\n  React.useLayoutEffect(() => {\n    if (!open) return\n    document\n      .getElementById(`${listId}-${active}`)\n      ?.scrollIntoView({ block: \"nearest\" })\n    placeDescription()\n  }, [open, listId, active, commands, placeDescription])\n\n  return (\n    <PopoverPrimitive.Root\n      open={open}\n      onOpenChange={(next) => {\n        if (!next) onDismiss()\n      }}\n      modal={false}\n    >\n      <PopoverPrimitive.Portal>\n        <PopoverPrimitive.Positioner\n          ref={positionerRef}\n          anchor={anchor}\n          side=\"bottom\"\n          align=\"start\"\n          sideOffset={4}\n          className=\"isolate z-50 outline-none\"\n        >\n          <PopoverPrimitive.Popup\n            initialFocus={false}\n            finalFocus={false}\n            data-slot=\"ai-chat-composer-commands\"\n            onScroll={placeDescription}\n            className=\"max-h-(--available-height) w-60 origin-(--transform-origin) overflow-y-auto rounded-14 bg-popover p-1 text-sm text-popover-foreground shadow-(--shadow-popover) ring-1 ring-border outline-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95\"\n          >\n            <div id={listId} role=\"listbox\" className=\"flex flex-col\">\n              {commands.map((command, index) => {\n                const startsGroup =\n                  !!command.group &&\n                  command.group !== commands[index - 1]?.group\n                return (\n                  <React.Fragment key={command.value}>\n                    {startsGroup && (\n                      <>\n                        {index > 0 && (\n                          <div\n                            role=\"separator\"\n                            className=\"mx-1 mt-1 mb-[3px] h-px bg-border\"\n                          />\n                        )}\n                        <div className=\"px-2 py-1.5 text-2xs font-medium text-muted-foreground\">\n                          {command.group}\n                        </div>\n                      </>\n                    )}\n                    <div\n                      id={`${listId}-${index}`}\n                      role=\"option\"\n                      aria-selected={index === active}\n                      data-highlighted={index === active || undefined}\n                      className=\"flex cursor-default items-center gap-2 rounded-lg px-2 py-1.5 select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&>svg]:mx-0.5\"\n                      onMouseMove={() => onHighlight(index)}\n                      onMouseDown={(event) => event.preventDefault()}\n                      onClick={() => onChoose(command)}\n                    >\n                      {command.icon}\n                      <span className=\"truncate\">\n                        {command.label ?? command.value}\n                      </span>\n                    </div>\n                  </React.Fragment>\n                )\n              })}\n            </div>\n          </PopoverPrimitive.Popup>\n          {description && (\n            <div\n              data-slot=\"ai-chat-composer-command-description\"\n              style={{ top: descriptionTop }}\n              className=\"pointer-events-none absolute left-full ml-2 w-max max-w-66 rounded-md bg-foreground px-2 py-1 text-2xs text-background\"\n            >\n              {description}\n            </div>\n          )}\n        </PopoverPrimitive.Positioner>\n      </PopoverPrimitive.Portal>\n    </PopoverPrimitive.Root>\n  )\n}\n\nfunction ExpandButton() {\n  const { maximized, setMaximized } = useAIChatComposer()\n  return (\n    <Button\n      data-slot=\"ai-chat-composer-expand\"\n      type=\"button\"\n      variant=\"ghost\"\n      size=\"icon-sm\"\n      aria-label={maximized ? \"Collapse\" : \"Expand\"}\n      onClick={() => setMaximized(!maximized)}\n      className=\"relative z-10 mt-1.5 mr-1.5 self-start justify-self-end rounded-full text-muted-foreground [grid-area:input] hover:text-foreground\"\n    >\n      {maximized ? <MinimizeIcon /> : <MaximizeIcon />}\n    </Button>\n  )\n}\n\n/**\n * The text input. Enter submits the closest form (Shift+Enter adds a line)\n * unless `submitOnEnter` is false. It grows with its content up to a limit and\n * fades out at the edges it scrolls past; from the fifth line a button\n * maximizes the composer.\n *\n * `tokens` are drawn as inline chips wherever they stand as a word, and\n * Backspace removes a token as a whole. Typing \"/\" at the start of a word\n * opens the `commands` menu, which inserts a token or runs an action.\n */\nfunction AIChatComposerTextarea({\n  className,\n  style,\n  submitOnEnter = true,\n  maximizable = true,\n  tokens,\n  commands,\n  onKeyDown,\n  onInput,\n  onScroll,\n  onSelect,\n  ref,\n  ...props\n}: React.ComponentProps<\"textarea\"> & {\n  submitOnEnter?: boolean\n  /** Shows the maximize button once the text runs long. */\n  maximizable?: boolean\n  /** Strings drawn as inline chips, such as \"/release-notes\". */\n  tokens?: string[]\n  /** Items of the menu that \"/\" opens. */\n  commands?: AIChatComposerCommand[]\n}) {\n  const { rootRef, textareaRef, maximized } = useAIChatComposer()\n  const localRef = React.useRef<HTMLTextAreaElement>(null)\n  const overlayRef = React.useRef<HTMLDivElement>(null)\n  const markerRef = React.useRef<HTMLSpanElement>(null)\n  const listId = React.useId()\n\n  const tokenPattern = useTokenPattern(tokens, commands)\n  const { text, long, measuring, scroll, gutter, measure } = useTextareaLayout(\n    localRef,\n    overlayRef,\n    String(props.value ?? props.defaultValue ?? \"\")\n  )\n  const menu = useSlashCommands(localRef, commands)\n  const mergedRef = React.useCallback(\n    (node: HTMLTextAreaElement | null) =>\n      assignRefs(node, [localRef, textareaRef, ref]),\n    [textareaRef, ref]\n  )\n\n  const menuAnchor = {\n    get contextElement() {\n      return localRef.current ?? undefined\n    },\n    getBoundingClientRect() {\n      const target = markerRef.current ?? rootRef.current\n      return target?.getBoundingClientRect() ?? new DOMRect()\n    },\n  }\n\n  const expandable = maximizable && (long || maximized)\n  const fadeAttributes = {\n    \"data-fade-top\": scroll.fadeTop || undefined,\n    \"data-fade-bottom\": scroll.fadeBottom || undefined,\n  }\n  const gutterStyle = gutter\n    ? ({ \"--ai-chat-composer-gutter\": `${gutter}px` } as React.CSSProperties)\n    : undefined\n\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n    onKeyDown?.(event)\n    if (\n      event.defaultPrevented ||\n      event.nativeEvent.isComposing ||\n      (event.key === \"Enter\" && event.keyCode === 229)\n    ) {\n      return\n    }\n    if (menu.handleKeyDown(event)) return\n\n    const textarea = event.currentTarget\n    if (\n      event.key === \"Backspace\" &&\n      tokenPattern &&\n      removeTokenBeforeCaret(textarea, tokenPattern)\n    ) {\n      event.preventDefault()\n      return\n    }\n    if (submitOnEnter && event.key === \"Enter\" && !event.shiftKey) {\n      const form = textarea.form\n      if (!form) return\n      event.preventDefault()\n      submitForm(form)\n    }\n  }\n\n  return (\n    <>\n      {(tokenPattern || commands) && (\n        <TokenOverlay\n          ref={overlayRef}\n          markerRef={markerRef}\n          text={text}\n          tokenPattern={tokenPattern}\n          markerAt={menu.slashStart}\n          {...fadeAttributes}\n          style={gutterStyle}\n          className={cn(\n            textBoxClassName,\n            \"pointer-events-none mr-[var(--ai-chat-composer-gutter,0px)] self-stretch overflow-hidden wrap-break-word whitespace-pre-wrap contain-size group-has-[[data-slot=ai-chat-composer-textarea]:disabled]/ai-chat-composer:opacity-50\",\n            !tokenPattern && \"text-transparent\",\n            expandable &&\n              \"pr-[calc(--spacing(11.5)-var(--ai-chat-composer-gutter,0px))]!\"\n          )}\n        />\n      )}\n      <textarea\n        ref={mergedRef}\n        data-slot=\"ai-chat-composer-textarea\"\n        data-measuring={measuring || undefined}\n        {...fadeAttributes}\n        rows={1}\n        aria-autocomplete={commands ? \"list\" : undefined}\n        aria-controls={menu.open ? listId : undefined}\n        aria-activedescendant={\n          menu.open ? `${listId}-${menu.active}` : undefined\n        }\n        style={gutterStyle ? { ...gutterStyle, ...style } : style}\n        className={cn(\n          textBoxClassName,\n          \"field-sizing-content max-h-47 min-h-10 resize-none bg-transparent outline-none group-data-[maximized=true]/ai-chat-composer:h-full group-data-[maximized=true]/ai-chat-composer:max-h-none group-data-[maximized=true]/ai-chat-composer:self-stretch placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50 [&::-webkit-scrollbar]:w-6 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:border-8 [&::-webkit-scrollbar-thumb]:border-solid [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-border [&::-webkit-scrollbar-thumb]:bg-clip-padding [&::-webkit-scrollbar-track]:mb-2 [&::-webkit-scrollbar-track]:bg-transparent [@supports_not_selector(::-webkit-scrollbar)]:[scrollbar-width:thin] [@supports_not_selector(::-webkit-scrollbar)]:[scrollbar-color:var(--border)_transparent]\",\n          tokenPattern &&\n            \"text-transparent caret-foreground selection:bg-primary/20 selection:text-transparent\",\n          expandable &&\n            \"[scrollbar-gutter:stable] pr-[calc(--spacing(11.5)-var(--ai-chat-composer-gutter,0px))]! [&::-webkit-scrollbar-track]:mt-10\",\n          className\n        )}\n        onInput={(event) => {\n          onInput?.(event)\n          measure()\n          menu.update()\n        }}\n        onSelect={(event) => {\n          onSelect?.(event)\n          menu.update()\n        }}\n        onScroll={(event) => {\n          onScroll?.(event)\n          measure()\n        }}\n        onKeyDown={handleKeyDown}\n        {...props}\n      />\n      {expandable && <ExpandButton />}\n      {commands && (\n        <CommandMenu\n          open={menu.open}\n          anchor={menuAnchor}\n          listId={listId}\n          commands={menu.matches}\n          active={menu.active}\n          onHighlight={menu.highlight}\n          onChoose={menu.choose}\n          onDismiss={menu.dismiss}\n        />\n      )}\n    </>\n  )\n}\n\n/** The actions before the text. A Badge here marks a tool that is turned on. */\nfunction AIChatComposerLeading({\n  className,\n  ...props\n}: React.ComponentProps<\"div\">) {\n  return (\n    <div\n      data-slot=\"ai-chat-composer-leading\"\n      className={cn(\n        \"flex items-center gap-1 py-1.5 pl-1.5 [grid-area:leading] group-data-[dictating=true]/ai-chat-composer:hidden [&>:not([data-slot=badge])+[data-slot=badge]]:ml-1 [&>button:not([data-slot=ai-chat-composer-submit])]:text-muted-foreground [&>button:not([data-slot=ai-chat-composer-submit]):hover]:text-foreground\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\n\nfunction AIChatComposerTrailing({\n  className,\n  ...props\n}: React.ComponentProps<\"div\">) {\n  return (\n    <div\n      data-slot=\"ai-chat-composer-trailing\"\n      className={cn(\n        \"flex items-center justify-end gap-1 py-1.5 pr-1.5 [grid-area:trailing] group-data-[dictating=true]/ai-chat-composer:hidden [&>button:not([data-slot=ai-chat-composer-submit])]:text-muted-foreground [&>button:not([data-slot=ai-chat-composer-submit]):hover]:text-foreground\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\n\n/**\n * Starts dictation. While recording, the row of actions turns into a bar with\n * cancel, a live waveform, stop and send; stop inserts the words at the caret,\n * send also submits the form.\n *\n * Without `transcribe` the browser's speech recognition is used (Safari and\n * Chrome; not Firefox, Arc or Brave). The button is disabled where neither is\n * available.\n */\nfunction AIChatComposerDictate({\n  transcribe,\n  lang,\n  onError,\n  onClick,\n  onMouseDown,\n  disabled,\n  children,\n  ...props\n}: Omit<React.ComponentProps<typeof Button>, \"onError\"> & {\n  /** Turns the recorded audio into text, e.g. through a speech-to-text API. */\n  transcribe?: (audio: Blob) => Promise<string>\n  /** BCP 47 language tag of the speech. Defaults to `navigator.language`. */\n  lang?: string\n  /** Called when dictation cannot start or produces no text. */\n  onError?: (error: AIChatComposerDictationError) => void\n}) {\n  const { dictation } = useAIChatComposer()\n  const { configure } = dictation\n  const supported = React.useSyncExternalStore(\n    subscribeNever,\n    () =>\n      !!navigator.mediaDevices?.getUserMedia &&\n      (!!transcribe || !!getSpeechRecognition()),\n    () => false\n  )\n\n  React.useEffect(() => {\n    configure({ transcribe, lang, onError })\n  }, [configure, transcribe, lang, onError])\n\n  return (\n    <Button\n      data-slot=\"ai-chat-composer-dictate\"\n      type=\"button\"\n      variant=\"ghost\"\n      size=\"icon-sm\"\n      aria-label=\"Dictate\"\n      disabled={disabled || !supported}\n      onMouseDown={(event) => {\n        onMouseDown?.(event)\n        event.preventDefault()\n      }}\n      onClick={(event) => {\n        onClick?.(event)\n        if (!event.defaultPrevented) dictation.start()\n      }}\n      {...props}\n    >\n      {children ?? <AudioLinesIcon />}\n    </Button>\n  )\n}\n\nfunction AIChatComposerSubmit({\n  children,\n  ...props\n}: React.ComponentProps<typeof Button>) {\n  return (\n    <Button\n      data-slot=\"ai-chat-composer-submit\"\n      type=\"submit\"\n      size=\"icon-sm\"\n      aria-label=\"Send\"\n      {...props}\n    >\n      {children ?? <ArrowUpIcon />}\n    </Button>\n  )\n}\n\n/**\n * Positions menus opened from the composer's buttons: 4px below the composer,\n * or above the button that opened them when there is no room below, aligned to\n * the composer's sides.\n *\n * @example\n * const { ref, anchor } = useAIChatComposerAnchor()\n * <AIChatComposer ref={ref}>…<DropdownMenuContent anchor={anchor}>\n */\nfunction useAIChatComposerAnchor() {\n  const ref = React.useRef<HTMLDivElement>(null)\n  const anchor = React.useCallback(() => {\n    const composer = ref.current\n    if (!composer) return null\n    return {\n      contextElement: composer,\n      getBoundingClientRect: () => {\n        const box = composer.getBoundingClientRect()\n        const trigger = composer.querySelector(\"[data-popup-open]\")\n        const top = trigger ? trigger.getBoundingClientRect().top : box.top\n        return DOMRect.fromRect({\n          x: box.left,\n          y: top,\n          width: box.width,\n          height: box.bottom - top,\n        })\n      },\n    }\n  }, [])\n  return { ref, anchor }\n}\n\nexport {\n  AIChatComposer,\n  AIChatComposerHeader,\n  AIChatComposerTextarea,\n  AIChatComposerLeading,\n  AIChatComposerTrailing,\n  AIChatComposerDictate,\n  AIChatComposerSubmit,\n  AIChatComposerDictationError,\n  useAIChatComposerAnchor,\n  insertAIChatComposerToken,\n  type AIChatComposerCommand,\n  type AIChatComposerDictationErrorCode,\n}\n","type":"registry:ui"}],"cssVars":{"theme":{"color-field-border":"var(--field-border)","radius-14":"0.875rem","text-2xs--letter-spacing":"-0.005em","text-xs--letter-spacing":"-0.005em","text-sm--letter-spacing":"-0.005em","text-2xs":"0.75rem","text-2xs--line-height":"calc(1 / 0.75)","text-xs":"0.8125rem","text-xs--line-height":"calc(1.25 / 0.8125)","shadow-popover":"0 10px 15px -3px oklch(0 0 0 / 7%), 0 4px 6px -4px oklch(0 0 0 / 7%)"},"light":{"field-border":"oklch(0.145 0 0 / 10%)"},"dark":{"field-border":"oklch(1 0 0 / 15%)"}},"categories":["chat"],"type":"registry:ui"}