{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prompt-bar",
  "type": "registry:ui",
  "title": "Prompt Bar",
  "description": "A compact prompt input with removable context chips, a toolbar slot for your model picker, and async send, stop, and retry states.",
  "author": "Aditya Ojha <https://akoder.xyz>",
  "categories": [
    "ai",
    "input",
    "context",
    "accessibility"
  ],
  "dependencies": [
    "lucide-react",
    "motion",
    "@tiptap/react@3.31.4",
    "@tiptap/pm@3.31.4",
    "@tiptap/starter-kit@3.31.4"
  ],
  "registryDependencies": [
    "badge",
    "command",
    "field",
    "hover-card",
    "input-group",
    "popover",
    "progress",
    "separator"
  ],
  "meta": {
    "docs": "https://akoder.xyz/components/prompt-bar",
    "source": "https://github.com/AdityaKodez/adityaojha/blob/main/components/ui/prompt-bar.tsx"
  },
  "files": [
    {
      "path": "components/ui/prompt-bar.tsx",
      "content": "\"use client\";\n\nimport { ArrowUp, AtSign, FileText, LoaderCircle, Paperclip, Square, X, Zap } from \"lucide-react\";\nimport { EditorContent, Node, NodeViewWrapper, ReactNodeViewRenderer, useEditor, type Editor, type JSONContent, type NodeViewProps } from \"@tiptap/react\";\nimport StarterKit from \"@tiptap/starter-kit\";\nimport { EditorState } from \"@tiptap/pm/state\";\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { createContext, useCallback, useContext, useEffect, useId, useMemo, useRef, useState, type FormEvent, type ReactNode } from \"react\";\n\nimport { Badge } from \"@/components/ui/badge\";\nimport { Command, CommandEmpty, CommandGroup, CommandItem, CommandList } from \"@/components/ui/command\";\nimport { Field, FieldError, FieldGroup, FieldLabel } from \"@/components/ui/field\";\nimport { HoverCard, HoverCardContent, HoverCardTrigger } from \"@/components/ui/hover-card\";\nimport { InputGroup, InputGroupButton } from \"@/components/ui/input-group\";\nimport { Popover, PopoverAnchor, PopoverContent } from \"@/components/ui/popover\";\nimport { Progress } from \"@/components/ui/progress\";\nimport { Separator } from \"@/components/ui/separator\";\nimport { cn } from \"@/lib/utils\";\n\nexport type PromptBarContext<TData = unknown> = {\n  id: string;\n  label: string;\n  description?: string;\n  icon?: ReactNode;\n  /** App-owned content, references, or metadata, passed through unchanged. */\n  data?: TData;\n};\n\nexport type PromptBarSkill<TData = unknown> = PromptBarContext<TData> & {\n  /** Instructions for your app to apply when building its prompt. */\n  instructions?: string;\n};\n\nexport type PromptBarUsage = {\n  usedTokens: number;\n  maxTokens: number;\n  /** A percentage from 0 to 100, supplied by your provider. */\n  cacheHitRate?: number;\n};\n\nexport type PromptBarSubmission<TContextData = unknown, TSkillData = unknown> = {\n  text: string;\n  contexts: readonly PromptBarContext<TContextData>[];\n  skill: PromptBarSkill<TSkillData> | null;\n  attachments: readonly File[];\n};\n\nexport type PromptBarProps<TContextData = unknown, TSkillData = unknown> = {\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  contexts?: readonly PromptBarContext<TContextData>[];\n  contextOptions?: readonly PromptBarContext<TContextData>[];\n  onContextAdd?: (context: PromptBarContext<TContextData>) => void;\n  onContextRemove?: (id: string) => void;\n  skills?: readonly PromptBarSkill<TSkillData>[];\n  /** Controlled selection. Supply onSkillChange to update it. */\n  skill?: PromptBarSkill<TSkillData> | null;\n  defaultSkill?: PromptBarSkill<TSkillData> | null;\n  onSkillChange?: (skill: PromptBarSkill<TSkillData> | null) => void;\n  toolbar?: ReactNode;\n  /** The selected model's display name, shown in the context summary. */\n  modelLabel?: string;\n  /** Provider-reported usage. Omit when measurements are unavailable. */\n  contextUsage?: PromptBarUsage;\n  onSubmit: (submission: PromptBarSubmission<TContextData, TSkillData>) => void | Promise<void>;\n  /** A synchronous cancellation callback, for example AbortController.abort. */\n  onStop?: () => void;\n  submitting?: boolean;\n  error?: string;\n  disabled?: boolean;\n  placeholder?: string;\n  label?: string;\n  maxHeight?: number;\n  /** Passed to the native file picker. Validate file contents on your server. */\n  accept?: string;\n  maxFiles?: number;\n  /** Per-file limit in bytes. */\n  maxFileSize?: number;\n  className?: string;\n};\n\ntype Trigger = { kind: \"/\" | \"@\"; query: string; start: number; end: number };\n\ntype PromptChip = { key: string; label: string; icon: ReactNode; remove?: () => void; restore: () => void };\nconst ChipContext = createContext<{ chips: PromptChip[]; disabled: boolean }>({ chips: [], disabled: false });\n\nfunction PromptChipView({ node }: NodeViewProps) {\n  const { chips, disabled } = useContext(ChipContext);\n  const chip = chips.find((item) => item.key === node.attrs.key);\n  return (\n    <NodeViewWrapper as=\"span\" contentEditable={false} className=\"inline-block max-w-full align-baseline\">\n      <Badge variant=\"secondary\" className={cn(\"group/chip relative mx-0.5 h-6 max-w-full min-w-0 gap-1.5 rounded-md px-1.5 align-baseline font-normal\", chip?.remove && \"pr-6\")}>\n        <span aria-hidden className=\"shrink-0 [&_svg]:size-3\">{chip?.icon || <AtSign />}</span>\n        <span className=\"max-w-52 truncate\">{chip?.label || node.attrs.label}</span>\n        {chip?.remove && <InputGroupButton size=\"icon-xs\" disabled={disabled} aria-label={`Remove ${chip.label}`} onMouseDown={(event) => event.preventDefault()} onClick={chip.remove} className=\"absolute right-0 top-0 size-6 cursor-pointer bg-secondary opacity-0 transition-opacity group-hover/chip:opacity-100 group-focus-within/chip:opacity-100 [@media(hover:none)]:opacity-100\"><X aria-hidden /></InputGroupButton>}\n      </Badge>\n    </NodeViewWrapper>\n  );\n}\n\nconst PromptChipNode = Node.create({\n  name: \"promptChip\", group: \"inline\", inline: true, atom: true, selectable: false,\n  addAttributes: () => ({ key: { default: \"\" }, label: { default: \"\" } }),\n  // Chips can only be created through this component, never by pasted HTML.\n  parseHTML: () => [],\n  renderHTML: ({ node }) => [\"span\", { \"data-prompt-chip\": node.attrs.key }, node.attrs.label],\n  renderText: ({ node }) => node.attrs.label,\n  addNodeView: () => ReactNodeViewRenderer(PromptChipView),\n});\n\nfunction promptText(editor: Editor) {\n  return editor.state.doc.textBetween(0, editor.state.doc.content.size, \"\\n\", (node) => node.type.name === \"hardBreak\" ? \"\\n\" : \"\");\n}\n\nfunction textDocument(text: string): JSONContent {\n  return { type: \"doc\", content: text.split(\"\\n\").map((line) => ({ type: \"paragraph\", content: line ? [{ type: \"text\", text: line }] : [] })) };\n}\n\nexport function PromptBar<TContextData = unknown, TSkillData = unknown>({\n  value, defaultValue = \"\", onValueChange, contexts = [], contextOptions = [],\n  onContextAdd, onContextRemove, skills = [], skill: controlledSkill, defaultSkill = null,\n  onSkillChange, toolbar, modelLabel, contextUsage, onSubmit, onStop,\n  submitting = false, error, disabled = false,\n  placeholder = \"Ask anything...\", label = \"Your prompt\", maxHeight = 240,\n  accept, maxFiles = 5, maxFileSize = 10 * 1024 * 1024, className,\n}: PromptBarProps<TContextData, TSkillData>) {\n  const id = useId();\n  const reducedMotion = useReducedMotion();\n  const formRef = useRef<HTMLFormElement>(null);\n  const fileInputRef = useRef<HTMLInputElement>(null);\n  const listRef = useRef<HTMLDivElement>(null);\n  const optionRefs = useRef(new Map<string, HTMLDivElement>());\n  const inFlight = useRef(false);\n  const requestId = useRef(0);\n  const composing = useRef(false);\n  const syncingEditor = useRef(false);\n  const chipHistory = useRef(new Map<string, PromptChip>());\n  const [draft, setDraft] = useState(defaultValue);\n  const [expanded, setExpanded] = useState(Boolean(defaultValue || value || contexts.length));\n  const [pending, setPending] = useState(false);\n  const [submitError, setSubmitError] = useState<string>();\n  const [status, setStatus] = useState(\"\");\n  const [attachments, setAttachments] = useState<File[]>([]);\n  const [selectedSkill, setSelectedSkill] = useState<PromptBarSkill<TSkillData> | null>(defaultSkill);\n  const skill = controlledSkill === undefined ? selectedSkill : controlledSkill;\n  const [trigger, setTrigger] = useState<Trigger | null>(null);\n  const [selectedId, setSelectedId] = useState(\"\");\n  const [contextOpen, setContextOpen] = useState(false);\n  const text = value ?? draft;\n  const busy = pending || submitting;\n  const canSubmit = Boolean(text.trim() || attachments.length);\n  const message = error || submitError;\n  const isExpanded = expanded || Boolean(text || contexts.length || attachments.length || skill);\n  const heightLimit = Number.isFinite(maxHeight) ? Math.max(96, maxHeight) : 240;\n  const fileLimit = Number.isFinite(maxFiles) ? Math.max(1, Math.floor(maxFiles)) : 5;\n  const sizeLimit = Number.isFinite(maxFileSize) ? Math.max(1, maxFileSize) : 10 * 1024 * 1024;\n  const options = (trigger?.kind === \"/\"\n    ? skills.map((option) => ({ ...option, select: () => updateSkill(option) }))\n    : contextOptions.filter((option) => !contexts.some((context) => context.id === option.id))\n      .map((option) => ({ ...option, select: () => onContextAdd?.(option) }))\n  ).filter((option) => `${option.id} ${option.label} ${option.description || \"\"}`.toLowerCase().includes(trigger?.query.toLowerCase() || \"\"));\n  const activeId = options.some((option) => option.id === selectedId) ? selectedId : options[0]?.id;\n  const menuOpen = Boolean(trigger) && !disabled && !busy;\n  if (contextUsage && (\n    !Number.isFinite(contextUsage.usedTokens) || contextUsage.usedTokens < 0 ||\n    !Number.isFinite(contextUsage.maxTokens) || contextUsage.maxTokens <= 0 ||\n    (contextUsage.cacheHitRate !== undefined && (!Number.isFinite(contextUsage.cacheHitRate) || contextUsage.cacheHitRate < 0 || contextUsage.cacheHitRate > 100))\n  )) throw new RangeError(\"PromptBar contextUsage requires non-negative usedTokens, positive maxTokens, and a cacheHitRate between 0 and 100.\");\n  const usagePercent = contextUsage ? contextUsage.usedTokens / contextUsage.maxTokens * 100 : undefined;\n  const compactTokens = new Intl.NumberFormat(\"en-US\", { notation: \"compact\", maximumFractionDigits: 1 });\n  const contextCount = contexts.length + attachments.length + (skill ? 1 : 0);\n  const contextSummary = [\n    `${contexts.length} context ${contexts.length === 1 ? \"item\" : \"items\"}`,\n    skill ? `${skill.label} skill` : \"No skill selected\",\n    `${attachments.length} ${attachments.length === 1 ? \"attachment\" : \"attachments\"}`,\n    modelLabel,\n    contextUsage ? `${contextUsage.usedTokens.toLocaleString(\"en-US\")} of ${contextUsage.maxTokens.toLocaleString(\"en-US\")} context tokens used, ${usagePercent?.toFixed(1)} percent` : \"Context usage unavailable\",\n    contextUsage?.cacheHitRate !== undefined ? `Average cache hit rate ${contextUsage.cacheHitRate.toFixed(1)} percent` : null,\n  ].filter(Boolean).join(\". \");\n\n  const updateSkill = useCallback((next: PromptBarSkill<TSkillData> | null) => {\n    if (controlledSkill === undefined) setSelectedSkill(next);\n    onSkillChange?.(next);\n  }, [controlledSkill, onSkillChange]);\n  const chips: PromptChip[] = useMemo(() => [\n    ...(skill ? [{ key: `skill-${skill.id}`, label: skill.label, icon: skill.icon || <Zap />, remove: () => updateSkill(null), restore: () => updateSkill(skill) }] : []),\n    ...contexts.map((context) => ({ key: `context-${context.id}`, label: context.label, icon: context.icon || <AtSign />, remove: onContextRemove ? () => onContextRemove(context.id) : undefined, restore: () => onContextAdd?.(context) })),\n    ...attachments.map((file) => ({ key: `file-${file.name}-${file.size}-${file.lastModified}`, label: file.name, icon: <FileText />, remove: () => setAttachments((current) => current.filter((item) => item !== file)), restore: () => setAttachments((current) => current.includes(file) ? current : [...current, file]) })),\n  ], [skill, updateSkill, contexts, onContextRemove, onContextAdd, attachments]);\n  const editor = useEditor({\n    immediatelyRender: false,\n    extensions: [StarterKit.configure({\n      blockquote: false, bold: false, bulletList: false, code: false, codeBlock: false,\n      dropcursor: false, gapcursor: false, heading: false, horizontalRule: false,\n      italic: false, link: false, listItem: false, listKeymap: false, orderedList: false,\n      strike: false, trailingNode: false, underline: false,\n    }), PromptChipNode],\n    content: textDocument(text),\n    onFocus: () => setExpanded(true),\n    onUpdate: ({ editor: current }) => {\n      if (syncingEditor.current) return;\n      const present = new Set<string>();\n      current.state.doc.descendants((node) => { if (node.type.name === \"promptChip\") present.add(node.attrs.key); });\n      for (const chip of chips) if (!present.has(chip.key)) chip.remove?.();\n      for (const key of present) if (!chips.some((chip) => chip.key === key)) chipHistory.current.get(key)?.restore();\n      updateText(promptText(current));\n      findTrigger(current);\n    },\n    onSelectionUpdate: ({ editor: current }) => findTrigger(current),\n    editorProps: {\n      attributes: {\n        id, \"data-slot\": \"input-group-control\", class: \"whitespace-pre-wrap break-words outline-none [&_p]:m-0\",\n        role: \"combobox\", \"aria-label\": label, \"aria-multiline\": \"true\",\n        \"aria-autocomplete\": \"list\", \"aria-haspopup\": \"listbox\",\n        \"aria-expanded\": String(menuOpen), \"aria-invalid\": String(Boolean(message)),\n        \"aria-disabled\": String(disabled), \"aria-readonly\": String(busy),\n        \"aria-describedby\": `${id}-hint${message ? ` ${id}-error` : \"\"}`,\n      },\n      handleKeyDown: (_view, event) => handleEditorKey(event),\n      handlePaste: (view, event) => {\n        event.preventDefault();\n        const pasted = event.clipboardData?.getData(\"text/plain\") || \"\";\n        if (pasted) view.dispatch(view.state.tr.insertText(pasted.replace(/\\r\\n?/g, \"\\n\")));\n        return true;\n      },\n    },\n  });\n\n  // Keep app-owned selections in the document without rebuilding it while typing.\n  // Existing chips retain their positions; newly supplied chips use the caret.\n  useEffect(() => {\n    if (!editor) return;\n    for (const chip of chips) chipHistory.current.set(chip.key, chip);\n    if (editor.isEditable !== (!disabled && !busy)) editor.setEditable(!disabled && !busy, false);\n    const transaction = editor.state.tr.setMeta(\"addToHistory\", false);\n    const present = new Set<string>();\n    editor.state.doc.descendants((node, position) => {\n      if (node.type.name !== \"promptChip\") return;\n      if (chips.some((chip) => chip.key === node.attrs.key) && !present.has(node.attrs.key)) present.add(node.attrs.key);\n      else transaction.delete(transaction.mapping.map(position), transaction.mapping.map(position + node.nodeSize));\n    });\n    let position = transaction.mapping.map(editor.state.selection.from);\n    for (const chip of chips) {\n      if (present.has(chip.key)) continue;\n      transaction.insert(position, editor.schema.nodes.promptChip.create({ key: chip.key, label: chip.label }));\n      position += 1;\n    }\n    if (transaction.docChanged) {\n      syncingEditor.current = true;\n      editor.view.dispatch(transaction);\n      syncingEditor.current = false;\n    }\n  }, [editor, chips, disabled, busy]);\n\n  useEffect(() => {\n    if (editor && value !== undefined && promptText(editor) !== value) {\n      // A consumer replacing the controlled value replaces the text, retaining\n      // selected metadata inline at the start of the new draft.\n      const document = textDocument(value);\n      document.content![0].content!.unshift(...chips.map((chip) => ({ type: \"promptChip\", attrs: { key: chip.key, label: chip.label } })));\n      editor.commands.setContent(document, { emitUpdate: false });\n    }\n    // Only a changed controlled value replaces text. Ordinary editor transactions\n    // must not reset the document or caret while onValueChange is being delivered.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [editor, value]);\n\n  // cmdk owns the generated list and option IDs. Connect the editor to those\n  // actual nodes while keeping typing focus out of the non-modal popover.\n  useEffect(() => {\n    const frame = requestAnimationFrame(() => {\n      const input = editor?.view.dom;\n      const option = activeId ? optionRefs.current.get(activeId) : undefined;\n      if (menuOpen && listRef.current) input?.setAttribute(\"aria-controls\", listRef.current.id);\n      else input?.removeAttribute(\"aria-controls\");\n      if (menuOpen && option) {\n        input?.setAttribute(\"aria-activedescendant\", option.id);\n        option.scrollIntoView({ block: \"nearest\" });\n      } else input?.removeAttribute(\"aria-activedescendant\");\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [editor, menuOpen, activeId]);\n\n  useEffect(() => () => { requestId.current += 1; }, []);\n\n  function updateText(next: string) {\n    if (value === undefined) setDraft(next);\n    onValueChange?.(next);\n    setSubmitError(undefined);\n    setStatus(\"\");\n  }\n\n  function findTrigger(current: Editor) {\n    const { $from, empty } = current.state.selection;\n    const before = $from.parent.textBetween(0, $from.parentOffset, \"\", \"\\uFFFC\");\n    const match = empty && before.match(/(?:^|[\\s\\uFFFC])([/@])([^\\s/@\\uFFFC]*)$/);\n    if (!match || (match[1] === \"/\" ? !skills.length : !onContextAdd)) {\n      setTrigger(null);\n      return;\n    }\n    setTrigger({ kind: match[1] as \"/\" | \"@\", query: match[2], start: $from.pos - match[2].length - 1, end: $from.pos });\n  }\n\n  function choose(option: (typeof options)[number]) {\n    if (!trigger || !editor) return;\n    const key = `${trigger.kind === \"/\" ? \"skill\" : \"context\"}-${option.id}`;\n    syncingEditor.current = true;\n    editor.chain().focus().insertContentAt({ from: trigger.start, to: trigger.end }, { type: \"promptChip\", attrs: { key, label: option.label } }).run();\n    syncingEditor.current = false;\n    updateText(promptText(editor));\n    option.select();\n    setTrigger(null);\n  }\n\n  function handleEditorKey(event: KeyboardEvent) {\n    if (event.target instanceof HTMLElement && event.target.closest(\"button\")) return false;\n    if (event.isComposing || composing.current || event.keyCode === 229) return false;\n    if (menuOpen) {\n      if (event.key === \"Escape\") { setTrigger(null); return true; }\n      if ((event.key === \"ArrowDown\" || event.key === \"ArrowUp\") && options.length) {\n        const index = options.findIndex((option) => option.id === activeId);\n        setSelectedId(options[(index + (event.key === \"ArrowDown\" ? 1 : -1) + options.length) % options.length].id);\n        return true;\n      }\n      if ((event.key === \"Enter\" && !event.shiftKey) || event.key === \"Tab\") {\n        const option = options.find((item) => item.id === activeId);\n        if (option) choose(option);\n        return Boolean(option) || event.key === \"Enter\";\n      }\n    }\n    if (event.key === \"Escape\" && !text && !chips.length) { setExpanded(false); editor?.commands.blur(); return true; }\n    if (event.key === \"Enter\" && !event.shiftKey) { formRef.current?.requestSubmit(); return true; }\n    return false;\n  }\n\n  function attach(files: FileList | null) {\n    if (!files?.length) return;\n    const next = [...attachments];\n    for (const file of Array.from(files)) {\n      if (file.size > sizeLimit) {\n        setSubmitError(`${file.name} exceeds the ${Math.round(sizeLimit / 1024 / 1024 * 10) / 10} MB limit.`);\n        return;\n      }\n      if (!next.some((item) => item.name === file.name && item.size === file.size && item.lastModified === file.lastModified)) next.push(file);\n    }\n    if (next.length > fileLimit) {\n      setSubmitError(`Attach up to ${fileLimit} files at a time.`);\n      return;\n    }\n    setAttachments(next);\n    setSubmitError(undefined);\n    setExpanded(true);\n    editor?.commands.focus();\n  }\n\n  async function submit(event: FormEvent<HTMLFormElement>) {\n    event.preventDefault();\n    if (disabled || busy || inFlight.current || !canSubmit) return;\n    const currentRequest = ++requestId.current;\n    inFlight.current = true;\n    setPending(true);\n    setTrigger(null);\n    setSubmitError(undefined);\n    setStatus(\"\");\n    try {\n      await onSubmit({ text: text.trim(), contexts: [...contexts], skill, attachments: [...attachments] });\n      if (currentRequest !== requestId.current) return;\n      if (editor && promptText(editor) === text) {\n        // A sent draft starts a new editing history. Undo must not resurrect\n        // files or commands from an already submitted prompt.\n        editor.view.updateState(EditorState.create({\n          schema: editor.schema, doc: editor.schema.nodeFromJSON(textDocument(\"\")),\n          plugins: editor.state.plugins,\n        }));\n        chipHistory.current.clear();\n        updateText(\"\");\n      }\n      setAttachments([]);\n      updateSkill(null);\n      setStatus(\"Prompt sent.\");\n    } catch (cause) {\n      if (currentRequest !== requestId.current) return;\n      setSubmitError(cause instanceof Error && cause.message ? cause.message : \"The prompt could not be sent. Try again.\");\n    } finally {\n      if (currentRequest === requestId.current) {\n        inFlight.current = false;\n        setPending(false);\n      }\n    }\n  }\n\n  function stop() {\n    try {\n      onStop?.();\n      requestId.current += 1;\n      inFlight.current = false;\n      setPending(false);\n      setStatus(\"Stopped. Your draft is kept.\");\n      editor?.commands.focus();\n    } catch (cause) {\n      setSubmitError(cause instanceof Error ? cause.message : \"Could not stop the request.\");\n    }\n  }\n\n  return (\n    <ChipContext.Provider value={{ chips, disabled: disabled || busy }}>\n    <form ref={formRef} onSubmit={submit} className={cn(\"w-full min-w-0\", className)}>\n      <FieldGroup>\n      <Field data-invalid={Boolean(message)} data-disabled={disabled} className=\"gap-2\">\n        <FieldLabel htmlFor={id} className=\"sr-only\">{label}</FieldLabel>\n        <input ref={fileInputRef} type=\"file\" accept={accept} multiple tabIndex={-1} className=\"hidden\" aria-label=\"Choose attachments\" disabled={disabled || busy} onChange={(event) => {\n          attach(event.target.files);\n          event.target.value = \"\";\n        }} />\n        <Popover open={menuOpen} onOpenChange={(open) => { if (!open) setTrigger(null); }}>\n          <PopoverAnchor asChild>\n            <motion.div layout={!reducedMotion} transition={{ duration: reducedMotion ? 0 : 0.22, ease: [0.22, 1, 0.36, 1] }}>\n              <InputGroup aria-busy={busy} data-disabled={disabled} className={cn(\"block h-auto rounded-xl border-0 bg-transparent! ring-1 ring-inset ring-border has-disabled:opacity-100 data-[disabled=true]:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:ring-1 has-[[data-slot][aria-invalid=true]]:ring-1\", isExpanded && \"pb-12\")}>\n                <motion.div layout=\"position\">\n                  <div className=\"relative\">\n                  {!text && !chips.length && <span aria-hidden className={cn(\"pointer-events-none absolute left-3.5 text-sm text-muted-foreground\", isExpanded ? \"top-3.5 leading-6\" : \"top-1/2 -translate-y-1/2 leading-5\")}>{placeholder}</span>}\n                  <EditorContent\n                    editor={editor}\n                    className={cn(\"overflow-y-auto px-3.5 py-3.5 text-sm\", isExpanded ? \"leading-6 [&>.tiptap]:min-h-17\" : \"pr-30 overflow-hidden leading-5 [&>.tiptap]:min-h-5\")}\n                    style={{ maxHeight: heightLimit }}\n                    onCompositionStart={() => { composing.current = true; }}\n                    onCompositionEnd={() => { composing.current = false; }}\n                  />\n                  </div>\n                </motion.div>\n                <motion.div layout=\"position\" className={cn(\"pointer-events-none absolute right-2.5 left-2.5 flex items-center gap-1.5\", isExpanded ? \"bottom-2\" : \"top-1/2 -translate-y-1/2\")}>\n                    <motion.fieldset disabled={disabled || busy || !isExpanded} inert={!isExpanded} aria-hidden={!isExpanded} aria-label=\"Prompt options\" initial={false} animate={{ opacity: isExpanded ? 1 : 0 }} transition={{ duration: reducedMotion ? 0 : 0.18 }} className={cn(\"mr-auto min-w-0 max-w-full [&>button]:max-w-full\", isExpanded && \"pointer-events-auto\")}>\n                      {toolbar}\n                    </motion.fieldset>\n                  <div className=\"pointer-events-auto ml-auto flex shrink-0 items-center gap-0.5\">\n                    <InputGroupButton size=\"icon-sm\" disabled={disabled || busy} aria-label=\"Attach files\" title=\"Attach files\" onClick={() => fileInputRef.current?.click()}><Paperclip aria-hidden /></InputGroupButton>\n                    <HoverCard open={contextOpen && !menuOpen} onOpenChange={setContextOpen} openDelay={150} closeDelay={100}>\n                      <HoverCardTrigger asChild>\n                        <InputGroupButton size=\"icon-sm\" aria-label=\"Context details\" aria-describedby={`${id}-context-summary`} aria-expanded={contextOpen && !menuOpen} aria-controls={contextOpen && !menuOpen ? `${id}-context-card` : undefined} onClick={() => setContextOpen((open) => !open)} className=\"relative rounded-full\">\n                          <svg aria-hidden viewBox=\"0 0 32 32\" className=\"size-7! -rotate-90\" fill=\"none\">\n                            <circle cx=\"16\" cy=\"16\" r=\"11\" stroke=\"currentColor\" strokeWidth=\"2\" className=\"text-border\" />\n                            {usagePercent !== undefined && usagePercent > 0 && <circle cx=\"16\" cy=\"16\" r=\"11\" pathLength=\"100\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeDasharray={`${Math.min(100, usagePercent)} 100`} className=\"text-primary\" />}\n                          </svg>\n                        </InputGroupButton>\n                      </HoverCardTrigger>\n                      <HoverCardContent id={`${id}-context-card`} role=\"region\" aria-labelledby={`${id}-context-title`} side=\"top\" align=\"end\" sideOffset={8} collisionPadding={12} className=\"max-h-[var(--radix-hover-card-content-available-height)] w-80 max-w-[calc(100vw-1.5rem)] gap-3 overflow-y-auto motion-reduce:animate-none\">\n                        <div className=\"flex flex-col gap-3\">\n                          <div className=\"flex flex-wrap items-center justify-between gap-2\">\n                            <span id={`${id}-context-title`} className=\"font-medium\">Context window</span>\n                            <span className=\"font-mono text-xs tabular-nums text-muted-foreground\">{contextUsage ? `${compactTokens.format(contextUsage.usedTokens)}/${compactTokens.format(contextUsage.maxTokens)} (${usagePercent?.toFixed(1)}%)` : \"Usage unavailable\"}</span>\n                          </div>\n                          {usagePercent !== undefined && <Progress value={Math.min(100, usagePercent)} aria-label=\"Context window usage\" aria-valuetext={`${usagePercent.toFixed(1)}% used`} className=\"h-2.5\" />}\n                          <div className=\"flex items-center justify-between gap-3 text-xs\">\n                            <span className=\"text-muted-foreground\">Average cache hit rate</span>\n                            <span className=\"font-mono tabular-nums\">{contextUsage?.cacheHitRate !== undefined ? `${contextUsage.cacheHitRate.toFixed(1)}%` : \"Unavailable\"}</span>\n                          </div>\n                        </div>\n                        <Separator />\n                        <div className=\"flex items-center justify-between gap-3\">\n                          <span className=\"text-xs font-medium\">Included context</span>\n                          <span className=\"font-mono text-xs text-muted-foreground\">{contextCount} {contextCount === 1 ? \"item\" : \"items\"}</span>\n                        </div>\n                        <div className=\"flex flex-col gap-2\">\n                          {[\n                            { label: \"Context\", items: contexts, icon: <AtSign />, empty: \"No context added\" },\n                            { label: \"Skill\", items: skill ? [skill] : [], icon: <Zap />, empty: \"No skill selected\" },\n                            { label: \"Attachments\", items: attachments.map((file, index) => ({ id: String(index), label: file.name, description: `${Math.max(1, Math.ceil(file.size / 1024)).toLocaleString()} KB` })), icon: <Paperclip />, empty: \"No files attached\" },\n                          ].map((group) => (\n                            <div key={group.label} className=\"flex items-start gap-2.5\">\n                              <span aria-hidden className=\"pt-0.5 text-muted-foreground [&_svg]:size-3.5\">{group.icon}</span>\n                              <div className=\"min-w-0 flex-1\">\n                                <p className=\"text-xs font-medium\">{group.label}</p>\n                                {group.items.length ? <ul className=\"mt-1 flex flex-col gap-1.5\">{group.items.map((item) => <li key={item.id} className=\"text-xs\"><span className=\"block break-words\">{item.label}</span>{item.description && <span className=\"block text-muted-foreground\">{item.description}</span>}</li>)}</ul> : <p className=\"text-xs text-muted-foreground\">{group.empty}</p>}\n                              </div>\n                            </div>\n                          ))}\n                        </div>\n                        <Separator />\n                        <div className=\"flex flex-col gap-2 text-xs\">\n                          {modelLabel && <div className=\"flex items-start justify-between gap-3\"><span className=\"text-muted-foreground\">Model</span><span className=\"text-right\">{modelLabel}</span></div>}\n                          <span className=\"font-medium\">Tools</span>\n                          {skills.length > 0 && <div className=\"flex items-center justify-between gap-3\"><span className=\"text-muted-foreground\">{skills.length} skills available</span><kbd className=\"font-mono\">/</kbd></div>}\n                          {onContextAdd && <div className=\"flex items-center justify-between gap-3\"><span className=\"text-muted-foreground\">Add context</span><kbd className=\"font-mono\">@</kbd></div>}\n                          <p className=\"text-muted-foreground\">Attach up to {fileLimit} files, {Math.round(sizeLimit / 1024 / 1024 * 10) / 10} MB each.</p>\n                        </div>\n                      </HoverCardContent>\n                    </HoverCard>\n                    <InputGroupButton key={busy ? \"stop\" : \"send\"} type={busy && onStop ? \"button\" : \"submit\"} variant={busy || canSubmit ? \"default\" : \"ghost\"} size=\"icon-sm\" disabled={disabled || (busy ? !onStop : !canSubmit)} aria-label={busy ? (onStop ? \"Stop response\" : \"Sending prompt\") : \"Send prompt\"} onClick={() => { if (busy && onStop) stop(); }} className=\"ml-1 cursor-pointer rounded-lg\">\n                      {busy ? (onStop ? <Square aria-hidden /> : <LoaderCircle aria-hidden className=\"animate-spin motion-reduce:animate-none\" />) : <ArrowUp aria-hidden />}\n                    </InputGroupButton>\n                  </div>\n                </motion.div>\n              </InputGroup>\n            </motion.div>\n          </PopoverAnchor>\n          <PopoverContent side=\"top\" align=\"start\" sideOffset={8} className=\"w-[var(--radix-popover-trigger-width)] max-w-[calc(100vw-2rem)] p-0\" onOpenAutoFocus={(event) => event.preventDefault()} onCloseAutoFocus={(event) => event.preventDefault()} onInteractOutside={(event) => { if (event.target instanceof globalThis.Node && editor?.view.dom.contains(event.target)) event.preventDefault(); }}>\n            <Command shouldFilter={false} value={activeId || \"\"} onValueChange={setSelectedId}>\n              <CommandList ref={listRef} aria-label={trigger?.kind === \"/\" ? \"Skills\" : \"Context\"}>\n                <CommandEmpty>No {trigger?.kind === \"/\" ? \"skills\" : \"context\"} found.</CommandEmpty>\n                <CommandGroup heading={trigger?.kind === \"/\" ? \"Skills\" : \"Add context\"}>\n                  {options.map((option) => (\n                    <CommandItem key={option.id} value={option.id} ref={(node) => { if (node) optionRefs.current.set(option.id, node); else optionRefs.current.delete(option.id); }} onSelect={() => choose(option)} onMouseDown={(event) => event.preventDefault()} className=\"cursor-pointer gap-2.5 py-2\">\n                      <span aria-hidden className=\"shrink-0 [&_svg]:size-4\">{option.icon || (trigger?.kind === \"/\" ? <Zap /> : <FileText />)}</span>\n                      <span className=\"min-w-0\"><span className=\"block truncate\">{option.label}</span>{option.description && <span className=\"block text-xs text-muted-foreground\">{option.description}</span>}</span>\n                    </CommandItem>\n                  ))}\n                </CommandGroup>\n              </CommandList>\n            </Command>\n          </PopoverContent>\n        </Popover>\n        <p id={`${id}-hint`} className=\"sr-only\">Type / for skills or @ for context. Use arrow keys and Enter to choose. Enter to send, Shift+Enter for a new line. Escape closes suggestions or collapses an empty prompt.</p>\n        <p id={`${id}-context-summary`} className=\"sr-only\">{contextSummary}</p>\n        {message && <FieldError id={`${id}-error`} className=\"text-xs\">{message}</FieldError>}\n        <p role=\"status\" aria-live=\"polite\" className=\"sr-only\">{busy ? \"Sending prompt...\" : status}</p>\n      </Field>\n      </FieldGroup>\n    </form>\n    </ChipContext.Provider>\n  );\n}\n",
      "type": "registry:ui"
    }
  ],
  "docs": "## Installation\n\n```bash\nnpx shadcn add @akoder/prompt-bar\n```\n\n## Usage\n\n```tsx\nimport { PromptBar } from \"@/components/ui/prompt-bar\";\n\nexport function Input({ send }: { send: (text: string) => Promise<void> }) {\n  return <PromptBar onSubmit={({ text }) => send(text)} />;\n}\n```\n\nSupply `/` choices through `skills` and `@` choices through `contextOptions`. Update `contexts` in `onContextAdd` and `onContextRemove`. Skills accept `instructions`; both item types accept consumer-defined `data`, preserved in callbacks and `onSubmit`. Use `PromptBar<TContextData, TSkillData>` for typed payloads. Control skill selection with `skill` and `onSkillChange`, or initialize it with `defaultSkill`. Your app builds the prompt and loads or uploads files; the prompt bar does not execute commands or append their payloads to text. See https://akoder.xyz/components/prompt-bar for a complete prompt-building example and the props reference. Compose an optional model picker through `toolbar`. The component awaits `onSubmit`, clears the draft and selected skill only on success, and preserves them on failure or cancellation. Use `onStop` to cancel work in your app. No AI client or site analytics are bundled."
}