{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prompt-09",
  "title": "Queued prompts",
  "description": "Prompts sent while an answer streams wait as cards you edit, drag or move, then fly into the thread one by one as each answer ends.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/dropdown-menu.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/textarea.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-agent-run.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/prompt/prompt-09.tsx",
      "content": "'use client';\n\nimport {\n  LayoutGroup,\n  motion,\n  Reorder,\n  useAnimate,\n  useDragControls,\n} from 'motion/react';\nimport {\n  useEffect,\n  useEffectEvent,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { useDocumentVisible } from '@/registry/ndeko/hooks/use-agent-run';\nimport {\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport {\n  ArrowDownIcon,\n  ArrowUpIcon,\n  EllipsisIcon,\n  GripVerticalIcon,\n  ListChecksIcon,\n  PencilIcon,\n  PlayIcon,\n  TrashIcon,\n  XIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { EASE_OUT_STRONG, springOf } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { nounOf, wordsOf } from '@/registry/ndeko/lib/words';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuShortcut,\n  DropdownMenuTrigger,\n} from '@/registry/ndeko/ui/dropdown-menu';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\nimport { Textarea } from '@/registry/ndeko/ui/textarea';\n\nimport { isOwnKey, isSendKey, useAutosize } from './_parts/use-autosize';\n\nexport type QueuedPrompt = {\n  id: string;\n  text: string;\n};\n\nfunction moveItem<T>(items: T[], from: number, to: number) {\n  const next = [...items];\n  const [moved] = next.splice(from, 1);\n  next.splice(to, 0, moved);\n  return next;\n}\n\nfunction placeWordOf(index: number) {\n  if (index === 0) {\n    return 'Next';\n  }\n  return 'Then';\n}\n\nfunction moveStepOf(event: React.KeyboardEvent) {\n  if (!event.altKey) {\n    return 0;\n  }\n  if (event.key === 'ArrowUp') {\n    return -1;\n  }\n  if (event.key === 'ArrowDown') {\n    return 1;\n  }\n  return 0;\n}\n\nfunction settleOf(shouldReduceMotion: boolean | null) {\n  return springOf(shouldReduceMotion);\n}\n\nfunction liftOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return undefined;\n  }\n  return { scale: 1.02 };\n}\n\ntype QueuedCardProps = {\n  item: QueuedPrompt;\n  index: number;\n  count: number;\n  groupRef: React.RefObject<HTMLUListElement | null>;\n  onMove: (from: number, to: number) => void;\n  onEdit: (id: string, text: string) => void;\n  onRemove: (id: string) => void;\n};\n\nfunction QueuedCard({\n  item,\n  index,\n  count,\n  groupRef,\n  onMove,\n  onEdit,\n  onRemove,\n}: QueuedCardProps) {\n  const [isEditing, setIsEditing] = useState(false);\n  const [draft, setDraft] = useState(item.text);\n  const controls = useDragControls();\n  const textButtonRef = useRef<HTMLButtonElement>(null);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const isFirst = index === 0;\n  const isLast = index === count - 1;\n  const placeWord = placeWordOf(index);\n\n  function startDrag(event: React.PointerEvent) {\n    controls.start(event);\n  }\n\n  function startEdit() {\n    setDraft(item.text);\n    setIsEditing(true);\n  }\n\n  function endEdit(shouldSave: boolean) {\n    setIsEditing(false);\n    const trimmed = draft.trim();\n    const canSave = shouldSave && trimmed !== '';\n    if (canSave) {\n      onEdit(item.id, trimmed);\n    }\n    requestAnimationFrame(() => textButtonRef.current?.focus());\n  }\n\n  function handleFieldKeys(event: React.KeyboardEvent<HTMLInputElement>) {\n    if (event.key === 'Enter') {\n      event.preventDefault();\n      endEdit(true);\n      return;\n    }\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      event.stopPropagation();\n      endEdit(false);\n    }\n  }\n\n  function moveFromKeys(event: React.KeyboardEvent<HTMLButtonElement>) {\n    const step = moveStepOf(event);\n    if (step === 0) {\n      return;\n    }\n    event.preventDefault();\n    const target = index + step;\n    const isInside = target >= 0 && target < count;\n    if (isInside) {\n      onMove(index, target);\n    }\n  }\n\n  return (\n    <Reorder.Item\n      value={item}\n      layoutId={`prompt-${item.id}`}\n      dragListener={false}\n      dragControls={controls}\n      dragConstraints={groupRef}\n      dragElastic={0.08}\n      whileDrag={liftOf(shouldReduceMotion)}\n      transition={settleOf(shouldReduceMotion)}\n      className='bg-card hairline-ring ring-border relative flex items-center gap-1 rounded-lg py-1 ps-1 pe-1 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'\n    >\n      <span\n        aria-hidden='true'\n        onPointerDown={startDrag}\n        className='text-muted-foreground hover:bg-foreground/5 hover:text-foreground grid size-7 shrink-0 cursor-grab touch-none place-items-center rounded-md active:cursor-grabbing'\n      >\n        <GripVerticalIcon className='size-4' />\n      </span>\n      <span className='text-muted-foreground w-9 shrink-0 text-xs'>\n        <Swap swapKey={placeWord}>{placeWord}</Swap>\n      </span>\n      {isEditing && (\n        <input\n          value={draft}\n          onChange={(event) => setDraft(event.target.value)}\n          onKeyDown={handleFieldKeys}\n          onBlur={() => endEdit(true)}\n          aria-label='Edit the queued prompt'\n          autoFocus\n          className='focus-visible:ring-ring/25 bg-foreground/[0.04] h-7 min-w-0 flex-1 rounded-md px-2 text-[13px] outline-none focus-visible:ring-[3px]'\n        />\n      )}\n      {!isEditing && (\n        <button\n          ref={textButtonRef}\n          type='button'\n          onClick={startEdit}\n          onKeyDown={moveFromKeys}\n          aria-label={`${placeWord}: ${item.text}. Edit it, or move it with Alt and the arrows`}\n          className='hover:bg-foreground/[0.03] focus-visible:ring-ring/25 h-7 min-w-0 flex-1 cursor-text truncate rounded-md px-2 text-start text-[13px] outline-none focus-visible:ring-[3px]'\n        >\n          {item.text}\n        </button>\n      )}\n      <DropdownMenu>\n        <DropdownMenuTrigger\n          render={\n            <Button\n              type='button'\n              variant='ghost'\n              size='icon-sm'\n              aria-label={`More for “${item.text}”`}\n              className='text-muted-foreground'\n            />\n          }\n        >\n          <EllipsisIcon />\n        </DropdownMenuTrigger>\n        <DropdownMenuContent align='end' className='min-w-48'>\n          <DropdownMenuItem onClick={startEdit}>\n            <PencilIcon />\n            Edit\n          </DropdownMenuItem>\n          <DropdownMenuItem\n            disabled={isFirst}\n            onClick={() => onMove(index, index - 1)}\n          >\n            <ArrowUpIcon />\n            Move up\n            <DropdownMenuShortcut>Alt ↑</DropdownMenuShortcut>\n          </DropdownMenuItem>\n          <DropdownMenuItem\n            disabled={isLast}\n            onClick={() => onMove(index, index + 1)}\n          >\n            <ArrowDownIcon />\n            Move down\n            <DropdownMenuShortcut>Alt ↓</DropdownMenuShortcut>\n          </DropdownMenuItem>\n          <DropdownMenuSeparator />\n          <DropdownMenuItem\n            variant='destructive'\n            onClick={() => onRemove(item.id)}\n          >\n            <TrashIcon />\n            Remove from the queue\n          </DropdownMenuItem>\n        </DropdownMenuContent>\n      </DropdownMenu>\n      <Button\n        type='button'\n        variant='ghost'\n        size='icon-sm'\n        aria-label={`Remove “${item.text}” from the queue`}\n        onClick={() => onRemove(item.id)}\n        className='text-muted-foreground'\n      >\n        <XIcon />\n      </Button>\n    </Reorder.Item>\n  );\n}\n\nexport type PromptQueueProps = {\n  items: QueuedPrompt[];\n  onReorder: (items: QueuedPrompt[]) => void;\n  onEdit: (id: string, text: string) => void;\n  onRemove: (id: string) => void;\n  /** After a stop the queue waits; Send next releases the first prompt. */\n  isPaused?: boolean;\n  onSendNext?: () => void;\n};\n\nexport function PromptQueue({\n  items,\n  onReorder,\n  onEdit,\n  onRemove,\n  isPaused = false,\n  onSendNext,\n}: PromptQueueProps) {\n  const groupRef = useRef<HTMLUListElement>(null);\n  const count = items.length;\n  const hasItems = count > 0;\n  const canSendNext = isPaused && onSendNext !== undefined;\n\n  function move(from: number, to: number) {\n    const next = moveItem(items, from, to);\n    onReorder(next);\n  }\n\n  return (\n    <AnimatedSize>\n      {hasItems && (\n        <div className='flex flex-col gap-1.5 pb-2'>\n          <div className='flex h-6 items-center justify-between gap-2 px-1'>\n            <p className='text-muted-foreground flex items-center gap-1.5 text-xs'>\n              <ListChecksIcon className='size-3.5' />\n              <MotionNumber value={count} /> queued\n              {isPaused && (\n                <span className='text-warning-foreground'>, paused</span>\n              )}\n            </p>\n            {canSendNext && (\n              <Button\n                type='button'\n                variant='ghost'\n                size='sm'\n                onClick={onSendNext}\n                className='h-6 px-2'\n              >\n                <PlayIcon />\n                Send next\n              </Button>\n            )}\n          </div>\n          <Reorder.Group\n            ref={groupRef}\n            axis='y'\n            values={items}\n            onReorder={onReorder}\n            aria-label='Queued prompts'\n            className='flex flex-col gap-1.5'\n          >\n            {items.map((item, index) => (\n              <QueuedCard\n                key={item.id}\n                item={item}\n                index={index}\n                count={count}\n                groupRef={groupRef}\n                onMove={move}\n                onEdit={onEdit}\n                onRemove={onRemove}\n              />\n            ))}\n          </Reorder.Group>\n        </div>\n      )}\n    </AnimatedSize>\n  );\n}\n\ntype MessageStatus = 'streaming' | 'done' | 'stopped';\n\ntype Message = {\n  id: string;\n  role: 'user' | 'assistant';\n  text: string;\n  status: MessageStatus;\n  /** The prompt waited in the queue: its bubble flies in from its card and settles where it lands. */\n  cameFromQueue?: boolean;\n  /** Words already written when the answer first shows. */\n  startsAt?: number;\n};\n\nconst WORD_MS = 85;\n\nconst END_PAUSE_MS = 650;\n\nconst STICK_DISTANCE = 48;\n\n/** The piece plays itself: once the queue is empty it waits this long and starts again. */\nconst LOOP_AFTER_MS = 2800;\n\nconst NO_STEPS: AutoplayStep[] = [];\n\nconst LANDING = { duration: 0.32, ease: EASE_OUT_STRONG };\n\nconst FIRST_PROMPT = 'Compare the shipping terms of Brightmoor and Ostrava';\n\nconst ANSWERS: Record<string, string> = {\n  [FIRST_PROMPT]:\n    'Brightmoor ships within 3 working days and charges a flat $18 per order, free above $500. Ostrava takes 5 to 7 days, bills freight by weight and only covers damage when the box is opened in front of the driver. For your usual orders Brightmoor is faster and about $40 cheaper a month.',\n  'Also compare the refund policies':\n    'Brightmoor refunds within 30 days and pays the return shipping when the item is faulty. Ostrava gives store credit only, within 14 days, and keeps a 10% restocking fee.',\n  'Then draft a short note for finance':\n    'Here is a note you can send: We compared Brightmoor and Ostrava on shipping and refunds. Brightmoor is faster, cheaper for our order sizes and refunds in cash, so we suggest moving the October orders there.',\n};\n\nconst SEED_QUEUE: QueuedPrompt[] = [\n  { id: 'refunds', text: 'Also compare the refund policies' },\n  { id: 'finance', text: 'Then draft a short note for finance' },\n];\n\n/** The piece opens with the first sentence of the answer written, so it reads before anything plays. */\nconst SEED_WORDS = 16;\n\nconst SEED_MESSAGES: Message[] = [\n  { id: 'first', role: 'user', text: FIRST_PROMPT, status: 'done' },\n  {\n    id: 'first-answer',\n    role: 'assistant',\n    text: ANSWERS[FIRST_PROMPT],\n    status: 'streaming',\n    startsAt: SEED_WORDS,\n  },\n];\n\nfunction answerFor(prompt: string) {\n  const prepared = ANSWERS[prompt];\n  if (prepared) {\n    return prepared;\n  }\n  return `Looked into “${prompt}”. The two vendors differ less here: both answer within a day and both keep the details in their terms page, which I linked in the notes.`;\n}\n\nfunction promptMessagesOf(\n  item: QueuedPrompt,\n  cameFromQueue: boolean\n): Message[] {\n  return [\n    {\n      id: item.id,\n      role: 'user',\n      text: item.text,\n      status: 'done',\n      cameFromQueue,\n    },\n    {\n      id: `${item.id}-answer`,\n      role: 'assistant',\n      text: answerFor(item.text),\n      status: 'streaming',\n    },\n  ];\n}\n\nfunction finishedOf(\n  messages: Message[],\n  status: MessageStatus,\n  shownText?: string\n) {\n  return messages.map((message) => {\n    if (message.status !== 'streaming') {\n      return message;\n    }\n    const text = shownText ?? message.text;\n    return { ...message, status, text };\n  });\n}\n\nfunction delayOf(isComplete: boolean) {\n  if (isComplete) {\n    return END_PAUSE_MS;\n  }\n  return WORD_MS;\n}\n\nfunction sendLabelOf(isAnswering: boolean, hasText: boolean) {\n  if (!isAnswering) {\n    return 'Send';\n  }\n  if (hasText) {\n    return 'Add to the queue';\n  }\n  return 'Stop the answer';\n}\n\nfunction keyGlyphOf(isAnswering: boolean, hasText: boolean) {\n  const isStop = isAnswering && !hasText;\n  if (isStop) {\n    return 'stop';\n  }\n  return 'send';\n}\n\nfunction UserBubble({ message }: { message: Message }) {\n  const [scope, animate] = useAnimate<HTMLDivElement>();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const hasLanded = useRef(false);\n\n  function settle() {\n    const isFirstLanding = !hasLanded.current;\n    hasLanded.current = true;\n    if (!isFirstLanding) {\n      return;\n    }\n    if (!message.cameFromQueue) {\n      return;\n    }\n    if (shouldReduceMotion) {\n      return;\n    }\n    animate(scope.current, { scale: [1.04, 1] }, LANDING);\n  }\n\n  return (\n    <motion.div\n      ref={scope}\n      layoutId={`prompt-${message.id}`}\n      layoutDependency={message.id}\n      onLayoutAnimationComplete={settle}\n      className='bg-foreground/[0.05] dark:bg-foreground/[0.07] ms-auto max-w-[85%] rounded-2xl rounded-ee-md px-3 py-2 text-[13px] leading-5'\n    >\n      <motion.span\n        layout='position'\n        layoutDependency={message.id}\n        className='block'\n      >\n        {message.text}\n      </motion.span>\n    </motion.div>\n  );\n}\n\ntype StreamProps = {\n  /** False off screen and in a hidden tab: the answer holds its place. */\n  isActive: boolean;\n  /** Called with the number of words written, each time one arrives. */\n  onProgress: (shownWords: number) => void;\n  onComplete: () => void;\n};\n\ntype StreamingTextProps = StreamProps & {\n  message: Message;\n};\n\n/** The words tick in here, so an answer that streams re-renders its own text and nothing around it. */\nfunction StreamingText({\n  message,\n  isActive,\n  onProgress,\n  onComplete,\n}: StreamingTextProps) {\n  const [shownWords, setShownWords] = useState(message.startsAt ?? 0);\n  const words = wordsOf(message.text);\n  const shown = words.slice(0, shownWords);\n  const isComplete = shownWords >= words.length;\n  const reportProgress = useEffectEvent(onProgress);\n  const complete = useEffectEvent(onComplete);\n\n  useEffect(() => {\n    if (!isActive) {\n      return;\n    }\n    const timer = setTimeout(() => {\n      if (isComplete) {\n        complete();\n        return;\n      }\n      setShownWords((current) => current + 1);\n    }, delayOf(isComplete));\n    return () => clearTimeout(timer);\n  }, [isActive, shownWords, isComplete]);\n\n  useLayoutEffect(() => {\n    reportProgress(shownWords);\n  }, [shownWords]);\n\n  return (\n    <div className='text-[13px] leading-6 text-pretty'>\n      {shown.map((word, index) => (\n        <span\n          key={index}\n          className='transition-opacity duration-300 starting:opacity-0'\n        >\n          {word}{' '}\n        </span>\n      ))}\n      <span\n        aria-hidden='true'\n        className={cn(\n          'bg-primary inline-block h-3.5 w-1.5 rounded-[2px] align-[-2px]',\n          isActive && 'animate-pulse'\n        )}\n      />\n    </div>\n  );\n}\n\nfunction AssistantText({ message, ...stream }: StreamingTextProps) {\n  if (message.status === 'streaming') {\n    return <StreamingText message={message} {...stream} />;\n  }\n  const isStopped = message.status === 'stopped';\n  const words = wordsOf(message.text);\n\n  return (\n    <div className='text-[13px] leading-6 text-pretty'>\n      {words.join(' ')}\n      {isStopped && (\n        <Badge variant='secondary' className='ms-1.5 align-[1px]'>\n          Stopped\n        </Badge>\n      )}\n    </div>\n  );\n}\n\nexport default function Prompt09() {\n  const [messages, setMessages] = useState<Message[]>(SEED_MESSAGES);\n  const [queue, setQueue] = useState<QueuedPrompt[]>(SEED_QUEUE);\n  const [isPaused, setIsPaused] = useState(false);\n  const [draft, setDraft] = useState('');\n  const [message, setMessage] = useState('');\n  const [hasActed, setHasActed] = useState(false);\n  const threadRef = useRef<HTMLDivElement>(null);\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n  const sticksToBottom = useRef(true);\n  const shownWords = useRef(SEED_WORDS);\n  const idCounter = useRef(0);\n  const layoutGroupId = useId();\n  const isVisible = useDocumentVisible();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const layoutSpring = springOf(shouldReduceMotion);\n  const streaming = messages.find((item) => item.status === 'streaming');\n  const isAnswering = streaming !== undefined;\n  const hasText = draft.trim() !== '';\n  const keyLabel = sendLabelOf(isAnswering, hasText);\n  const keyGlyph = keyGlyphOf(isAnswering, hasText);\n  const isKeyEnabled = isAnswering || hasText;\n  const isFinished = !isAnswering && queue.length === 0;\n  useAutosize(textareaRef, draft, 120);\n\n  function stickToBottom() {\n    const thread = threadRef.current;\n    if (!thread) {\n      return;\n    }\n    if (sticksToBottom.current) {\n      thread.scrollTop = thread.scrollHeight;\n    }\n  }\n\n  useLayoutEffect(() => {\n    stickToBottom();\n  }, [messages]);\n\n  function followAnswer(count: number) {\n    shownWords.current = count;\n    stickToBottom();\n  }\n\n  function completeAnswer() {\n    const finished = finishedOf(messages, 'done');\n    const [first, ...rest] = queue;\n    const canContinue = first !== undefined && !isPaused;\n    if (!canContinue) {\n      setMessages(finished);\n      setMessage('Answer finished');\n      return;\n    }\n    setMessages([...finished, ...promptMessagesOf(first, true)]);\n    setQueue(rest);\n    setMessage(`Answer finished. Sent the next prompt: ${first.text}`);\n  }\n\n  function noteAction() {\n    setHasActed(true);\n  }\n\n  function trackScroll(event: React.UIEvent<HTMLDivElement>) {\n    const thread = event.currentTarget;\n    const bottom = thread.scrollTop + thread.clientHeight;\n    const distance = thread.scrollHeight - bottom;\n    sticksToBottom.current = distance < STICK_DISTANCE;\n  }\n\n  function nextId() {\n    idCounter.current += 1;\n    return `typed-${idCounter.current}`;\n  }\n\n  function sendNow(item: QueuedPrompt, cameFromQueue: boolean) {\n    sticksToBottom.current = true;\n    const sent = promptMessagesOf(item, cameFromQueue);\n    setMessages((current) => [...current, ...sent]);\n  }\n\n  function submit() {\n    const text = draft.trim();\n    if (text === '') {\n      return;\n    }\n    const item = { id: nextId(), text };\n    setDraft('');\n    if (isAnswering) {\n      setQueue((current) => [...current, item]);\n      setMessage(`Queued: ${text}`);\n      return;\n    }\n    sendNow(item, false);\n    setMessage(`Sent: ${text}`);\n  }\n\n  function stop() {\n    if (!streaming) {\n      return;\n    }\n    const words = wordsOf(streaming.text);\n    const shown = words.slice(0, shownWords.current);\n    const shownText = shown.join(' ');\n    setMessages((current) => finishedOf(current, 'stopped', shownText));\n    const hasQueue = queue.length > 0;\n    setIsPaused(hasQueue);\n    setMessage(stopMessageOf(queue.length));\n  }\n\n  function sendNext() {\n    const [first, ...rest] = queue;\n    if (!first) {\n      return;\n    }\n    setIsPaused(false);\n    setQueue(rest);\n    sendNow(first, true);\n    setMessage(`Sent the next prompt: ${first.text}`);\n  }\n\n  function pressKey() {\n    const isStop = isAnswering && !hasText;\n    if (isStop) {\n      stop();\n      return;\n    }\n    submit();\n  }\n\n  function editQueued(id: string, text: string) {\n    setQueue((current) =>\n      current.map((item) => {\n        if (item.id !== id) {\n          return item;\n        }\n        return { ...item, text };\n      })\n    );\n    setMessage('Queued prompt saved');\n  }\n\n  function removeQueued(id: string) {\n    const removed = queue.find((item) => item.id === id);\n    const rest = queue.filter((item) => item.id !== id);\n    setQueue(rest);\n    if (rest.length === 0) {\n      setIsPaused(false);\n    }\n    setMessage(`Removed from the queue: ${removed?.text ?? ''}`);\n  }\n\n  function reorder(items: QueuedPrompt[]) {\n    setQueue(items);\n    const first = items[0];\n    if (first) {\n      setMessage(`Next up: ${first.text}`);\n    }\n  }\n\n  function handleFieldKeys(event: React.KeyboardEvent<HTMLTextAreaElement>) {\n    if (!isSendKey(event)) {\n      return;\n    }\n    event.preventDefault();\n    submit();\n  }\n\n  function handleEscape(event: React.KeyboardEvent<HTMLDivElement>) {\n    const isEscape = event.key === 'Escape';\n    const isStoppable = isEscape && isAnswering;\n    if (!isStoppable) {\n      return;\n    }\n    if (!isOwnKey(event)) {\n      return;\n    }\n    event.preventDefault();\n    stop();\n  }\n\n  function restart() {\n    setMessages(SEED_MESSAGES);\n    setQueue(SEED_QUEUE);\n    setIsPaused(false);\n    setMessage('');\n    sticksToBottom.current = true;\n  }\n\n  function replay() {\n    restart();\n    setMessage('The demo starts again');\n  }\n\n  const { ref, isInView } = useAutoplay(NO_STEPS, {\n    loopAfter: LOOP_AFTER_MS,\n    onReset: restart,\n    isEnabled: isFinished,\n  });\n  // Under reduced motion the piece does not play by itself: the answer holds until a person acts on it.\n  const playsAlone = !shouldReduceMotion;\n  const canStream = playsAlone || hasActed;\n  const isOnScreen = isInView && isVisible;\n  const isStreaming = isOnScreen && canStream;\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      onPointerDownCapture={noteAction}\n      onKeyDownCapture={noteAction}\n      className='flex w-full max-w-[28rem] flex-col gap-2'\n    >\n      <div className='bg-card hairline-ring ring-border flex flex-col rounded-xl shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n        <LayoutGroup id={layoutGroupId}>\n          <div\n            ref={threadRef}\n            onScroll={trackScroll}\n            className='flex h-64 flex-col gap-3 overflow-y-auto p-3'\n          >\n            {messages.map((item) => {\n              if (item.role === 'user') {\n                return <UserBubble key={item.id} message={item} />;\n              }\n              return (\n                <AssistantText\n                  key={item.id}\n                  message={item}\n                  isActive={isStreaming}\n                  onProgress={followAnswer}\n                  onComplete={completeAnswer}\n                />\n              );\n            })}\n          </div>\n          <div className='flex flex-col px-2 pt-1 pb-2'>\n            <PromptQueue\n              items={queue}\n              onReorder={reorder}\n              onEdit={editQueued}\n              onRemove={removeQueued}\n              isPaused={isPaused}\n              onSendNext={sendNext}\n            />\n            <motion.div\n              layout='position'\n              layoutDependency={queue.length}\n              transition={layoutSpring}\n              onKeyDown={handleEscape}\n              className='bg-foreground/[0.03] dark:bg-foreground/[0.05] has-[textarea:focus]:ring-ring/25 flex items-end gap-1.5 rounded-lg p-1.5 has-[textarea:focus]:ring-[3px]'\n            >\n              <Textarea\n                ref={textareaRef}\n                rows={1}\n                value={draft}\n                onChange={(event) => setDraft(event.target.value)}\n                onKeyDown={handleFieldKeys}\n                aria-label='Message'\n                placeholder={placeholderOf(isAnswering)}\n                className='max-h-none min-h-8 border-0 bg-transparent px-1.5 py-1.5 shadow-none ring-0 focus-visible:ring-0 dark:bg-transparent'\n              />\n              <Button\n                type='button'\n                size='icon'\n                aria-label={keyLabel}\n                disabled={!isKeyEnabled}\n                focusableWhenDisabled\n                onClick={pressKey}\n              >\n                <Swap swapKey={keyGlyph}>\n                  {keyGlyph === 'stop' && (\n                    <span\n                      aria-hidden='true'\n                      className='size-2.5 rounded-[2px] bg-current'\n                    />\n                  )}\n                  {keyGlyph === 'send' && <ArrowUpIcon />}\n                </Swap>\n              </Button>\n            </motion.div>\n          </div>\n        </LayoutGroup>\n      </div>\n      <div className='flex h-7 items-center justify-between gap-2 px-1'>\n        <p className='text-muted-foreground text-xs'>{hintOf(isAnswering)}</p>\n        <ReplayButton\n          isShown={isFinished}\n          onReplay={replay}\n          label='Start over'\n        />\n      </div>\n      <LiveRegion message={spokenUnless(!hasActed, message)} />\n    </div>\n  );\n}\n\nfunction placeholderOf(isAnswering: boolean) {\n  if (isAnswering) {\n    return 'Type the next prompt, it waits in the queue';\n  }\n  return 'Message';\n}\n\nfunction hintOf(isAnswering: boolean) {\n  if (isAnswering) {\n    return 'Escape stops the answer';\n  }\n  return 'Enter sends';\n}\n\nfunction stopMessageOf(queued: number) {\n  if (queued === 0) {\n    return 'Answer stopped';\n  }\n  const prompts = nounOf(queued, 'prompt');\n  return `Answer stopped. ${queued} ${prompts} wait in the queue, Send next releases them`;\n}\n",
      "type": "registry:component",
      "target": "components/prompt/prompt-09.tsx"
    },
    {
      "path": "registry/ndeko/components/prompt/_parts/use-autosize.ts",
      "content": "'use client';\n\nimport { useLayoutEffect } from 'react';\n\nfunction fitHeight(textarea: HTMLTextAreaElement, maxHeight: number) {\n  textarea.style.height = 'auto';\n  const height = Math.min(textarea.scrollHeight, maxHeight);\n  textarea.style.height = `${height}px`;\n}\n\n/** Also fits again when the width changes, and when `remountKey` changes for a textarea shown again. */\nexport function useAutosize(\n  ref: React.RefObject<HTMLTextAreaElement | null>,\n  value: string,\n  maxHeight: number,\n  remountKey?: unknown\n) {\n  useLayoutEffect(() => {\n    const textarea = ref.current;\n    if (!textarea) {\n      return;\n    }\n    fitHeight(textarea, maxHeight);\n    let lastWidth = textarea.offsetWidth;\n    const observer = new ResizeObserver(() => {\n      const width = textarea.offsetWidth;\n      if (width === lastWidth) {\n        return;\n      }\n      lastWidth = width;\n      fitHeight(textarea, maxHeight);\n    });\n    observer.observe(textarea);\n    return () => observer.disconnect();\n  }, [ref, value, maxHeight, remountKey]);\n}\n\nexport function isSendKey(event: React.KeyboardEvent<HTMLTextAreaElement>) {\n  const isEnter = event.key === 'Enter';\n  const isNewLine = event.shiftKey;\n  const isComposing = event.nativeEvent.isComposing;\n  const isPlainEnter = isEnter && !isNewLine;\n  return isPlainEnter && !isComposing;\n}\n\n/** Puts the caret after the last character once React has committed the new text. */\nexport function caretToEnd(ref: React.RefObject<HTMLTextAreaElement | null>) {\n  requestAnimationFrame(() => {\n    const textarea = ref.current;\n    if (!textarea) {\n      return;\n    }\n    const end = textarea.value.length;\n    textarea.focus();\n    textarea.setSelectionRange(end, end);\n  });\n}\n\n/** Keydown that started inside this element, not in a menu or popover portalled out of it. */\nexport function isOwnKey(event: React.KeyboardEvent<HTMLElement>) {\n  const target = event.target;\n  if (!(target instanceof Node)) {\n    return false;\n  }\n  return event.currentTarget.contains(target);\n}\n",
      "type": "registry:component",
      "target": "components/prompt/_parts/use-autosize.ts"
    }
  ],
  "categories": [
    "components",
    "prompt"
  ],
  "type": "registry:component"
}