{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "card-01",
  "title": "Contact stack",
  "description": "A stack of contact cards with one action each, where the front card drops away and tucks behind the others on a click or an arrow key.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/avatar.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/company-mark.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/recipes.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/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/card/card-01.tsx",
      "content": "'use client';\n\nimport { useId, useImperativeHandle, useRef, useState } from 'react';\n\nimport type { AutoplayStep } from '@/registry/ndeko/hooks/use-autoplay';\nimport {\n  PRESS_LEAD_MS,\n  pressedQuietOf,\n  spokenUnless,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  BookmarkIcon,\n  CheckIcon,\n  ChevronLeftIcon,\n  ChevronRightIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { FOCUS_RING } from '@/registry/ndeko/lib/recipes';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Avatar } from '@/registry/ndeko/ui/avatar';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { CompanyMark } from '@/registry/ndeko/ui/company-mark';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\n\nimport { depthOf, useDeck } from './_parts/deck';\nimport { holdFocusOutsideCards, isOnControl, sideStepOf } from './_parts/keys';\nimport { PEOPLE } from './_parts/people';\nimport { useCardDemo } from './_parts/use-card-demo';\n\nexport type Contact = {\n  id: string;\n  name: string;\n  role: string;\n  company: string;\n};\n\n/** The control a demonstration holds down before it acts. */\nexport type ContactStackPress = 'save' | 'next';\n\nexport type ContactStackHandle = {\n  next: () => void;\n  previous: () => void;\n  toggleSaved: () => void;\n};\n\nconst LAST_LAYER = 2;\nconst PEEK_PX = 10;\nconst SCALE_STEP = 0.05;\nconst DROP_PX = 44;\nconst DROP_TILT_DEG = 3;\nconst LEAVE_MS = 240;\n\nconst CARD = [\n  'bg-card hairline-ring ring-border absolute inset-x-0 bottom-0 flex h-36 origin-top flex-col justify-between rounded-xl p-4',\n  'shadow-[0_1px_2px_rgb(0_0_0/0.04)] ease-(--ease-out-strong)',\n].join(' ');\n\nconst FRONT = 'cursor-pointer hover:ring-foreground/25';\n\nconst TRAVELLING = 'transition-[transform,opacity] duration-300';\n\nconst PLACED = 'transition-none';\n\ntype Placement = { transform: string; opacity: number; zIndex: number };\n\nfunction transformOf(offsetY: number, scale: number, tilt: number) {\n  return `translateY(${offsetY}px) scale(${scale}) rotate(${tilt}deg)`;\n}\n\nfunction opacityOf(isShown: boolean) {\n  if (isShown) {\n    return 1;\n  }\n  return 0;\n}\n\n/** The front card sits lowest and largest; each card behind it shows a strip above it, and the fourth is hidden. */\nfunction placementOf(depth: number, isOut: boolean, count: number): Placement {\n  if (isOut) {\n    const dropped = transformOf(DROP_PX, 1, DROP_TILT_DEG);\n    const aboveAll = count + 1;\n    return { transform: dropped, opacity: 0, zIndex: aboveAll };\n  }\n  const layer = Math.min(depth, LAST_LAYER);\n  const lift = layer * -PEEK_PX;\n  const shrink = layer * SCALE_STEP;\n  const scale = 1 - shrink;\n  const isShown = depth <= LAST_LAYER;\n  const stackOrder = count - depth;\n  return {\n    transform: transformOf(lift, scale, 0),\n    opacity: opacityOf(isShown),\n    zIndex: stackOrder,\n  };\n}\n\nfunction travelOf(isPlaced: boolean) {\n  if (isPlaced) {\n    return PLACED;\n  }\n  return TRAVELLING;\n}\n\nfunction saveLabelOf(isSaved: boolean) {\n  if (isSaved) {\n    return 'Saved';\n  }\n  return 'Save';\n}\n\ntype ContactCardProps = {\n  contact: Contact;\n  placement: Placement;\n  isFront: boolean;\n  /** The card takes its pose at once, to travel from there on the next change. */\n  isPlaced: boolean;\n  /** A press on the card itself turns the stack: false for a stack of one. */\n  canTurn: boolean;\n  isSaved: boolean;\n  isSavePressed: boolean;\n  onToggleSaved: () => void;\n  onTurn: () => void;\n};\n\nfunction ContactCard({\n  contact,\n  placement,\n  isFront,\n  isPlaced,\n  canTurn,\n  isSaved,\n  isSavePressed,\n  onToggleSaved,\n  onTurn,\n}: ContactCardProps) {\n  const saveLabel = saveLabelOf(isSaved);\n  const answersPress = isFront && canTurn;\n\n  function turnFromCard(event: React.MouseEvent<HTMLLIElement>) {\n    if (isOnControl(event.target)) {\n      return;\n    }\n    onTurn();\n  }\n\n  return (\n    <li\n      style={placement}\n      inert={!isFront}\n      aria-hidden={!isFront}\n      onClick={turnFromCard}\n      className={cn(CARD, travelOf(isPlaced), answersPress && FRONT)}\n    >\n      <div className='flex items-center gap-3'>\n        <Avatar seed={contact.name} className='size-10' />\n        <div className='min-w-0'>\n          <p className='truncate text-sm font-medium'>{contact.name}</p>\n          <p className='text-muted-foreground truncate text-xs'>\n            {contact.role}\n          </p>\n        </div>\n      </div>\n      <div className='flex items-center justify-between gap-3'>\n        <p className='flex min-w-0 items-center gap-1.5 text-xs'>\n          <CompanyMark seed={contact.company} size='sm' />\n          <span className='truncate'>{contact.company}</span>\n        </p>\n        <Button\n          type='button'\n          size='sm'\n          variant='outline'\n          aria-pressed={isSaved}\n          onClick={onToggleSaved}\n          className={cn('w-[4.75rem]', pressedQuietOf(isSavePressed))}\n        >\n          <Swap swapKey={saveLabel}>\n            {isSaved && <CheckIcon className='size-3.5' />}\n            {!isSaved && <BookmarkIcon className='size-3.5' />}\n          </Swap>\n          {saveLabel}\n        </Button>\n      </div>\n    </li>\n  );\n}\n\nexport type ContactStackProps = {\n  contacts: Contact[];\n  savedIds: readonly string[];\n  onSavedChange: (contactId: string, isSaved: boolean) => void;\n  /** Turns the stack or saves from outside, for a demonstration or a shortcut of the page. */\n  handleRef?: React.Ref<ContactStackHandle>;\n  /** Shows Save or Next held down, for a demonstration that presses it. */\n  pressed?: ContactStackPress | null;\n  /** Keeps the live region quiet while a demonstration turns the stack by itself. */\n  isSilent?: boolean;\n  label?: string;\n  className?: string;\n};\n\nexport function ContactStack({\n  contacts,\n  savedIds,\n  onSavedChange,\n  handleRef,\n  pressed = null,\n  isSilent = false,\n  label = 'Contacts',\n  className,\n}: ContactStackProps) {\n  const hintId = useId();\n  const count = contacts.length;\n  const deck = useDeck(count, LEAVE_MS);\n  const frontContact = contacts[deck.front];\n  const position = deck.front + 1;\n  const canTurn = count > 1;\n  const isSaveDown = pressed === 'save';\n  const isNextDown = pressed === 'next';\n\n  function isSavedContact(contact: Contact) {\n    return savedIds.includes(contact.id);\n  }\n\n  function toggleSaved(contact: Contact) {\n    const isSaved = isSavedContact(contact);\n    onSavedChange(contact.id, !isSaved);\n  }\n\n  function toggleFrontSaved() {\n    if (frontContact) {\n      toggleSaved(frontContact);\n    }\n  }\n\n  function turnWithKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    const step = sideStepOf(event.key);\n    if (step === 0) {\n      return;\n    }\n    event.preventDefault();\n    holdFocusOutsideCards(event.currentTarget);\n    if (step === 1) {\n      deck.next();\n      return;\n    }\n    deck.previous();\n  }\n\n  useImperativeHandle(handleRef, () => ({\n    next: deck.next,\n    previous: deck.previous,\n    toggleSaved: toggleFrontSaved,\n  }));\n\n  if (!frontContact) {\n    return (\n      <p className='hairline-border border-foreground/20 text-muted-foreground flex h-36 w-full items-center justify-center rounded-xl border-dashed text-[13px]'>\n        No contacts yet\n      </p>\n    );\n  }\n\n  const announcement = `${frontContact.name}, ${frontContact.role} at ${frontContact.company}, ${position} of ${count}`;\n\n  return (\n    <div\n      role='group'\n      aria-roledescription='carousel'\n      aria-label={label}\n      aria-describedby={hintId}\n      tabIndex={0}\n      onKeyDown={turnWithKeys}\n      className={cn(\n        'flex w-full flex-col gap-3 rounded-xl',\n        FOCUS_RING,\n        className\n      )}\n    >\n      <ul className='relative h-[10.25rem]'>\n        {contacts.map((contact, index) => {\n          const depth = depthOf(index, deck.front, count);\n          const isOut = index === deck.out;\n          const isFront = depth === 0;\n          const isPlaced = isOut && deck.isReturning;\n          const isSavePressed = isFront && isSaveDown;\n          return (\n            <ContactCard\n              key={contact.id}\n              contact={contact}\n              placement={placementOf(depth, isOut, count)}\n              isFront={isFront}\n              isPlaced={isPlaced}\n              canTurn={canTurn}\n              isSaved={isSavedContact(contact)}\n              isSavePressed={isSavePressed}\n              onToggleSaved={() => toggleSaved(contact)}\n              onTurn={deck.next}\n            />\n          );\n        })}\n      </ul>\n      <div className='flex h-7 items-center justify-between gap-2 ps-1'>\n        <p className='text-muted-foreground text-xs tabular-nums'>\n          {position} of {count}\n        </p>\n        {canTurn && (\n          <div className='flex items-center gap-1'>\n            <Button\n              type='button'\n              variant='ghost'\n              size='icon-sm'\n              aria-label='Previous contact'\n              onClick={deck.previous}\n              className='text-muted-foreground'\n            >\n              <ChevronLeftIcon />\n            </Button>\n            <Button\n              type='button'\n              variant='ghost'\n              size='icon-sm'\n              aria-label='Next contact'\n              onClick={deck.next}\n              className={cn(\n                'text-muted-foreground',\n                pressedQuietOf(isNextDown)\n              )}\n            >\n              <ChevronRightIcon />\n            </Button>\n          </div>\n        )}\n      </div>\n      <span id={hintId} className='sr-only'>\n        Left and Right arrows turn the stack\n      </span>\n      <LiveRegion message={spokenUnless(isSilent, announcement)} />\n    </div>\n  );\n}\n\nconst CONTACTS: Contact[] = [\n  PEOPLE.amara,\n  PEOPLE.jonas,\n  PEOPLE.mei,\n  PEOPLE.rafael,\n  PEOPLE.ingrid,\n];\n\nfunction withSaved(savedIds: string[], contactId: string, isSaved: boolean) {\n  const others = savedIds.filter((savedId) => savedId !== contactId);\n  if (isSaved) {\n    return [...others, contactId];\n  }\n  return others;\n}\n\nexport default function Card01() {\n  const [savedIds, setSavedIds] = useState<string[]>([]);\n  const stack = useRef<ContactStackHandle>(null);\n  const { pressed, press } = usePress<ContactStackPress>();\n\n  function changeSaved(contactId: string, isSaved: boolean) {\n    setSavedIds((current) => withSaved(current, contactId, isSaved));\n  }\n\n  const steps: AutoplayStep[] = [\n    { after: 1500, run: () => press('save') },\n    { after: PRESS_LEAD_MS, run: () => stack.current?.toggleSaved() },\n    { after: 1200, run: () => press('next') },\n    { after: PRESS_LEAD_MS, run: () => stack.current?.next() },\n  ];\n  const { ref, isAutoplaying } = useCardDemo(steps, {\n    loopAfter: 700,\n  });\n\n  return (\n    <div ref={ref} className='min-h-[12.75rem] w-full max-w-[21rem]'>\n      <ContactStack\n        contacts={CONTACTS}\n        savedIds={savedIds}\n        onSavedChange={changeSaved}\n        handleRef={stack}\n        pressed={pressed}\n        isSilent={isAutoplaying}\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/card-01.tsx"
    },
    {
      "path": "registry/ndeko/components/card/_parts/deck.ts",
      "content": "'use client';\n\nimport { useCallback, useLayoutEffect, useReducer } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\n\ntype DeckDirection = 1 | -1;\n\ntype DeckState = {\n  front: number;\n  /** The card held out of the deck for a moment: the one that left the front, or the one about to come back to it. */\n  out: number | null;\n  /** The out card waits in its pose, then comes back to the front from there. */\n  isReturning: boolean;\n};\n\ntype DeckAction =\n  | { type: 'leave'; count: number }\n  | { type: 'summon'; count: number }\n  | { type: 'jump'; direction: DeckDirection; count: number }\n  | { type: 'land' };\n\nconst RESTING: DeckState = { front: 0, out: null, isReturning: false };\n\n/** An index that runs past either end of a list comes back in at the other end. */\nexport function wrapIndex(index: number, count: number) {\n  if (count <= 0) {\n    return 0;\n  }\n  const remainder = index % count;\n  const positive = remainder + count;\n  return positive % count;\n}\n\n/** How many cards sit in front of this one: 0 for the front card. */\nexport function depthOf(index: number, front: number, count: number) {\n  const behind = index - front;\n  return wrapIndex(behind, count);\n}\n\nfunction landed(deck: DeckState): DeckState {\n  if (deck.out === null) {\n    return deck;\n  }\n  if (deck.isReturning) {\n    return { front: deck.out, out: null, isReturning: false };\n  }\n  return { front: deck.front, out: null, isReturning: false };\n}\n\nfunction reduceDeck(deck: DeckState, action: DeckAction): DeckState {\n  const settled = landed(deck);\n  if (action.type === 'land') {\n    return settled;\n  }\n  if (action.type === 'jump') {\n    const stepped = settled.front + action.direction;\n    const front = wrapIndex(stepped, action.count);\n    return { front, out: null, isReturning: false };\n  }\n  if (action.type === 'leave') {\n    const stepped = settled.front + 1;\n    const front = wrapIndex(stepped, action.count);\n    return { front, out: settled.front, isReturning: false };\n  }\n  const before = settled.front - 1;\n  const out = wrapIndex(before, action.count);\n  return { front: settled.front, out, isReturning: true };\n}\n\n/**\n * A deck that turns one card at a time. Going forward, the front card is held out while the others\n * step up, then it joins the back. Going back, the last card is placed out first and comes to the\n * front from there. Each piece draws the out pose its own way: dropped, swung aside.\n */\nexport function useDeck(count: number, leaveMs: number) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const [deck, dispatch] = useReducer(reduceDeck, RESTING);\n  const { schedule, clearAll } = useTimeouts();\n  const canTurn = count > 1;\n\n  useLayoutEffect(() => {\n    if (!deck.isReturning) {\n      return;\n    }\n    // A transition starts from the last pose the browser applied. Reading a layout value applies\n    // the out pose now, so the card travels from there and not from the back of the deck.\n    document.body.getBoundingClientRect();\n    const frame = requestAnimationFrame(() => dispatch({ type: 'land' }));\n    return () => cancelAnimationFrame(frame);\n  }, [deck.isReturning, deck.out]);\n\n  const next = useCallback(() => {\n    if (!canTurn) {\n      return;\n    }\n    clearAll();\n    if (shouldReduceMotion) {\n      dispatch({ type: 'jump', direction: 1, count });\n      return;\n    }\n    dispatch({ type: 'leave', count });\n    schedule(() => dispatch({ type: 'land' }), leaveMs);\n  }, [canTurn, clearAll, count, leaveMs, schedule, shouldReduceMotion]);\n\n  const previous = useCallback(() => {\n    if (!canTurn) {\n      return;\n    }\n    clearAll();\n    if (shouldReduceMotion) {\n      dispatch({ type: 'jump', direction: -1, count });\n      return;\n    }\n    dispatch({ type: 'summon', count });\n  }, [canTurn, clearAll, count, shouldReduceMotion]);\n\n  const front = wrapIndex(deck.front, count);\n\n  return {\n    front,\n    out: deck.out,\n    isReturning: deck.isReturning,\n    next,\n    previous,\n  };\n}\n",
      "type": "registry:component",
      "target": "components/card/_parts/deck.ts"
    },
    {
      "path": "registry/ndeko/components/card/_parts/keys.ts",
      "content": "/** The step an arrow key asks for along a row: -1 for Left, 1 for Right, 0 for any other key. */\nexport function sideStepOf(key: string) {\n  if (key === 'ArrowLeft') {\n    return -1;\n  }\n  if (key === 'ArrowRight') {\n    return 1;\n  }\n  return 0;\n}\n\n/** True when a press landed on a control inside a surface that also answers presses of its own. */\nexport function isOnControl(target: EventTarget) {\n  if (!(target instanceof Element)) {\n    return false;\n  }\n  return target.closest('button, a, input') !== null;\n}\n\n/** True when the keyboard brings focus into an element from outside it, not when focus moves within it. */\nexport function isKeyboardArrival(event: React.FocusEvent<HTMLElement>) {\n  const isKeyboardFocus = event.target.matches(':focus-visible');\n  const cameFromInside = event.currentTarget.contains(event.relatedTarget);\n  return isKeyboardFocus && !cameFromInside;\n}\n\n/**\n * A card that goes behind the others turns inert and would drop the focus it holds. Before a deck\n * turns from the keyboard, the group takes the focus, so the next arrow key still reaches it.\n */\nexport function holdFocusOutsideCards(group: HTMLElement) {\n  const focused = document.activeElement;\n  if (!(focused instanceof Element)) {\n    return;\n  }\n  const card = focused.closest('li');\n  if (!card) {\n    return;\n  }\n  if (group.contains(card)) {\n    group.focus();\n  }\n}\n",
      "type": "registry:component",
      "target": "components/card/_parts/keys.ts"
    },
    {
      "path": "registry/ndeko/components/card/_parts/people.ts",
      "content": "export type Person = {\n  id: string;\n  name: string;\n  role: string;\n  company: string;\n};\n\n/** The invented people of the card demos. The same person keeps the same picture on every card. */\nexport const PEOPLE = {\n  amara: {\n    id: 'amara',\n    name: 'Amara Diallo',\n    role: 'Product lead',\n    company: 'Halden Works',\n  },\n  jonas: {\n    id: 'jonas',\n    name: 'Jonas Weber',\n    role: 'Staff engineer',\n    company: 'Brightwater',\n  },\n  mei: {\n    id: 'mei',\n    name: 'Mei Tanaka',\n    role: 'Design director',\n    company: 'Kiln Studio',\n  },\n  rafael: {\n    id: 'rafael',\n    name: 'Rafael Ortega',\n    role: 'Head of support',\n    company: 'Tallyard',\n  },\n  ingrid: {\n    id: 'ingrid',\n    name: 'Ingrid Solheim',\n    role: 'Finance manager',\n    company: 'Quillhouse',\n  },\n} satisfies Record<string, Person>;\n",
      "type": "registry:component",
      "target": "components/card/_parts/people.ts"
    },
    {
      "path": "registry/ndeko/components/card/_parts/use-card-demo.ts",
      "content": "'use client';\n\nimport {\n  useAutoplay,\n  type AutoplayOptions,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\n\n/**\n * What every card demo shares: the demonstration, and the box that keeps its tallest height so a\n * round never moves the page.\n */\nexport function useCardDemo(\n  steps: readonly AutoplayStep[],\n  options?: AutoplayOptions\n) {\n  const demo = useAutoplay(steps, options);\n  const { ref } = demo;\n\n  useKeptHeight(ref);\n\n  return demo;\n}\n",
      "type": "registry:component",
      "target": "components/card/_parts/use-card-demo.ts"
    }
  ],
  "categories": [
    "components",
    "card"
  ],
  "type": "registry:component"
}