{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "card-13",
  "title": "Nights",
  "description": "A week of sleep as columns of lights, one per hour, against a dashed goal line, where the lights of the picked night fill up beside its hours, bedtime and distance from the goal.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/card.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.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-13.tsx",
      "content": "'use client';\n\nimport { useId, useState } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { WordRoll } from '@/components/core/word-roll';\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 { cn } from '@/registry/ndeko/lib/utils';\nimport { Card } from '@/registry/ndeko/ui/card';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\n\nimport { wrapIndex } from './_parts/deck';\nimport { sideStepOf } from './_parts/keys';\nimport { SampleNote } from './_parts/sample-note';\nimport { useCardDemo } from './_parts/use-card-demo';\n\nexport type Night = {\n  id: string;\n  /** The day the night ended on, short for the column and whole for the detail: \"Thu\", \"Thursday\". */\n  day: string;\n  dayName: string;\n  /** Minutes asleep. */\n  minutes: number;\n  /** When the lights went out, as it reads: \"22:40\". */\n  bedtime: string;\n};\n\nconst DEFAULT_MAX_HOURS = 10;\n\nconst LIGHT_PX = 10;\n\nconst LIGHT_GAP_PX = 4;\n\n/** Each light of the picked night comes on this long after the one under it. */\nconst FILL_STEP_MS = 45;\n\nconst TWO_DIGITS: Intl.NumberFormatOptions = { minimumIntegerDigits: 2 };\n\n/** Under 16rem the seven columns share the width equally, with no padding of their own, so Sunday stays in the card. */\nconst COLUMN = [\n  'flex cursor-pointer flex-col items-center gap-2 rounded-lg px-1.5 py-1.5 text-xs outline-none @max-3xs:flex-1 @max-3xs:px-0',\n  'transition-[background-color,scale,color] duration-150 ease-(--ease-out-strong)',\n  'hover:bg-foreground/[0.04] focus-visible:ring-ring/25 focus-visible:ring-[3px]',\n].join(' ');\n\nconst GLOW =\n  'bg-primary absolute inset-0 rounded-full transition-[opacity,scale] duration-300 ease-(--ease-out-strong)';\n\nconst GLOW_OFF = 'scale-50 opacity-0';\n\nconst GLOW_ON = 'scale-100 opacity-100';\n\nconst GLOW_PART = 'scale-100 opacity-50';\n\ntype LightLevel = 'off' | 'part' | 'full';\n\n/** How much of the hour with this number was slept: all of it, some of it, none. */\nfunction levelOf(minutes: number, hour: number): LightLevel {\n  const hoursSlept = minutes / 60;\n  const hoursBefore = hour - 1;\n  if (hoursSlept >= hour) {\n    return 'full';\n  }\n  if (hoursSlept > hoursBefore) {\n    return 'part';\n  }\n  return 'off';\n}\n\nconst BASE_TONES: Record<LightLevel, string> = {\n  off: 'bg-foreground/[0.07]',\n  part: 'bg-foreground/15',\n  full: 'bg-foreground/25',\n};\n\nconst GLOW_TONES: Record<LightLevel, string> = {\n  off: GLOW_OFF,\n  part: GLOW_PART,\n  full: GLOW_ON,\n};\n\nfunction glowOf(level: LightLevel, isPicked: boolean) {\n  if (isPicked) {\n    return GLOW_TONES[level];\n  }\n  return GLOW_OFF;\n}\n\n/** The lights of the picked night come on from the bottom up. A night that is left goes dark at once. */\nfunction fillDelayOf(hour: number, isPicked: boolean) {\n  if (!isPicked) {\n    return '0ms';\n  }\n  const steps = hour - 1;\n  const delay = steps * FILL_STEP_MS;\n  return `${delay}ms`;\n}\n\nfunction durationOf(minutes: number) {\n  const whole = Math.round(minutes);\n  const hours = Math.floor(whole / 60);\n  const rest = whole % 60;\n  return { hours, rest };\n}\n\nfunction spanOf(minutes: number) {\n  const { hours, rest } = durationOf(minutes);\n  if (hours === 0) {\n    return `${rest} min`;\n  }\n  if (rest === 0) {\n    return `${hours}h`;\n  }\n  return `${hours}h ${rest}m`;\n}\n\nfunction goalLineOf(minutes: number, goalMinutes: number) {\n  const exactDifference = minutes - goalMinutes;\n  const difference = Math.round(exactDifference);\n  const goal = spanOf(goalMinutes);\n  if (difference === 0) {\n    return `Right on the ${goal} goal`;\n  }\n  const distance = Math.abs(difference);\n  const gap = spanOf(distance);\n  if (difference < 0) {\n    return `${gap} short of the ${goal} goal`;\n  }\n  return `${gap} over the ${goal} goal`;\n}\n\nfunction averageOf(nights: Night[]) {\n  if (nights.length === 0) {\n    return 0;\n  }\n  let total = 0;\n  for (const night of nights) {\n    total += night.minutes;\n  }\n  return total / nights.length;\n}\n\nfunction spokenNightOf(night: Night, goalMinutes: number) {\n  const { hours, rest } = durationOf(night.minutes);\n  const goalLine = goalLineOf(night.minutes, goalMinutes);\n  return `${night.dayName}: ${hours} hours ${rest} minutes, lights out at ${night.bedtime}, ${goalLine}`;\n}\n\nfunction dayToneOf(isPicked: boolean) {\n  if (isPicked) {\n    return 'font-medium';\n  }\n  return 'text-muted-foreground';\n}\n\nfunction tabStopOf(isPicked: boolean) {\n  if (isPicked) {\n    return 0;\n  }\n  return -1;\n}\n\ntype NightColumnProps = {\n  night: Night;\n  hours: number[];\n  label: string;\n  isPicked: boolean;\n  isPressed: boolean;\n  onPick: () => void;\n};\n\nfunction NightColumn({\n  night,\n  hours,\n  label,\n  isPicked,\n  isPressed,\n  onPick,\n}: NightColumnProps) {\n  return (\n    <button\n      type='button'\n      role='radio'\n      aria-checked={isPicked}\n      aria-label={label}\n      tabIndex={tabStopOf(isPicked)}\n      onClick={onPick}\n      className={cn(COLUMN, pressedQuietOf(isPressed))}\n    >\n      <span aria-hidden='true' className='flex flex-col-reverse gap-1'>\n        {hours.map((hour) => {\n          const level = levelOf(night.minutes, hour);\n          const glowStyle = { transitionDelay: fillDelayOf(hour, isPicked) };\n          return (\n            <span\n              key={hour}\n              className={cn(\n                'relative size-2.5 rounded-full',\n                BASE_TONES[level]\n              )}\n            >\n              <span\n                style={glowStyle}\n                className={cn(GLOW, glowOf(level, isPicked))}\n              />\n            </span>\n          );\n        })}\n      </span>\n      <span aria-hidden='true' className={dayToneOf(isPicked)}>\n        {night.day}\n      </span>\n    </button>\n  );\n}\n\nexport type NightsCardProps = {\n  nights: Night[];\n  goalMinutes: number;\n  selectedId: string;\n  onSelect: (nightId: string) => void;\n  /** How many hours a column holds, one light each. */\n  maxHours?: number;\n  /** Says the nights are made up. Leave it out for real ones. */\n  note?: string;\n  /** The night a demonstration picks, shown held down. */\n  pressedId?: string | null;\n  className?: string;\n};\n\nexport function NightsCard({\n  nights,\n  goalMinutes,\n  selectedId,\n  onSelect,\n  maxHours = DEFAULT_MAX_HOURS,\n  note,\n  pressedId = null,\n  className,\n}: NightsCardProps) {\n  const titleId = useId();\n  const selectedIndex = nights.findIndex((night) => night.id === selectedId);\n  const selected = nights[selectedIndex];\n  const hours = Array.from({ length: maxHours }, (_, index) => index + 1);\n  const step = LIGHT_PX + LIGHT_GAP_PX;\n  const halfGap = LIGHT_GAP_PX / 2;\n  const goalHours = goalMinutes / 60;\n  const goalTop = goalHours * step;\n  const goalRise = goalTop - halfGap;\n  const goalStyle = { bottom: goalRise };\n  const goalLabel = spanOf(goalMinutes);\n  const averageMinutes = averageOf(nights);\n  const average = spanOf(averageMinutes);\n\n  function pickWithArrows(event: React.KeyboardEvent<HTMLDivElement>) {\n    const direction = sideStepOf(event.key);\n    if (direction === 0) {\n      return;\n    }\n    event.preventDefault();\n    const steppedIndex = selectedIndex + direction;\n    const nextIndex = wrapIndex(steppedIndex, nights.length);\n    const next = nights[nextIndex];\n    if (!next) {\n      return;\n    }\n    const columns =\n      event.currentTarget.querySelectorAll<HTMLElement>('[role=\"radio\"]');\n    onSelect(next.id);\n    columns[nextIndex]?.focus();\n  }\n\n  if (!selected) {\n    return null;\n  }\n\n  const slept = durationOf(selected.minutes);\n  const goalLine = goalLineOf(selected.minutes, goalMinutes);\n\n  return (\n    <Card\n      role='group'\n      aria-labelledby={titleId}\n      className={cn('@container w-full gap-4 p-5', className)}\n    >\n      <div className='flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1'>\n        <div className='flex min-w-0 items-baseline gap-2'>\n          <h3 id={titleId} className='text-sm font-medium'>\n            Sleep\n          </h3>\n          {note && <SampleNote className='truncate'>{note}</SampleNote>}\n        </div>\n        <p className='text-muted-foreground text-xs tabular-nums'>\n          Average {average}\n        </p>\n      </div>\n      <div className='flex items-start gap-2'>\n        <div\n          aria-hidden='true'\n          className='text-muted-foreground relative mt-1.5 h-[8.5rem] shrink-0 text-xs whitespace-nowrap tabular-nums'\n        >\n          <span className='invisible'>{goalLabel}</span>\n          <span style={goalStyle} className='absolute start-0 translate-y-1/2'>\n            {goalLabel}\n          </span>\n        </div>\n        <div\n          role='radiogroup'\n          aria-label='Night'\n          onKeyDown={pickWithArrows}\n          className='relative flex min-w-0 flex-1 justify-between'\n        >\n          <div\n            aria-hidden='true'\n            className='pointer-events-none absolute inset-x-0 top-1.5 h-[8.5rem]'\n          >\n            <span\n              style={goalStyle}\n              className='hairline-t border-foreground/35 absolute inset-x-0 border-dashed'\n            />\n          </div>\n          {nights.map((night) => (\n            <NightColumn\n              key={night.id}\n              night={night}\n              hours={hours}\n              label={spokenNightOf(night, goalMinutes)}\n              isPicked={night.id === selected.id}\n              isPressed={night.id === pressedId}\n              onPick={() => onSelect(night.id)}\n            />\n          ))}\n        </div>\n      </div>\n      <div className='flex items-end justify-between gap-3 @max-2xs:flex-col @max-2xs:items-start @max-2xs:gap-2'>\n        <div className='min-w-0'>\n          <p className='text-muted-foreground text-xs'>\n            <Swap swapKey={selected.id}>{selected.dayName}</Swap>\n          </p>\n          <p\n            aria-hidden='true'\n            className='flex items-baseline text-[28px] leading-8 font-semibold'\n          >\n            <MotionNumber value={slept.hours} suffix='h' />\n            <MotionNumber\n              value={slept.rest}\n              suffix='m'\n              format={TWO_DIGITS}\n              className='ms-1.5'\n            />\n          </p>\n        </div>\n        <div className='flex min-w-0 flex-col items-end text-xs @max-2xs:items-start'>\n          <p className='tabular-nums'>\n            <span className='text-muted-foreground'>Lights out </span>\n            <Swap swapKey={selected.id}>{selected.bedtime}</Swap>\n          </p>\n          <WordRoll text={goalLine} className='text-muted-foreground' />\n        </div>\n      </div>\n    </Card>\n  );\n}\n\nconst NIGHTS: Night[] = [\n  { id: 'mon', day: 'Mon', dayName: 'Monday', minutes: 412, bedtime: '23:48' },\n  { id: 'tue', day: 'Tue', dayName: 'Tuesday', minutes: 455, bedtime: '23:10' },\n  {\n    id: 'wed',\n    day: 'Wed',\n    dayName: 'Wednesday',\n    minutes: 388,\n    bedtime: '00:35',\n  },\n  {\n    id: 'thu',\n    day: 'Thu',\n    dayName: 'Thursday',\n    minutes: 502,\n    bedtime: '22:40',\n  },\n  { id: 'fri', day: 'Fri', dayName: 'Friday', minutes: 431, bedtime: '23:55' },\n  {\n    id: 'sat',\n    day: 'Sat',\n    dayName: 'Saturday',\n    minutes: 538,\n    bedtime: '23:20',\n  },\n  { id: 'sun', day: 'Sun', dayName: 'Sunday', minutes: 468, bedtime: '23:05' },\n];\n\nconst GOAL_MINUTES = 480;\n\nconst LAST_NIGHT_ID = 'sun';\n\nfunction announcementOf(nightId: string) {\n  const night = NIGHTS.find((candidate) => candidate.id === nightId);\n  if (!night) {\n    return '';\n  }\n  return spokenNightOf(night, GOAL_MINUTES);\n}\n\nexport default function Card13() {\n  const [selectedId, setSelectedId] = useState(LAST_NIGHT_ID);\n  const { pressed, press } = usePress<string>();\n\n  const steps: AutoplayStep[] = [\n    { after: 2200, run: () => press('wed') },\n    { after: PRESS_LEAD_MS, run: () => setSelectedId('wed') },\n    { after: 2200, run: () => press('thu') },\n    { after: PRESS_LEAD_MS, run: () => setSelectedId('thu') },\n    { after: 2200, run: () => press('sat') },\n    { after: PRESS_LEAD_MS, run: () => setSelectedId('sat') },\n    { after: 2200, run: () => press(LAST_NIGHT_ID) },\n    { after: PRESS_LEAD_MS, run: () => setSelectedId(LAST_NIGHT_ID) },\n  ];\n  const { ref, isAutoplaying } = useCardDemo(steps, {\n    loopAfter: 400,\n  });\n\n  return (\n    <div ref={ref} className='min-h-[19.5rem] w-full max-w-[22rem]'>\n      <NightsCard\n        nights={NIGHTS}\n        goalMinutes={GOAL_MINUTES}\n        selectedId={selectedId}\n        onSelect={setSelectedId}\n        note='Sample week'\n        pressedId={pressed}\n      />\n      <LiveRegion\n        message={spokenUnless(isAutoplaying, announcementOf(selectedId))}\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/card-13.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/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"
}