{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prompt-11",
  "title": "Prompt deck",
  "description": "Suggested prompts as a stack of cards: the front one is dragged or sent away with Left and Right and the next lifts into place, and pressing a card types its prompt into the composer.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/kbd.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/textarea.json",
    "https://ui.ndekocode.dev/r/theme.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"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/prompt/prompt-11.tsx",
      "content": "'use client';\n\nimport {\n  AnimatePresence,\n  motion,\n  useMotionValue,\n  useTransform,\n  type PanInfo,\n  type Transition,\n} from 'motion/react';\nimport { useEffect, useImperativeHandle, useRef, useState } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\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 {\n  hold,\n  PRESS_LEAD_MS,\n  spokenUnless,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  ArrowUpIcon,\n  CodeIcon,\n  FileTextIcon,\n  LanguagesIcon,\n  LightbulbIcon,\n  RotateCcwIcon,\n  UndoIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { fadePresence, springOf } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Kbd } from '@/registry/ndeko/ui/kbd';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { Textarea } from '@/registry/ndeko/ui/textarea';\n\nimport { useAutosize } from './_parts/use-autosize';\n\nexport type DeckPrompt = {\n  id: string;\n  icon: React.ReactNode;\n  prompt: string;\n  hint: string;\n};\n\nexport type DeckSide = 1 | -1;\n\nexport type PromptDeckHandle = {\n  /** Sends the front card away to the right, as Right does. */\n  next: () => void;\n  /** Brings the card that left last back to the front. */\n  previous: () => void;\n  /** Uses the front card, as pressing it does. */\n  pick: () => void;\n};\n\ntype Pose = {\n  x: number;\n  y: number;\n  scale: number;\n  opacity: number;\n};\n\nconst STEP_PX = 6;\n\nconst VISIBLE_CARDS = 3;\n\nconst SCALE_STEP = 0.04;\n\nconst EXIT_PX = 320;\n\nconst TILT_DEGREES = 4;\n\nconst DISMISS_OFFSET = 96;\n\nconst DISMISS_SPEED = 500;\n\nconst CARD_HEIGHT = 'h-28';\n\nconst CARD_SURFACE =\n  'bg-card hairline-ring ring-foreground/12 dark:ring-foreground/15 rounded-xl shadow-[0_1px_2px_rgb(0_0_0/0.05)]';\n\nfunction signOf(value: number): DeckSide {\n  if (value < 0) {\n    return -1;\n  }\n  return 1;\n}\n\nfunction sideOf(offset: number, speed: number) {\n  if (offset !== 0) {\n    return signOf(offset);\n  }\n  return signOf(speed);\n}\n\nfunction poseOf(rank: number, side: DeckSide): Pose {\n  if (rank < 0) {\n    return { x: side * EXIT_PX, y: 0, scale: 1, opacity: 0 };\n  }\n  const depth = Math.min(rank, VISIBLE_CARDS - 1);\n  const y = depth * STEP_PX;\n  const scale = 1 - depth * SCALE_STEP;\n  const isHidden = rank >= VISIBLE_CARDS;\n  if (isHidden) {\n    return { x: 0, y, scale, opacity: 0 };\n  }\n  return { x: 0, y, scale, opacity: 1 };\n}\n\nfunction dragOf(isFront: boolean) {\n  if (isFront) {\n    return 'x';\n  }\n  return false;\n}\n\nfunction frontToneOf(isFront: boolean) {\n  if (isFront) {\n    return 'cursor-grab active:cursor-grabbing';\n  }\n  return 'pointer-events-none';\n}\n\nfunction pressedToneOf(isPressed: boolean) {\n  if (isPressed) {\n    return 'scale-[0.97] bg-foreground/[0.03]';\n  }\n  return undefined;\n}\n\ntype DeckCardProps = {\n  prompt: DeckPrompt;\n  rank: number;\n  side: DeckSide;\n  isPressed: boolean;\n  glide: Transition;\n  register: (id: string, node: HTMLButtonElement | null) => void;\n  onDismiss: (side: DeckSide) => void;\n  onPick: () => void;\n};\n\nfunction DeckCard({\n  prompt,\n  rank,\n  side,\n  isPressed,\n  glide,\n  register,\n  onDismiss,\n  onPick,\n}: DeckCardProps) {\n  const x = useMotionValue(0);\n  const rotate = useTransform(\n    x,\n    [-EXIT_PX, 0, EXIT_PX],\n    [-TILT_DEGREES, 0, TILT_DEGREES]\n  );\n  const wasDragged = useRef(false);\n  const isFront = rank === 0;\n  const pose = poseOf(rank, side);\n\n  function endDrag(info: PanInfo) {\n    setTimeout(() => {\n      wasDragged.current = false;\n    }, 0);\n    const isFarEnough = Math.abs(info.offset.x) > DISMISS_OFFSET;\n    const isFastEnough = Math.abs(info.velocity.x) > DISMISS_SPEED;\n    const shouldLeave = isFarEnough || isFastEnough;\n    if (shouldLeave) {\n      onDismiss(sideOf(info.offset.x, info.velocity.x));\n    }\n  }\n\n  function pick() {\n    if (wasDragged.current) {\n      return;\n    }\n    onPick();\n  }\n\n  return (\n    <motion.div\n      inert={!isFront}\n      initial={false}\n      drag={dragOf(isFront)}\n      dragConstraints={{ left: 0, right: 0 }}\n      dragElastic={0.8}\n      onDragStart={() => {\n        wasDragged.current = true;\n      }}\n      onDragEnd={(_, info) => endDrag(info)}\n      animate={pose}\n      transition={glide}\n      style={{ x, rotate, zIndex: 100 - rank }}\n      className={cn(\n        'absolute inset-x-2 top-0 origin-bottom',\n        CARD_HEIGHT,\n        CARD_SURFACE,\n        frontToneOf(isFront)\n      )}\n    >\n      <button\n        ref={(node) => register(prompt.id, node)}\n        type='button'\n        data-deck-card=''\n        tabIndex={rankTabIndexOf(isFront)}\n        onClick={pick}\n        className={cn(\n          'focus-visible:ring-ring/25 flex size-full cursor-[inherit] items-start gap-3 rounded-[inherit] p-3.5 text-start transition-[scale,background-color] duration-150 ease-(--ease-out-strong) outline-none focus-visible:ring-[3px]',\n          pressedToneOf(isPressed && isFront)\n        )}\n      >\n        <span className='keycap-3d text-muted-foreground flex size-8 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*=\"size-\"])]:size-4'>\n          {prompt.icon}\n        </span>\n        <span className='flex h-full min-w-0 flex-1 flex-col gap-1'>\n          <span className='line-clamp-3 text-sm leading-5 font-medium'>\n            {prompt.prompt}\n          </span>\n          <span className='text-muted-foreground mt-auto truncate text-xs'>\n            {prompt.hint}\n          </span>\n        </span>\n      </button>\n    </motion.div>\n  );\n}\n\nfunction emptyTextOf(count: number) {\n  if (count === 0) {\n    return 'No suggestions yet';\n  }\n  return 'That was every idea';\n}\n\nfunction rankTabIndexOf(isFront: boolean) {\n  if (isFront) {\n    return 0;\n  }\n  return -1;\n}\n\nexport type PromptDeckProps = {\n  prompts: DeckPrompt[];\n  onPick?: (prompt: DeckPrompt) => void;\n  handleRef?: React.Ref<PromptDeckHandle>;\n  /** Shows the front card held down, for a demonstration that presses it. */\n  isFrontPressed?: boolean;\n  /** Putting the deck back to its first state: change this number. */\n  resetToken?: number;\n  /** A demonstration is not read aloud. */\n  isDemonstrating?: boolean;\n  className?: string;\n};\n\nexport function PromptDeck({\n  prompts,\n  onPick,\n  handleRef,\n  isFrontPressed = false,\n  resetToken = 0,\n  isDemonstrating = false,\n  className,\n}: PromptDeckProps) {\n  const [index, setIndex] = useState(0);\n  const [sides, setSides] = useState<Record<string, DeckSide>>({});\n  const [notice, setNotice] = useState('');\n  const [seenToken, setSeenToken] = useState(resetToken);\n  const rootRef = useRef<HTMLDivElement>(null);\n  const buttons = useRef(new Map<string, HTMLButtonElement>());\n  const shouldFocusFront = useRef(false);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const fade = fadePresence();\n  const glide = springOf(shouldReduceMotion);\n  const count = prompts.length;\n  const isEmpty = index >= count;\n  const front = prompts[index];\n  const shown = Math.min(index + 1, count);\n\n  if (seenToken !== resetToken) {\n    setSeenToken(resetToken);\n    setIndex(0);\n  }\n\n  useEffect(() => {\n    if (!shouldFocusFront.current) {\n      return;\n    }\n    shouldFocusFront.current = false;\n    const current = prompts[index];\n    if (current) {\n      buttons.current.get(current.id)?.focus();\n      return;\n    }\n    const showAgainButton =\n      rootRef.current?.querySelector<HTMLElement>('[data-deck-empty]');\n    showAgainButton?.focus();\n  }, [index, prompts]);\n\n  function register(id: string, node: HTMLButtonElement | null) {\n    if (node) {\n      buttons.current.set(id, node);\n      return;\n    }\n    buttons.current.delete(id);\n  }\n\n  function rememberFocus() {\n    const active = document.activeElement;\n    const isElement = active instanceof HTMLElement;\n    shouldFocusFront.current = isElement && active.matches('[data-deck-card]');\n  }\n\n  function dismissFront(side: DeckSide) {\n    if (!front) {\n      return;\n    }\n    rememberFocus();\n    setSides((current) => ({ ...current, [front.id]: side }));\n    setIndex((current) => current + 1);\n    const following = prompts[index + 1];\n    if (following) {\n      setNotice(`Next idea: ${following.prompt}`);\n      return;\n    }\n    setNotice('That was every idea');\n  }\n\n  function previous() {\n    if (index === 0) {\n      return;\n    }\n    rememberFocus();\n    const back = prompts[index - 1];\n    setIndex((current) => current - 1);\n    setNotice(`Back to: ${back.prompt}`);\n  }\n\n  function showAgain() {\n    setIndex(0);\n    setNotice('The ideas are back');\n  }\n\n  function pick() {\n    if (!front) {\n      return;\n    }\n    setNotice(`Using: ${front.prompt}`);\n    onPick?.(front);\n  }\n\n  useImperativeHandle(handleRef, () => ({\n    next: () => dismissFront(1),\n    previous,\n    pick,\n  }));\n\n  function handleKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    const hasModifier = event.metaKey || event.ctrlKey || event.altKey;\n    if (hasModifier) {\n      return;\n    }\n    if (event.key === 'ArrowRight') {\n      event.preventDefault();\n      dismissFront(1);\n      return;\n    }\n    if (event.key === 'ArrowLeft') {\n      event.preventDefault();\n      dismissFront(-1);\n    }\n  }\n\n  return (\n    <div\n      ref={rootRef}\n      onKeyDown={handleKeys}\n      className={cn('@container flex w-full flex-col gap-3', className)}\n    >\n      <div\n        role='group'\n        aria-label='Suggested prompts'\n        className='relative -mx-2 h-[calc(7rem+12px)] overflow-x-clip'\n      >\n        {prompts.map((prompt, position) => (\n          <DeckCard\n            key={prompt.id}\n            prompt={prompt}\n            rank={position - index}\n            side={sides[prompt.id] ?? 1}\n            isPressed={isFrontPressed}\n            glide={glide}\n            register={register}\n            onDismiss={dismissFront}\n            onPick={pick}\n          />\n        ))}\n        <AnimatePresence initial={false}>\n          {isEmpty && (\n            <motion.div\n              key='empty'\n              {...fade}\n              className={cn(\n                'hairline-border border-foreground/20 absolute inset-x-2 top-0 flex flex-col items-center justify-center gap-2 rounded-xl border-dashed',\n                CARD_HEIGHT\n              )}\n            >\n              <p className='text-muted-foreground text-[13px]'>\n                {emptyTextOf(count)}\n              </p>\n              {count > 0 && (\n                <Button\n                  type='button'\n                  variant='outline'\n                  size='sm'\n                  data-deck-empty=''\n                  onClick={showAgain}\n                >\n                  <RotateCcwIcon />\n                  Show them again\n                </Button>\n              )}\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n      <div className='flex h-7 items-center justify-between gap-3 px-1'>\n        <p className='text-muted-foreground flex items-baseline gap-1 text-xs'>\n          <MotionNumber value={shown} /> of {count}\n        </p>\n        <Button\n          type='button'\n          variant='ghost'\n          size='sm'\n          disabled={index === 0}\n          focusableWhenDisabled\n          onClick={previous}\n          className='text-muted-foreground'\n        >\n          <UndoIcon />\n          Back\n        </Button>\n      </div>\n      <p className='text-muted-foreground hidden items-center gap-1 px-1 text-xs @sm:flex'>\n        <Kbd>←</Kbd>\n        <Kbd>→</Kbd> send a card away, <Kbd>Enter</Kbd> uses it\n      </p>\n      <LiveRegion message={spokenUnless(isDemonstrating, notice)} />\n    </div>\n  );\n}\n\nconst PROMPTS: DeckPrompt[] = [\n  {\n    id: 'summary',\n    icon: <FileTextIcon />,\n    prompt: 'Summarize this contract and list what I must do before signing',\n    hint: 'Reads the file you attached',\n  },\n  {\n    id: 'translate',\n    icon: <LanguagesIcon />,\n    prompt: 'Translate my last message into Lingala and keep the same tone',\n    hint: 'Keeps names and numbers as they are',\n  },\n  {\n    id: 'bug',\n    icon: <CodeIcon />,\n    prompt: 'Find why the invoice total is off by a cent and fix it',\n    hint: 'Looks at the staged changes first',\n  },\n  {\n    id: 'ideas',\n    icon: <LightbulbIcon />,\n    prompt: 'Give me five names for a small neighbourhood delivery service',\n    hint: 'Short names that are easy to say',\n  },\n];\n\nconst TYPE_MS = 24;\n\ntype TypeJob = {\n  id: number;\n  text: string;\n};\n\nfunction TypedComposer({\n  value,\n  onValueChange,\n  onSend,\n}: {\n  value: string;\n  onValueChange: (value: string) => void;\n  onSend: () => void;\n}) {\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n  const hasText = value.trim() !== '';\n  useAutosize(textareaRef, value, 120);\n\n  return (\n    <div className='bg-card hairline-ring ring-foreground/12 dark:ring-foreground/15 has-[textarea:focus]:ring-ring/25 flex items-end gap-1.5 rounded-xl p-1.5 shadow-[0_1px_2px_rgb(0_0_0/0.04)] transition-shadow duration-150 has-[textarea:focus]:ring-[3px]'>\n      <Textarea\n        ref={textareaRef}\n        rows={1}\n        value={value}\n        onChange={(event) => onValueChange(event.target.value)}\n        aria-label='Message'\n        placeholder='Pick an idea or write your own'\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='Send'\n        disabled={!hasText}\n        focusableWhenDisabled\n        onClick={onSend}\n      >\n        <ArrowUpIcon />\n      </Button>\n    </div>\n  );\n}\n\nfunction DeckDemo() {\n  const [round, setRound] = useState(0);\n  const [draft, setDraft] = useState('');\n  const [job, setJob] = useState<TypeJob | null>(null);\n  const deck = useRef<PromptDeckHandle>(null);\n  const { pressed, press } = usePress<'front'>();\n\n  useEffect(() => {\n    if (!job) {\n      return;\n    }\n    let length = 0;\n    const timer = setInterval(() => {\n      length += 1;\n      setDraft(job.text.slice(0, length));\n      if (length >= job.text.length) {\n        clearInterval(timer);\n      }\n    }, TYPE_MS);\n    return () => clearInterval(timer);\n  }, [job]);\n\n  function resetDemo() {\n    setJob(null);\n    setDraft('');\n    setRound((current) => current + 1);\n  }\n\n  function takeIdea(prompt: DeckPrompt) {\n    setJob({ id: Date.now(), text: prompt.prompt });\n  }\n\n  function editDraft(text: string) {\n    setJob(null);\n    setDraft(text);\n  }\n\n  function sendDraft() {\n    setJob(null);\n    setDraft('');\n  }\n\n  const steps: AutoplayStep[] = [\n    { after: 1800, run: () => deck.current?.next() },\n    { after: 1600, run: () => deck.current?.next() },\n    { after: 1500, run: () => press('front') },\n    { after: PRESS_LEAD_MS, run: () => deck.current?.pick() },\n    { after: 3600, run: hold },\n  ];\n  const { ref, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: 1600,\n    onReset: resetDemo,\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='flex min-h-[17rem] w-full max-w-[28rem] flex-col gap-3'\n    >\n      <PromptDeck\n        prompts={PROMPTS}\n        onPick={takeIdea}\n        handleRef={deck}\n        isFrontPressed={pressed === 'front'}\n        resetToken={round}\n        isDemonstrating={isAutoplaying}\n      />\n      <TypedComposer\n        value={draft}\n        onValueChange={editDraft}\n        onSend={sendDraft}\n      />\n    </div>\n  );\n}\n\nexport default function Prompt11() {\n  return <DeckDemo />;\n}\n",
      "type": "registry:component",
      "target": "components/prompt/prompt-11.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"
}