{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "card-07",
  "title": "Week in figures",
  "description": "A weekly card whose four figures roll through a vertical loop with no end, where the figure in front changes place with the next.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/card.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/segments.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-07.tsx",
      "content": "'use client';\n\nimport { useId, useImperativeHandle, useRef, useState } from 'react';\n\nimport type { AutoplayStep } from '@/registry/ndeko/hooks/use-autoplay';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport {\n  CheckCheckIcon,\n  ClockIcon,\n  FolderIcon,\n  ZapIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Card } from '@/registry/ndeko/ui/card';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\nimport { wrapIndex } from './_parts/deck';\nimport { SampleNote } from './_parts/sample-note';\nimport { useCardDemo } from './_parts/use-card-demo';\n\nexport type WeekFigure = {\n  id: string;\n  /** One word, for the switch and the row: \"Focus\". */\n  name: string;\n  /** The figure as it reads, already formatted: \"18h 40m\", \"23\". */\n  value: string;\n  /** What the figure counts when it does not say so itself: \"done\", \"days\". */\n  unit?: string;\n  detail: string;\n  icon: React.ReactNode;\n};\n\nexport type WeekFiguresHandle = {\n  next: () => void;\n};\n\nconst AWAY_PX = 84;\n\n/** A narrow card stacks each figure over its label, so the faint neighbours of the front row sit further out there. */\nconst WHEEL_PEEK = '[--peek:52px] @2xs:[--peek:46px]';\n\nconst ROW = [\n  'absolute inset-x-0 top-1/2 -mt-7 flex h-14 flex-wrap content-center items-center gap-x-3 px-3 @2xs:flex-nowrap',\n  'transition-[transform,opacity] duration-500 ease-(--ease-in-out-strong)',\n].join(' ');\n\nconst FADED_ENDS =\n  '[mask-image:linear-gradient(to_bottom,transparent,black_1.75rem,black_calc(100%_-_1.75rem),transparent)]';\n\ntype RowStyle = { transform: string; opacity: number };\n\nconst FRONT: RowStyle = { transform: 'translateY(0px) scale(1)', opacity: 1 };\n\n/** The row in front sits in the middle, one row shows faintly on each side, and the rest wait out of sight. */\nfunction rowStyleOf(offset: number): RowStyle {\n  const distance = Math.abs(offset);\n  const side = Math.sign(offset);\n  if (distance === 0) {\n    return FRONT;\n  }\n  if (distance === 1) {\n    const shift = `calc(${side} * var(--peek))`;\n    return { transform: `translateY(${shift}) scale(0.86)`, opacity: 0.4 };\n  }\n  const shift = side * AWAY_PX;\n  return { transform: `translateY(${shift}px) scale(0.8)`, opacity: 0 };\n}\n\n/**\n * How far the rows are kept on each side of the front one. A row that will show after a turn is\n * already there, waiting out of sight, so it travels in instead of appearing.\n */\nfunction reachOf(count: number) {\n  if (count < 2) {\n    return 0;\n  }\n  const farthestTurn = Math.floor(count / 2);\n  return farthestTurn + 1;\n}\n\nfunction offsetsOf(reach: number) {\n  const bothSides = reach * 2;\n  const length = bothSides + 1;\n  return Array.from({ length }, (_, index) => index - reach);\n}\n\n/** The shortest way round the loop from one figure to another: forward when both ways are equal. */\nfunction shortestTurnOf(from: number, to: number, count: number) {\n  const gap = to - from;\n  const ahead = wrapIndex(gap, count);\n  const behind = count - ahead;\n  if (ahead <= behind) {\n    return ahead;\n  }\n  return -behind;\n}\n\nfunction FigureRow({ figure, offset }: { figure: WeekFigure; offset: number }) {\n  return (\n    <div style={rowStyleOf(offset)} className={ROW}>\n      <span className='keycap-3d text-muted-foreground hidden size-8 shrink-0 items-center justify-center rounded-lg @2xs:flex [&_svg]:size-4'>\n        {figure.icon}\n      </span>\n      <p className='flex min-w-0 flex-1 items-baseline gap-1.5'>\n        <span className='text-2xl leading-7 font-semibold tabular-nums'>\n          {figure.value}\n        </span>\n        {figure.unit && (\n          <span className='text-muted-foreground truncate text-[13px]'>\n            {figure.unit}\n          </span>\n        )}\n      </p>\n      <p className='flex min-w-0 basis-full items-baseline gap-1.5 @2xs:block @2xs:basis-auto @2xs:text-end'>\n        <span className='block truncate text-[13px] font-medium'>\n          {figure.name}\n        </span>\n        <span className='text-muted-foreground block truncate text-xs'>\n          {figure.detail}\n        </span>\n      </p>\n    </div>\n  );\n}\n\nfunction amountOf(figure: WeekFigure) {\n  if (figure.unit) {\n    return `${figure.value} ${figure.unit}`;\n  }\n  return figure.value;\n}\n\nfunction spokenFigureOf(figure: WeekFigure) {\n  const amount = amountOf(figure);\n  return `${figure.name}: ${amount}, ${figure.detail}`;\n}\n\nexport type WeekFiguresProps = {\n  title: string;\n  /** The days the figures cover: \"Nov 9 to 15\". */\n  period: string;\n  figures: WeekFigure[];\n  /** Says the figures are made up. Leave it out for real figures. */\n  note?: string;\n  /** Rolls the wheel from outside, for a demonstration or a timer of the page. */\n  handleRef?: React.Ref<WeekFiguresHandle>;\n  /** Keeps the live region quiet while a demonstration rolls the wheel by itself. */\n  isSilent?: boolean;\n  className?: string;\n};\n\nexport function WeekFigures({\n  title,\n  period,\n  figures,\n  note,\n  handleRef,\n  isSilent = false,\n  className,\n}: WeekFiguresProps) {\n  const titleId = useId();\n  const [step, setStep] = useState(0);\n  const count = figures.length;\n  const activeIndex = wrapIndex(step, count);\n  const active = figures[activeIndex];\n  const reach = reachOf(count);\n  const offsets = offsetsOf(reach);\n  const segments: Segment<string>[] = figures.map((figure) => ({\n    value: figure.id,\n    label: figure.name,\n  }));\n\n  function showNext() {\n    setStep((current) => current + 1);\n  }\n\n  function pick(figureId: string) {\n    const target = figures.findIndex((figure) => figure.id === figureId);\n    if (target === -1) {\n      return;\n    }\n    const turn = shortestTurnOf(activeIndex, target, count);\n    const nextStep = step + turn;\n    setStep(nextStep);\n  }\n\n  useImperativeHandle(handleRef, () => ({ next: showNext }));\n\n  if (!active) {\n    return null;\n  }\n\n  const announcement = spokenFigureOf(active);\n\n  return (\n    <Card\n      role='group'\n      aria-labelledby={titleId}\n      className={cn('@container relative w-full gap-4 p-5', className)}\n    >\n      <div className='flex items-start justify-between gap-3'>\n        <div className='min-w-0'>\n          <h3 id={titleId} className='text-sm font-medium'>\n            {title}\n          </h3>\n          <p className='text-muted-foreground truncate text-xs'>{period}</p>\n        </div>\n        {note && <SampleNote>{note}</SampleNote>}\n      </div>\n      <div\n        aria-hidden='true'\n        className={cn('relative h-36 overflow-hidden', FADED_ENDS, WHEEL_PEEK)}\n      >\n        <div className='bg-foreground/[0.04] absolute inset-x-0 top-1/2 -mt-7 h-14 rounded-lg' />\n        {offsets.map((offset) => {\n          const position = step + offset;\n          const index = wrapIndex(position, count);\n          const figure = figures[index];\n          return <FigureRow key={position} figure={figure} offset={offset} />;\n        })}\n      </div>\n      <dl className='sr-only'>\n        {figures.map((figure) => (\n          <div key={figure.id}>\n            <dt>{figure.name}</dt>\n            <dd>\n              {amountOf(figure)}, {figure.detail}\n            </dd>\n          </div>\n        ))}\n      </dl>\n      <Segments\n        value={active.id}\n        segments={segments}\n        onValueChange={pick}\n        label='Figure in front'\n        className='w-full'\n        itemClassName='@max-3xs:px-1'\n      />\n      <LiveRegion message={spokenUnless(isSilent, announcement)} />\n    </Card>\n  );\n}\n\nconst FIGURES: WeekFigure[] = [\n  {\n    id: 'focus',\n    name: 'Focus',\n    value: '18h 40m',\n    detail: 'of 24h planned',\n    icon: <ClockIcon />,\n  },\n  {\n    id: 'tasks',\n    name: 'Tasks',\n    value: '23',\n    unit: 'done',\n    detail: '4 more than last week',\n    icon: <CheckCheckIcon />,\n  },\n  {\n    id: 'streak',\n    name: 'Streak',\n    value: '9',\n    unit: 'days',\n    detail: 'longest this quarter',\n    icon: <ZapIcon />,\n  },\n  {\n    id: 'projects',\n    name: 'Projects',\n    value: '4',\n    unit: 'active',\n    detail: 'with time logged',\n    icon: <FolderIcon />,\n  },\n];\n\nexport default function Card07() {\n  const wheel = useRef<WeekFiguresHandle>(null);\n\n  const steps: AutoplayStep[] = [\n    { after: 2200, run: () => wheel.current?.next() },\n  ];\n  const { ref, isAutoplaying } = useCardDemo(steps, {\n    loopAfter: 0,\n  });\n\n  return (\n    <div ref={ref} className='min-h-[17.5rem] w-full max-w-[21rem]'>\n      <WeekFigures\n        title='This week'\n        period='Nov 9 to 15'\n        figures={FIGURES}\n        note='Illustrative'\n        handleRef={wheel}\n        isSilent={isAutoplaying}\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/card-07.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/sample-note.tsx",
      "content": "import { cn } from '@/registry/ndeko/lib/utils';\n\ntype SampleNoteProps = {\n  /** What the sample is: \"Illustrative\", \"Sample quote\". */\n  children?: React.ReactNode;\n  className?: string;\n};\n\n/** The word that says the figures or the words of a demo are made up. */\nexport function SampleNote({\n  children = 'Illustrative',\n  className,\n}: SampleNoteProps) {\n  return (\n    <span className={cn('text-muted-foreground text-xs', className)}>\n      {children}\n    </span>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/_parts/sample-note.tsx"
    },
    {
      "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"
}