{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prompt-composer",
  "title": "Prompt composer",
  "description": "Rich prompt input with slash commands, file attachments, model picker, token counter and a history of sent prompts.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "button",
    "dropdown-menu"
  ],
  "files": [
    {
      "path": "registry/blocks/ai/prompt-composer.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport {\n  ArrowUp,\n  Check,\n  ChevronDown,\n  Copy,\n  CornerDownLeft,\n  FileSpreadsheet,\n  FileText,\n  Image as ImageIcon,\n  Languages,\n  ListCollapse,\n  Megaphone,\n  MessageSquareReply,\n  Paperclip,\n  RotateCcw,\n  Slash,\n  Sparkles,\n  Wand2,\n  X,\n} from \"lucide-react\"\nimport { Button } from \"@/components/ui/button\"\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from \"@/components/ui/dropdown-menu\"\nimport { cn } from \"@/lib/utils\"\n\ntype Attachment = { id: string; name: string; size: number; type: string }\ntype Entry = { id: number; text: string; files: Attachment[]; model: string; tokens: number; at: number }\ntype Command = { cmd: string; label: string; hint: string; icon: React.ElementType; insert?: string; attach?: Attachment }\n\nconst LIMIT = 4000\n\nconst MODELS = [\n  { id: \"atlas-pro\", name: \"Atlas Pro\", context: \"200k context\" },\n  { id: \"atlas-mini\", name: \"Atlas Mini\", context: \"128k context · fastest\" },\n  { id: \"atlas-vision\", name: \"Atlas Vision\", context: \"Reads images and PDFs\" },\n]\n\nconst COMMANDS: Command[] = [\n  { cmd: \"summarize\", label: \"Summarize\", hint: \"Condense notes or a thread\", icon: ListCollapse, insert: \"Summarize the following in 3 short bullet points:\\n\" },\n  { cmd: \"reply\", label: \"Draft reply\", hint: \"Answer a client message\", icon: MessageSquareReply, insert: \"Draft a warm, short reply to this client message:\\n\" },\n  { cmd: \"promo\", label: \"Promo campaign\", hint: \"SMS + email to fill quiet slots\", icon: Megaphone, insert: \"Write an SMS and an email that fill our quiet Tuesday mornings with 15% off. Keep the SMS under 160 characters.\\n\" },\n  { cmd: \"translate\", label: \"Translate\", hint: \"Keep tone, change language\", icon: Languages, insert: \"Translate into Spanish and keep the friendly tone:\\n\" },\n  { cmd: \"tone\", label: \"Change tone\", hint: \"Friendlier, shorter or formal\", icon: Wand2, insert: \"Rewrite this so it sounds friendlier and half as long:\\n\" },\n  { cmd: \"attach\", label: \"Attach sample data\", hint: \"bookings-october.csv\", icon: FileSpreadsheet, attach: { id: \"sample\", name: \"bookings-october.csv\", size: 48_312, type: \"text/csv\" } },\n]\n\nconst fmtSize = (b: number) => (b < 1024 ? `${b} B` : b < 1024 * 1024 ? `${(b / 1024).toFixed(b < 10_240 ? 1 : 0)} KB` : `${(b / 1024 / 1024).toFixed(1)} MB`)\nconst tokensOf = (text: string, files: Attachment[]) => Math.ceil(text.length / 4) + files.reduce((n, f) => n + Math.min(2000, Math.ceil(f.size / 40)), 0)\n\nfunction FileIcon({ type, className }: { type: string; className?: string }) {\n  if (type.startsWith(\"image/\")) return <ImageIcon className={className} />\n  if (type.includes(\"csv\") || type.includes(\"sheet\") || type.includes(\"excel\")) return <FileSpreadsheet className={className} />\n  return <FileText className={className} />\n}\n\nexport default function PromptComposer() {\n  const [value, setValue] = React.useState(\"\")\n  const [files, setFiles] = React.useState<Attachment[]>([])\n  const [model, setModel] = React.useState(MODELS[0]!)\n  const [history, setHistory] = React.useState<Entry[]>([])\n  const [menu, setMenu] = React.useState<{ start: number; query: string } | null>(null)\n  const [highlight, setHighlight] = React.useState(0)\n  const [copied, setCopied] = React.useState<number | null>(null)\n  const area = React.useRef<HTMLTextAreaElement>(null)\n  const fileInput = React.useRef<HTMLInputElement>(null)\n  const caret = React.useRef<number | null>(null)\n  const nextId = React.useRef(1)\n  const listBox = React.useRef<HTMLDivElement>(null)\n\n  // Auto-grow the textarea and restore the caret after a command was inserted.\n  React.useLayoutEffect(() => {\n    const el = area.current\n    if (!el) return\n    el.style.height = \"auto\"\n    el.style.height = `${Math.min(el.scrollHeight, 240)}px`\n    if (caret.current !== null) {\n      el.focus()\n      el.setSelectionRange(caret.current, caret.current)\n      caret.current = null\n    }\n  }, [value])\n\n  React.useEffect(() => {\n    const el = listBox.current\n    if (el && history.length) el.scrollTo({ top: el.scrollHeight, behavior: \"smooth\" })\n  }, [history.length])\n\n  const matches = menu ? COMMANDS.filter((c) => c.cmd.startsWith(menu.query.toLowerCase()) || c.label.toLowerCase().includes(menu.query.toLowerCase())) : []\n  const tokens = tokensOf(value, files)\n  const over = value.length > LIMIT\n  const canSend = (value.trim().length > 0 || files.length > 0) && !over\n\n  const detect = (text: string, pos: number) => {\n    const m = /(?:^|\\s)\\/(\\w*)$/.exec(text.slice(0, pos))\n    if (m) {\n      const query = m[1] ?? \"\"\n      setMenu({ start: pos - query.length - 1, query })\n      setHighlight(0)\n    } else setMenu(null)\n  }\n\n  const pick = (c: Command) => {\n    if (!menu) return\n    const end = menu.start + 1 + menu.query.length\n    const before = value.slice(0, menu.start)\n    const after = value.slice(end)\n    if (c.attach) {\n      const att = c.attach\n      setFiles((f) => (f.some((x) => x.id === att.id) ? f : [...f, att]))\n      caret.current = before.length\n      setValue(before + after)\n    } else {\n      const ins = c.insert ?? \"\"\n      caret.current = before.length + ins.length\n      setValue(before + ins + after)\n    }\n    setMenu(null)\n  }\n\n  const addFiles = (list: FileList | null) => {\n    if (!list) return\n    const added = Array.from(list).map((f, i) => ({ id: `${f.name}-${f.size}-${f.lastModified}-${i}`, name: f.name, size: f.size, type: f.type || \"application/octet-stream\" }))\n    setFiles((cur) => [...cur, ...added.filter((a) => !cur.some((c) => c.id === a.id))])\n    if (fileInput.current) fileInput.current.value = \"\"\n    area.current?.focus()\n  }\n\n  const submit = () => {\n    if (!canSend) return\n    setHistory((h) => [...h, { id: nextId.current++, text: value.trim(), files, model: model.name, tokens, at: Date.now() }])\n    setValue(\"\")\n    setFiles([])\n    setMenu(null)\n  }\n\n  const reuse = (e: Entry) => {\n    setFiles(e.files)\n    caret.current = e.text.length\n    setValue(e.text)\n  }\n\n  const copy = (e: Entry) => {\n    navigator.clipboard?.writeText(e.text).catch(() => {})\n    setCopied(e.id)\n    setTimeout(() => setCopied((c) => (c === e.id ? null : c)), 1500)\n  }\n\n  return (\n    <div className=\"p-4 md:p-6\">\n      <div className=\"mx-auto flex max-w-2xl flex-col gap-4\">\n        {/* History */}\n        <div ref={listBox} className=\"flex max-h-[300px] min-h-[180px] flex-col gap-3 overflow-y-auto rounded-2xl border border-dashed bg-muted/30 p-3\">\n          {history.length === 0 ? (\n            <div className=\"flex flex-1 flex-col items-center justify-center gap-2 py-6 text-center\">\n              <div className=\"flex -space-x-2\">\n                {[ListCollapse, Megaphone, Languages].map((I, i) => (\n                  <span key={i} className=\"flex size-9 items-center justify-center rounded-full border-2 border-background bg-card shadow-xs\">\n                    <I className=\"size-4 text-muted-foreground\" />\n                  </span>\n                ))}\n              </div>\n              <p className=\"text-sm font-medium\">Prompts you send show up here</p>\n              <p className=\"text-xs text-muted-foreground\">Type <kbd className=\"rounded border bg-background px-1 font-mono\">/</kbd> for commands or attach a file to start.</p>\n            </div>\n          ) : (\n            history.map((e) => (\n              <div key={e.id} className=\"group rounded-xl border bg-card p-3 shadow-xs animate-in fade-in-0 slide-in-from-bottom-2\">\n                <p className=\"line-clamp-4 text-sm whitespace-pre-wrap\">{e.text || <span className=\"text-muted-foreground italic\">Attachments only</span>}</p>\n                {e.files.length > 0 && (\n                  <div className=\"mt-2 flex flex-wrap gap-1.5\">\n                    {e.files.map((f) => (\n                      <span key={f.id} className=\"inline-flex max-w-full items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground\">\n                        <FileIcon type={f.type} className=\"size-3 shrink-0\" /> <span className=\"truncate\">{f.name}</span>\n                      </span>\n                    ))}\n                  </div>\n                )}\n                <div className=\"mt-2 flex items-center gap-2 text-[11px] text-muted-foreground\">\n                  <span>{e.model}</span>·<span className=\"tabular-nums\">{e.tokens.toLocaleString(\"en-US\")} tokens</span>·\n                  <span>{new Intl.DateTimeFormat(undefined, { hour: \"numeric\", minute: \"2-digit\" }).format(e.at)}</span>\n                  <span className=\"ml-auto flex gap-0.5\">\n                    <Button variant=\"ghost\" size=\"icon-xs\" aria-label=\"Copy prompt\" onClick={() => copy(e)}>\n                      {copied === e.id ? <Check className=\"text-emerald-600 dark:text-emerald-400\" /> : <Copy />}\n                    </Button>\n                    <Button variant=\"ghost\" size=\"xs\" onClick={() => reuse(e)}>\n                      <RotateCcw /> Reuse\n                    </Button>\n                  </span>\n                </div>\n              </div>\n            ))\n          )}\n        </div>\n\n        {/* Composer */}\n        <div className=\"relative rounded-[22px] bg-gradient-to-br from-[var(--chart-1)] via-[var(--chart-3)] to-[var(--chart-5)] p-px shadow-lg shadow-primary/5\">\n          {/* Slash menu */}\n          {menu && (\n            <div className=\"absolute inset-x-3 bottom-full z-20 mb-2 overflow-hidden rounded-xl border bg-popover text-popover-foreground shadow-xl animate-in fade-in-0 slide-in-from-bottom-1\" role=\"listbox\" aria-label=\"Commands\">\n              <div className=\"flex items-center gap-1.5 border-b px-3 py-2 text-xs text-muted-foreground\">\n                <Slash className=\"size-3\" /> Commands {menu.query && <span>matching “{menu.query}”</span>}\n              </div>\n              {matches.length === 0 ? (\n                <p className=\"px-3 py-3 text-sm text-muted-foreground\">No command found. Keep typing or press Esc.</p>\n              ) : (\n                <div className=\"max-h-64 overflow-y-auto p-1\">\n                  {matches.map((c, i) => (\n                    <button\n                      key={c.cmd}\n                      type=\"button\"\n                      role=\"option\"\n                      aria-selected={i === highlight}\n                      onMouseDown={(ev) => ev.preventDefault()}\n                      onMouseEnter={() => setHighlight(i)}\n                      onClick={() => pick(c)}\n                      className={cn(\"flex w-full items-center gap-3 rounded-lg px-2 py-1.5 text-left\", i === highlight && \"bg-accent text-accent-foreground\")}\n                    >\n                      <span className=\"flex size-8 items-center justify-center rounded-md border bg-background\"><c.icon className=\"size-4\" /></span>\n                      <span className=\"min-w-0 flex-1\">\n                        <span className=\"block text-sm font-medium\">{c.label}</span>\n                        <span className=\"block truncate text-xs text-muted-foreground\">{c.hint}</span>\n                      </span>\n                      <span className=\"font-mono text-xs text-muted-foreground\">/{c.cmd}</span>\n                    </button>\n                  ))}\n                </div>\n              )}\n            </div>\n          )}\n\n          <div className=\"rounded-[21px] bg-card\">\n            {files.length > 0 && (\n              <div className=\"flex flex-wrap gap-2 px-3 pt-3\">\n                {files.map((f) => (\n                  <span key={f.id} className=\"group/chip inline-flex max-w-[220px] items-center gap-2 rounded-lg border bg-background py-1 pr-1 pl-1.5 animate-in fade-in-0 zoom-in-95\">\n                    <span className=\"flex size-7 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary\"><FileIcon type={f.type} className=\"size-3.5\" /></span>\n                    <span className=\"min-w-0\">\n                      <span className=\"block truncate text-xs font-medium\">{f.name}</span>\n                      <span className=\"block text-[10px] text-muted-foreground\">{fmtSize(f.size)}</span>\n                    </span>\n                    <button type=\"button\" aria-label={`Remove ${f.name}`} onClick={() => setFiles((l) => l.filter((x) => x.id !== f.id))} className=\"rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground\">\n                      <X className=\"size-3.5\" />\n                    </button>\n                  </span>\n                ))}\n              </div>\n            )}\n\n            <label htmlFor=\"pc-input\" className=\"sr-only\">Prompt</label>\n            <textarea\n              id=\"pc-input\"\n              ref={area}\n              rows={2}\n              value={value}\n              placeholder=\"Ask anything about your bookings, or type / for commands…\"\n              onChange={(e) => {\n                setValue(e.target.value)\n                detect(e.target.value, e.target.selectionStart)\n              }}\n              onClick={(e) => detect(e.currentTarget.value, e.currentTarget.selectionStart)}\n              onBlur={() => setMenu(null)}\n              onKeyDown={(e) => {\n                if (menu && matches.length) {\n                  if (e.key === \"ArrowDown\") { e.preventDefault(); setHighlight((h) => (h + 1) % matches.length); return }\n                  if (e.key === \"ArrowUp\") { e.preventDefault(); setHighlight((h) => (h - 1 + matches.length) % matches.length); return }\n                  if (e.key === \"Enter\" || e.key === \"Tab\") { e.preventDefault(); pick(matches[Math.min(highlight, matches.length - 1)]!); return }\n                }\n                if (menu && e.key === \"Escape\") { e.preventDefault(); setMenu(null); return }\n                if (e.key === \"Enter\" && !e.shiftKey && !e.nativeEvent.isComposing) {\n                  e.preventDefault()\n                  submit()\n                }\n              }}\n              className=\"block w-full resize-none bg-transparent px-4 pt-3.5 pb-2 text-[15px] leading-relaxed outline-none placeholder:text-muted-foreground\"\n            />\n\n            <div className=\"flex flex-wrap items-center gap-1.5 px-2.5 pb-2.5\">\n              <input ref={fileInput} type=\"file\" multiple className=\"hidden\" aria-hidden tabIndex={-1} onChange={(e) => addFiles(e.target.files)} />\n              <Button variant=\"ghost\" size=\"icon-sm\" aria-label=\"Attach files\" onClick={() => fileInput.current?.click()}>\n                <Paperclip />\n              </Button>\n              <Button\n                variant=\"ghost\"\n                size=\"icon-sm\"\n                aria-label=\"Open command menu\"\n                onClick={() => {\n                  const el = area.current\n                  const pos = el ? el.selectionStart : value.length\n                  const needsSpace = pos > 0 && !/\\s/.test(value.charAt(pos - 1))\n                  const next = value.slice(0, pos) + (needsSpace ? \" /\" : \"/\") + value.slice(pos)\n                  caret.current = pos + (needsSpace ? 2 : 1)\n                  setValue(next)\n                  setMenu({ start: pos + (needsSpace ? 1 : 0), query: \"\" })\n                  setHighlight(0)\n                }}\n              >\n                <Slash />\n              </Button>\n              <DropdownMenu>\n                <DropdownMenuTrigger className=\"inline-flex h-8 items-center gap-1.5 rounded-lg px-2 text-xs font-medium text-muted-foreground hover:bg-muted hover:text-foreground\">\n                  <Sparkles className=\"size-3.5 text-primary\" /> {model.name} <ChevronDown className=\"size-3\" />\n                </DropdownMenuTrigger>\n                <DropdownMenuContent align=\"start\" className=\"w-60\">\n                  <DropdownMenuLabel>Model</DropdownMenuLabel>\n                  {MODELS.map((m) => (\n                    <DropdownMenuItem key={m.id} onClick={() => setModel(m)}>\n                      <div className=\"flex-1\">\n                        <div className=\"text-sm\">{m.name}</div>\n                        <div className=\"text-xs text-muted-foreground\">{m.context}</div>\n                      </div>\n                      {m.id === model.id && <Check className=\"text-primary\" />}\n                    </DropdownMenuItem>\n                  ))}\n                </DropdownMenuContent>\n              </DropdownMenu>\n\n              <div className=\"ml-auto flex items-center gap-3\">\n                <span className={cn(\"hidden text-[11px] tabular-nums sm:inline\", over ? \"font-medium text-destructive\" : \"text-muted-foreground\")} aria-live=\"polite\">\n                  {value.length.toLocaleString(\"en-US\")}/{LIMIT.toLocaleString(\"en-US\")} · ~{tokens.toLocaleString(\"en-US\")} tokens\n                </span>\n                <CharRing used={value.length} />\n                <Button size=\"icon\" className=\"rounded-xl\" disabled={!canSend} onClick={submit} aria-label=\"Send prompt\">\n                  <ArrowUp />\n                </Button>\n              </div>\n            </div>\n          </div>\n        </div>\n\n        <div className=\"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-[11px] text-muted-foreground\">\n          <span className=\"inline-flex items-center gap-1\"><kbd className=\"inline-flex items-center rounded border bg-muted px-1 py-px\"><CornerDownLeft className=\"size-3\" /></kbd> Send</span>\n          <span className=\"inline-flex items-center gap-1\"><kbd className=\"rounded border bg-muted px-1 py-px font-mono\">Shift</kbd>+<kbd className=\"inline-flex items-center rounded border bg-muted px-1 py-px\"><CornerDownLeft className=\"size-3\" /></kbd> New line</span>\n          <span className=\"inline-flex items-center gap-1\"><kbd className=\"rounded border bg-muted px-1 py-px font-mono\">/</kbd> Commands</span>\n          <span className=\"sm:hidden\">{value.length}/{LIMIT} · ~{tokens} tokens</span>\n        </div>\n      </div>\n    </div>\n  )\n}\n\nfunction CharRing({ used }: { used: number }) {\n  const pct = Math.min(1, used / LIMIT)\n  const r = 9\n  const c = 2 * Math.PI * r\n  const color = used > LIMIT ? \"var(--destructive)\" : pct > 0.8 ? \"#f59e0b\" : \"var(--primary)\"\n  return (\n    <svg viewBox=\"0 0 24 24\" className=\"size-6 -rotate-90\" role=\"img\" aria-label={`${Math.round(pct * 100)}% of character limit used`}>\n      <circle cx=\"12\" cy=\"12\" r={r} fill=\"none\" stroke=\"var(--border)\" strokeWidth=\"3\" />\n      <circle cx=\"12\" cy=\"12\" r={r} fill=\"none\" stroke={color} strokeWidth=\"3\" strokeLinecap=\"round\" strokeDasharray={c} strokeDashoffset={c * (1 - pct)} className=\"transition-all duration-300\" />\n    </svg>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/prompt-composer.tsx"
    }
  ],
  "categories": [
    "ai"
  ],
  "type": "registry:block"
}