{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-12",
  "title": "Matchup",
  "description": "Two contenders compared on six criteria as one shape made of petals, each as long as the lead and in the colour of whoever leads there, with a sentence that names the leads and petals that reshape when a contender changes.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/select.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/chart/chart-12.tsx",
      "content": "'use client';\n\nimport { useState } from 'react';\n\nimport type { AutoplayStep } from '@/registry/ndeko/hooks/use-autoplay';\nimport { seriesColorOf, type SeriesSlot } from '@/registry/ndeko/lib/agent-run';\nimport { hold, spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from '@/registry/ndeko/ui/select';\n\nimport { ChartCard } from './_parts/chart-card';\nimport { walkSteps, whileDemonstrating } from './_parts/demo';\nimport { MorphPath } from './_parts/morph-path';\nimport { PLOT_SURFACE } from './_parts/plot';\nimport { useChartDemo } from './_parts/use-chart-demo';\nimport { activeIndexOf, readingAloud, useReading } from './_parts/use-reading';\nimport { WrappingRoll } from './_parts/wrapping-roll';\n\nexport type MatchupContender = {\n  id: string;\n  name: string;\n  /** Fixed per contender, so a colour always names the same one whoever it meets. */\n  series: SeriesSlot;\n  /** One score per criterion, where a higher score is better. */\n  scores: readonly number[];\n};\n\nexport type MatchupProps = {\n  title: string;\n  /** A short mark beside the title, such as \"Illustrative\" over sample data. */\n  note?: string;\n  criteria: readonly string[];\n  contenders: readonly MatchupContender[];\n  firstId: string;\n  secondId: string;\n  onFirstIdChange: (id: string) => void;\n  onSecondIdChange: (id: string) => void;\n  /** Lights a criterion from outside, for a demonstration. */\n  guideIndex?: number | null;\n  className?: string;\n};\n\ntype Lead = {\n  criterion: string;\n  first: number;\n  second: number;\n  /** How far ahead the leader is. Zero when the two are level. */\n  size: number;\n  /** Null when the two are level. */\n  leader: MatchupContender | null;\n};\n\n/** The shape is drawn in a square of this many units from its centre to an edge. */\nconst HALF_VIEW = 100;\n\nconst VIEW_BOX = '-100 -100 200 200';\n\nconst PETAL_REACH = 62;\n\n/** A criterion where the two are level still shows a bud, so no direction of the shape is empty. */\nconst BUD_REACH = 9;\n\nconst PETAL_GROWTH = PETAL_REACH - BUD_REACH;\n\nconst LABEL_REACH = 84;\n\n/** How far along a petal its sides stop spreading and turn back in. */\nconst FLARE = 0.55;\n\n/** Petals stay this share inside the line that splits two neighbours, so they never touch. */\nconst CLEARANCE = 0.88;\n\nconst FULL_TURN = Math.PI * 2;\n\nconst LEVEL_COLOR = 'color-mix(in oklab, var(--foreground) 18%, transparent)';\n\nfunction scoreAt(contender: MatchupContender, index: number) {\n  return contender.scores[index] ?? 0;\n}\n\nfunction leaderOf(\n  difference: number,\n  first: MatchupContender,\n  second: MatchupContender\n) {\n  if (difference > 0) {\n    return first;\n  }\n  if (difference < 0) {\n    return second;\n  }\n  return null;\n}\n\nfunction leadsOf(\n  criteria: readonly string[],\n  first: MatchupContender,\n  second: MatchupContender\n) {\n  return criteria.map((criterion, index): Lead => {\n    const firstScore = scoreAt(first, index);\n    const secondScore = scoreAt(second, index);\n    const difference = firstScore - secondScore;\n    return {\n      criterion,\n      first: firstScore,\n      second: secondScore,\n      size: Math.abs(difference),\n      leader: leaderOf(difference, first, second),\n    };\n  });\n}\n\n/** The widest gap between any two contenders on any criterion: the lead a full petal stands for. */\nfunction widestGapOf(\n  criteria: readonly string[],\n  contenders: readonly MatchupContender[]\n) {\n  let widest = 1;\n  for (const [index] of criteria.entries()) {\n    const scores = contenders.map((contender) => scoreAt(contender, index));\n    const highest = Math.max(...scores);\n    const lowest = Math.min(...scores);\n    widest = Math.max(widest, highest - lowest);\n  }\n  return widest;\n}\n\nfunction reachOf(lead: Lead, widestGap: number) {\n  const share = lead.size / widestGap;\n  const growth = share * PETAL_GROWTH;\n  return BUD_REACH + growth;\n}\n\nfunction angleOf(index: number, count: number) {\n  const share = index / count;\n  return share * FULL_TURN;\n}\n\n/** A point turned round the centre by an angle, clockwise from straight up, written for a path. */\nfunction turned(x: number, y: number, angle: number) {\n  const cos = Math.cos(angle);\n  const sin = Math.sin(angle);\n  const turnedX = x * cos - y * sin;\n  const turnedY = x * sin + y * cos;\n  const left = turnedX.toFixed(2);\n  const top = turnedY.toFixed(2);\n  return `${left} ${top}`;\n}\n\n/**\n * A petal from the centre to its tip. Its sides leave the centre inside the line that splits two\n * neighbours, so petals of any length never overlap, and they meet at a round tip.\n */\nfunction petalPathOf(reach: number, angle: number, criterionCount: number) {\n  const halfSlice = Math.PI / criterionCount;\n  const spread = Math.tan(halfSlice) * CLEARANCE;\n  const flareAt = reach * FLARE;\n  const side = flareAt * spread;\n  const shoulder = -flareAt;\n  const base = turned(0, 0, angle);\n  const tip = turned(0, -reach, angle);\n  const rightOut = turned(side, shoulder, angle);\n  const rightIn = turned(side, -reach, angle);\n  const leftIn = turned(-side, -reach, angle);\n  const leftOut = turned(-side, shoulder, angle);\n  return `M${base} C${rightOut} ${rightIn} ${tip} C${leftIn} ${leftOut} ${base} Z`;\n}\n\n/** A distance from the centre of the square, as a percentage from its left or top edge. */\nfunction percentFromCentre(distance: number) {\n  const share = distance / HALF_VIEW;\n  const percent = 50 + share * 50;\n  return `${percent}%`;\n}\n\n/** Where the label of a criterion sits round the shape, in percentages of its square. */\nfunction labelPlaceOf(angle: number): React.CSSProperties {\n  const x = Math.sin(angle) * LABEL_REACH;\n  const y = -Math.cos(angle) * LABEL_REACH;\n  const left = percentFromCentre(x);\n  const top = percentFromCentre(y);\n  return { left, top };\n}\n\nfunction colorOf(contender: MatchupContender | null) {\n  if (!contender) {\n    return LEVEL_COLOR;\n  }\n  return seriesColorOf(contender.series);\n}\n\nfunction leadTextOf(lead: Lead) {\n  if (!lead.leader) {\n    return 'Level';\n  }\n  return `+${lead.size}`;\n}\n\nfunction leadWordsOf(lead: Lead) {\n  if (!lead.leader) {\n    return `${lead.criterion}: level`;\n  }\n  return `${lead.criterion}: ${lead.leader.name} leads by ${lead.size}`;\n}\n\nfunction listOf(names: readonly string[]) {\n  if (names.length <= 1) {\n    return names.join('');\n  }\n  const last = names[names.length - 1];\n  const others = names.slice(0, -1);\n  const start = others.join(', ');\n  return `${start} and ${last}`;\n}\n\n/** The two criteria a contender leads by the most, in words. */\nfunction strengthsOf(leads: readonly Lead[], contender: MatchupContender) {\n  const own = leads.filter((lead) => lead.leader?.id === contender.id);\n  const ranked = [...own].sort((first, second) => second.size - first.size);\n  const strongest = ranked.slice(0, 2);\n  const names = strongest.map((lead) => lead.criterion.toLowerCase());\n  return listOf(names);\n}\n\nfunction firstLineOf(leads: readonly Lead[], first: MatchupContender) {\n  const strengths = strengthsOf(leads, first);\n  if (strengths === '') {\n    return `${first.name} leads nowhere`;\n  }\n  return `${first.name} leads on ${strengths}`;\n}\n\nfunction secondLineOf(leads: readonly Lead[], second: MatchupContender) {\n  const strengths = strengthsOf(leads, second);\n  if (strengths === '') {\n    return `${second.name} leads nowhere`;\n  }\n  return `${second.name} on ${strengths}`;\n}\n\nfunction dimmedOf(isDimmed: boolean) {\n  if (isDimmed) {\n    return 'opacity-35';\n  }\n  return undefined;\n}\n\nfunction litOf(isLit: boolean) {\n  if (isLit) {\n    return 'text-foreground';\n  }\n  return 'text-muted-foreground';\n}\n\ntype ColorKeyProps = {\n  color: string;\n  className?: string;\n};\n\nfunction ColorKey({ color, className }: ColorKeyProps) {\n  return (\n    <span\n      aria-hidden='true'\n      className={cn('size-2 shrink-0 rounded-full', className)}\n      style={{ backgroundColor: color }}\n    />\n  );\n}\n\ntype ContenderPickerProps = {\n  label: string;\n  contenders: readonly MatchupContender[];\n  value: string;\n  /** The contender on the other side, which this side cannot also pick. */\n  takenId: string;\n  onValueChange: (id: string) => void;\n};\n\nfunction ContenderPicker({\n  label,\n  contenders,\n  value,\n  takenId,\n  onValueChange,\n}: ContenderPickerProps) {\n  const items = contenders.map((contender) => ({\n    value: contender.id,\n    label: contender.name,\n  }));\n\n  function changeValue(next: string | null) {\n    if (next !== null) {\n      onValueChange(next);\n    }\n  }\n\n  return (\n    <Select items={items} value={value} onValueChange={changeValue}>\n      <SelectTrigger size='sm' aria-label={label} className='w-auto min-w-0'>\n        <SelectValue />\n      </SelectTrigger>\n      <SelectContent>\n        {contenders.map((contender) => (\n          <SelectItem\n            key={contender.id}\n            value={contender.id}\n            disabled={contender.id === takenId}\n          >\n            {contender.name}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n\nexport function Matchup({\n  title,\n  note,\n  criteria,\n  contenders,\n  firstId,\n  secondId,\n  onFirstIdChange,\n  onSecondIdChange,\n  guideIndex = null,\n  className,\n}: MatchupProps) {\n  const [hasPicked, setHasPicked] = useState(false);\n  const first = contenderOf(contenders, firstId);\n  const second = contenderOf(contenders, secondId);\n  const leads = leadsOf(criteria, first, second);\n  const widestGap = widestGapOf(criteria, contenders);\n  const count = Math.max(criteria.length, 1);\n  const reading = useReading({ count, defaultIndex: 0, guideIndex });\n  const activeIndex = activeIndexOf(reading.isActive, reading.shownIndex);\n  const firstLine = firstLineOf(leads, first);\n  const secondLine = secondLineOf(leads, second);\n  const sentence = `${firstLine}; ${secondLine}`;\n  const shownLead = leads.at(reading.shownIndex);\n  const pointReading = readingOfLead(shownLead);\n  const keyReading = readingAloud(reading.isReadingByKeys, pointReading);\n\n  /** The sentence is said aloud once a person has picked a contender: a demonstration stays silent. */\n  function pickFirst(id: string) {\n    setHasPicked(true);\n    onFirstIdChange(id);\n  }\n\n  function pickSecond(id: string) {\n    setHasPicked(true);\n    onSecondIdChange(id);\n  }\n\n  return (\n    <ChartCard\n      title={title}\n      note={note}\n      summary={`${sentence}.`}\n      className={className}\n    >\n      <div className='flex flex-wrap items-center gap-2'>\n        <ContenderPicker\n          label='First contender'\n          contenders={contenders}\n          value={first.id}\n          takenId={second.id}\n          onValueChange={pickFirst}\n        />\n        <span className='text-muted-foreground text-xs'>against</span>\n        <ContenderPicker\n          label='Second contender'\n          contenders={contenders}\n          value={second.id}\n          takenId={first.id}\n          onValueChange={pickSecond}\n        />\n      </div>\n      <div className='flex flex-col gap-0.5 text-[13px]'>\n        <p className='flex items-start gap-2'>\n          <ColorKey color={colorOf(first)} className='mt-1.5' />\n          <WrappingRoll text={firstLine} className='min-w-0' />\n        </p>\n        <p className='flex items-start gap-2'>\n          <ColorKey color={colorOf(second)} className='mt-1.5' />\n          <WrappingRoll text={secondLine} className='min-w-0' />\n        </p>\n      </div>\n      <div\n        role='group'\n        tabIndex={0}\n        aria-label={`${title}. Use the arrow keys to read each criterion.`}\n        className={cn(\n          PLOT_SURFACE,\n          'mx-auto aspect-square w-full max-w-[17rem]'\n        )}\n        {...reading.markHandlers}\n      >\n        <svg\n          aria-hidden='true'\n          viewBox={VIEW_BOX}\n          className='absolute inset-0 size-full'\n        >\n          <circle\n            r={PETAL_REACH}\n            vectorEffect='non-scaling-stroke'\n            className='stroke-border fill-none [stroke-width:var(--hairline)]'\n          />\n          {leads.map((lead, index) => {\n            const angle = angleOf(index, count);\n            const reach = reachOf(lead, widestGap);\n            const isDimmed = activeIndex !== null && activeIndex !== index;\n\n            return (\n              <MorphPath\n                key={lead.criterion}\n                d={petalPathOf(reach, angle, count)}\n                onPointerEnter={() => reading.pointTo(index)}\n                className={cn(\n                  'transition-[fill,opacity] duration-300 ease-(--ease-out-strong)',\n                  dimmedOf(isDimmed)\n                )}\n                style={{ fill: colorOf(lead.leader) }}\n              />\n            );\n          })}\n          <circle r={3.5} className='fill-card' />\n        </svg>\n        {leads.map((lead, index) => (\n          <span\n            key={lead.criterion}\n            aria-hidden='true'\n            className={cn(\n              'pointer-events-none absolute flex -translate-1/2 flex-col items-center text-[11px] leading-4 whitespace-nowrap transition-colors duration-150',\n              litOf(activeIndex === index)\n            )}\n            style={labelPlaceOf(angleOf(index, count))}\n          >\n            {lead.criterion}\n            <span className='flex items-center gap-1 tabular-nums'>\n              <ColorKey color={colorOf(lead.leader)} />\n              {leadTextOf(lead)}\n            </span>\n          </span>\n        ))}\n      </div>\n      <table className='w-full text-xs tabular-nums'>\n        <caption className='sr-only'>\n          Scores on each criterion, and who leads\n        </caption>\n        <thead>\n          <tr className='text-muted-foreground text-start'>\n            <th scope='col' className='py-1.5 text-start font-normal'>\n              Criterion\n            </th>\n            <th\n              scope='col'\n              className='py-1.5 ps-3 text-end font-normal text-balance'\n            >\n              {first.name}\n            </th>\n            <th\n              scope='col'\n              className='py-1.5 ps-3 text-end font-normal text-balance'\n            >\n              {second.name}\n            </th>\n            <th scope='col' className='py-1.5 ps-3 text-end font-normal'>\n              Lead\n            </th>\n          </tr>\n        </thead>\n        <tbody>\n          {leads.map((lead, index) => (\n            <tr\n              key={lead.criterion}\n              onPointerEnter={() => reading.pointTo(index)}\n              onPointerLeave={() => reading.pointTo(null)}\n              className={cn(\n                'hairline-t border-border transition-colors duration-150',\n                activeIndex === index && 'bg-foreground/[0.03]'\n              )}\n            >\n              <th scope='row' className='py-1.5 text-start font-medium'>\n                {lead.criterion}\n              </th>\n              <td className='py-1.5 ps-3 text-end'>{lead.first}</td>\n              <td className='py-1.5 ps-3 text-end'>{lead.second}</td>\n              <td className='py-1.5 ps-3 text-end'>\n                <span className='inline-flex items-center justify-end gap-1.5'>\n                  <ColorKey color={colorOf(lead.leader)} />\n                  {leadTextOf(lead)}\n                  <span className='sr-only'>\n                    {lead.leader && ` for ${lead.leader.name}`}\n                  </span>\n                </span>\n              </td>\n            </tr>\n          ))}\n        </tbody>\n      </table>\n      <LiveRegion message={keyReading} />\n      <LiveRegion message={spokenUnless(!hasPicked, sentence)} />\n    </ChartCard>\n  );\n}\n\nfunction contenderOf(contenders: readonly MatchupContender[], id: string) {\n  const contender = contenders.find((candidate) => candidate.id === id);\n  return contender ?? contenders[0];\n}\n\nfunction readingOfLead(lead: Lead | undefined) {\n  if (!lead) {\n    return '';\n  }\n  return leadWordsOf(lead);\n}\n\nconst CRITERIA = [\n  'Reasoning',\n  'Accuracy',\n  'Speed',\n  'Cost',\n  'Context',\n  'Tool use',\n];\n\nconst MODELS: MatchupContender[] = [\n  {\n    id: 'lumen-max',\n    name: 'Lumen Max',\n    series: 3,\n    scores: [92, 90, 58, 44, 88, 84],\n  },\n  {\n    id: 'lumen-swift',\n    name: 'Lumen Swift',\n    series: 1,\n    scores: [71, 76, 93, 91, 62, 70],\n  },\n  {\n    id: 'quarry-large',\n    name: 'Quarry Large',\n    series: 2,\n    scores: [86, 84, 72, 63, 91, 77],\n  },\n  {\n    id: 'quarry-mini',\n    name: 'Quarry Mini',\n    series: 4,\n    scores: [64, 70, 89, 95, 55, 61],\n  },\n];\n\nconst FIRST_MODEL = 'lumen-max';\n\nconst RESTING_RIVAL = 'lumen-swift';\n\n/** Cost, speed, then context: where the two resting contenders are furthest apart. */\nconst WALK = [3, 2, 4];\n\nexport default function Chart12() {\n  const [firstId, setFirstId] = useState(FIRST_MODEL);\n  const [secondId, setSecondId] = useState(RESTING_RIVAL);\n  const [guide, setGuide] = useState<number | null>(null);\n\n  function resetDemo() {\n    setFirstId(FIRST_MODEL);\n    setSecondId(RESTING_RIVAL);\n    setGuide(null);\n  }\n\n  const steps: AutoplayStep[] = [\n    ...walkSteps(WALK, setGuide, { startAfter: 1300, stepMs: 900 }),\n    { after: 1100, run: () => setGuide(null) },\n    { after: 500, run: () => setSecondId('quarry-large') },\n    { after: 2600, run: () => setSecondId('quarry-mini') },\n    { after: 2600, run: () => setSecondId(RESTING_RIVAL) },\n    { after: 1400, run: hold },\n  ];\n  const { ref, isAutoplaying, stopOnKeyboardFocus } = useChartDemo(steps, {\n    loopAfter: 1600,\n    onReset: resetDemo,\n  });\n\n  return (\n    <div\n      ref={ref}\n      onFocus={stopOnKeyboardFocus}\n      className='flex min-h-[41rem] w-full max-w-[26rem]'\n    >\n      <Matchup\n        title='Model matchup'\n        note='Illustrative'\n        criteria={CRITERIA}\n        contenders={MODELS}\n        firstId={firstId}\n        secondId={secondId}\n        onFirstIdChange={setFirstId}\n        onSecondIdChange={setSecondId}\n        guideIndex={whileDemonstrating(isAutoplaying, guide)}\n        className='w-full'\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/chart/chart-12.tsx"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/axis.tsx",
      "content": "import { cn } from '@/registry/ndeko/lib/utils';\n\nimport { yOf } from './path';\nimport { columnCenterOf, percentOf, type Scale } from './scale';\n\n/** The least room one label of the category axis needs, text and breathing space. */\nexport const LABEL_ROOM_PX = 56;\n\ntype ValueAxisProps = {\n  scale: Scale;\n  height: number;\n  format: (value: number) => string;\n  className?: string;\n};\n\n/** The figures of the value axis, one per gridline, in a column beside the plot. */\nexport function ValueAxis({\n  scale,\n  height,\n  format,\n  className,\n}: ValueAxisProps) {\n  return (\n    <div\n      aria-hidden='true'\n      className={cn('relative w-9 shrink-0', className)}\n      style={{ height }}\n    >\n      {scale.ticks.map((tick) => (\n        <span\n          key={tick}\n          className='text-muted-foreground absolute right-0 -translate-y-1/2 text-[11px] tabular-nums'\n          style={{ top: yOf(tick, scale, height) }}\n        >\n          {format(tick)}\n        </span>\n      ))}\n    </div>\n  );\n}\n\n/** Zero is drawn stronger when values go below it, since bars start there. */\nexport function gridToneOf(tick: number, scale: Scale) {\n  const isZero = tick === 0;\n  const crossesZero = scale.min < 0;\n  if (isZero && crossesZero) {\n    return 'border-foreground/25';\n  }\n  return 'border-border';\n}\n\ntype GridLinesProps = {\n  scale: Scale;\n  height: number;\n};\n\nexport function GridLines({ scale, height }: GridLinesProps) {\n  return (\n    <div aria-hidden='true' className='pointer-events-none absolute inset-0'>\n      {scale.ticks.map((tick) => (\n        <span\n          key={tick}\n          className={cn(\n            'hairline-t absolute inset-x-0',\n            gridToneOf(tick, scale)\n          )}\n          style={{ top: yOf(tick, scale, height) }}\n        />\n      ))}\n    </div>\n  );\n}\n\nexport type AxisLabel = {\n  id: string;\n  text: string;\n  /** From 0 at the left edge of the plot to 1 at its right edge. */\n  ratio: number;\n  isStrong?: boolean;\n};\n\n/** Every how many positions a label is written, so the labels that are written never touch. */\nexport function labelStepOf(count: number, plotWidth: number) {\n  const fitting = Math.floor(plotWidth / LABEL_ROOM_PX);\n  const labelCount = Math.max(fitting, 1);\n  const step = Math.ceil(count / labelCount);\n  return Math.max(step, 1);\n}\n\n/** The labels kept when one in `step` is written, counted back from the last so the latest is always named. */\nexport function spacedLabelsOf(labels: readonly AxisLabel[], step: number) {\n  const lastIndex = labels.length - 1;\n  return labels.filter((_, index) => {\n    const fromLast = lastIndex - index;\n    return fromLast % step === 0;\n  });\n}\n\n/**\n * One label per position, under the middle of its column, written as often as the room allows. The\n * one at `strongIndex`, such as today, is set stronger.\n */\nexport function positionLabelsOf(\n  labels: readonly string[],\n  plotWidth: number,\n  strongIndex?: number\n) {\n  const all: AxisLabel[] = labels.map((text, index) => ({\n    id: `${index}-${text}`,\n    text,\n    ratio: columnCenterOf(index, labels.length),\n    isStrong: index === strongIndex,\n  }));\n  const step = labelStepOf(labels.length, plotWidth);\n  return spacedLabelsOf(all, step);\n}\n\nfunction strongOf(isStrong: boolean | undefined) {\n  if (isStrong) {\n    return 'text-foreground font-medium';\n  }\n  return 'text-muted-foreground';\n}\n\ntype LabelAlign = 'spread' | 'center';\n\n/**\n * A spread label slides from its left edge to its right edge as it crosses the plot, like the\n * readout, so the first and the last never stick out of the piece. A centred label sits under its\n * mark, for the few wide columns of a bar chart.\n */\nfunction labelStyleOf(\n  label: AxisLabel,\n  align: LabelAlign\n): React.CSSProperties {\n  const left = percentOf(label.ratio);\n  if (align === 'center') {\n    return { left, transform: 'translateX(-50%)' };\n  }\n  const shift = percentOf(-label.ratio);\n  return { left, transform: `translateX(${shift})` };\n}\n\ntype CategoryAxisProps = {\n  labels: readonly AxisLabel[];\n  align?: LabelAlign;\n  className?: string;\n};\n\nexport function CategoryAxis({\n  labels,\n  align = 'spread',\n  className,\n}: CategoryAxisProps) {\n  return (\n    <div aria-hidden='true' className={cn('relative h-4', className)}>\n      {labels.map((label) => (\n        <span\n          key={label.id}\n          className={cn(\n            'absolute top-0 text-[11px] whitespace-nowrap tabular-nums',\n            strongOf(label.isStrong)\n          )}\n          style={labelStyleOf(label, align)}\n        >\n          {label.text}\n        </span>\n      ))}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/axis.tsx"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/chart-card.tsx",
      "content": "import { useId } from 'react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Badge } from '@/registry/ndeko/ui/badge';\n\ntype ChartCardProps = {\n  title: string;\n  /** A short mark beside the title, such as \"Illustrative\" over sample data. */\n  note?: string;\n  /** One line that says what the chart shows, read by screen readers with the title. */\n  summary: string;\n  /** Controls that change what the chart draws: a period, a view. */\n  actions?: React.ReactNode;\n  className?: string;\n  children: React.ReactNode;\n};\n\n/**\n * The surface every chart sits on. It is a query container, so a chart lays itself out by the\n * room it has, and it is positioned, so the hidden table of a chart never widens the page.\n */\nexport function ChartCard({\n  title,\n  note,\n  summary,\n  actions,\n  className,\n  children,\n}: ChartCardProps) {\n  const titleId = useId();\n  const summaryId = useId();\n\n  return (\n    <section\n      aria-labelledby={titleId}\n      aria-describedby={summaryId}\n      className={cn(\n        'bg-card hairline-ring ring-border @container relative flex flex-col gap-4 rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]',\n        className\n      )}\n    >\n      <header className='flex min-h-7 flex-wrap items-center justify-between gap-x-3 gap-y-2'>\n        <div className='flex min-w-0 items-center gap-2'>\n          <h3 id={titleId} className='text-sm font-medium text-balance'>\n            {title}\n          </h3>\n          {note && <Badge variant='secondary'>{note}</Badge>}\n        </div>\n        {actions}\n      </header>\n      {children}\n      <p id={summaryId} className='sr-only'>\n        {summary}\n      </p>\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/chart-card.tsx"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/demo.ts",
      "content": "import type { AutoplayStep } from '@/registry/ndeko/hooks/use-autoplay';\nimport { keyDelayOf } from '@/registry/ndeko/lib/demonstration';\n\ntype WalkOptions = {\n  /** Milliseconds before the first position. */\n  startAfter?: number;\n  /** Milliseconds between two positions. */\n  stepMs?: number;\n};\n\n/** One step per position, so a reading crosses a plot the way a pointer does. */\nexport function walkSteps<Position>(\n  positions: readonly Position[],\n  moveTo: (position: Position) => void,\n  { startAfter = 700, stepMs = 240 }: WalkOptions = {}\n): AutoplayStep[] {\n  return positions.map((position, index) => {\n    const after = keyDelayOf(index, startAfter, stepMs);\n    return { after, run: () => moveTo(position) };\n  });\n}\n\n/** What a demonstration points at lets go the moment a person takes over. */\nexport function whileDemonstrating<Value>(\n  isDemonstrating: boolean,\n  value: Value | null\n) {\n  if (isDemonstrating) {\n    return value;\n  }\n  return null;\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/demo.ts"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/morph-path.tsx",
      "content": "'use client';\n\nimport { motion, type Transition } from 'motion/react';\nimport { useState } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { EASE_OUT_STRONG, INSTANT } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nconst MORPH: Transition = { duration: 0.3, ease: EASE_OUT_STRONG };\n\n/** What is there on mount does not fade in: only a shape that replaced another one does. */\nconst SWAP_FADE =\n  'transition-opacity duration-200 ease-(--ease-out-strong) starting:opacity-0';\n\nfunction transitionOf(isInstant: boolean) {\n  if (isInstant) {\n    return INSTANT;\n  }\n  return MORPH;\n}\n\nfunction swapFadeOf(hasChanged: boolean) {\n  if (hasChanged) {\n    return SWAP_FADE;\n  }\n  return undefined;\n}\n\n/** False until the value changes for the first time. */\nfunction useHasChanged(value: string) {\n  const [firstValue] = useState(value);\n  const [hasChanged, setHasChanged] = useState(false);\n  const isFirstChange = value !== firstValue && !hasChanged;\n  if (isFirstChange) {\n    setHasChanged(true);\n  }\n  return hasChanged;\n}\n\ntype MorphPathProps = {\n  d: string;\n  /** True while the shape follows a hand: it is redrawn where the hand is, with no glide behind it. */\n  isInstant?: boolean;\n  className?: string;\n  style?: React.CSSProperties;\n  /** For a shape that is its own hit target. */\n  onPointerEnter?: () => void;\n};\n\n/**\n * A shape that glides to its new outline when the data changes, as long as both outlines have the\n * same number of points. Under reduced motion the new shape replaces the old one with a fade.\n */\nexport function MorphPath({\n  d,\n  isInstant = false,\n  className,\n  style,\n  onPointerEnter,\n}: MorphPathProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const hasChanged = useHasChanged(d);\n\n  if (shouldReduceMotion) {\n    return (\n      <path\n        key={d}\n        d={d}\n        vectorEffect='non-scaling-stroke'\n        className={cn(swapFadeOf(hasChanged), className)}\n        style={style}\n        onPointerEnter={onPointerEnter}\n      />\n    );\n  }\n\n  return (\n    <motion.path\n      initial={false}\n      animate={{ d }}\n      transition={transitionOf(isInstant)}\n      vectorEffect='non-scaling-stroke'\n      className={className}\n      style={style}\n      onPointerEnter={onPointerEnter}\n    />\n  );\n}\n\n/** The stroke of a line: 2px whatever the width of the plot, with round joins and ends. */\nexport const LINE_STROKE =\n  'fill-none stroke-2 [stroke-linecap:round] [stroke-linejoin:round]';\n",
      "type": "registry:component",
      "target": "components/chart/_parts/morph-path.tsx"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/path.ts",
      "content": "import { columnCenterOf, lerp, ratioOf, type Domain } from './scale';\n\nexport type Point = {\n  x: number;\n  y: number;\n};\n\n/** Paths are drawn in a box this wide and stretched to the plot, so a change of width never redraws them. */\nexport const VIEW_WIDTH = 1000;\n\nfunction commandOf(point: Point, index: number) {\n  const x = point.x.toFixed(1);\n  const y = point.y.toFixed(1);\n  if (index === 0) {\n    return `M${x} ${y}`;\n  }\n  return `L${x} ${y}`;\n}\n\nexport function linePathOf(points: readonly Point[]) {\n  const commands = points.map((point, index) => commandOf(point, index));\n  return commands.join(' ');\n}\n\n/** The line closed down (or up) to a level, for the wash under a line. */\nexport function areaPathOf(points: readonly Point[], levelY: number) {\n  if (points.length === 0) {\n    return '';\n  }\n  const line = linePathOf(points);\n  const lastIndex = points.length - 1;\n  const firstX = points[0].x.toFixed(1);\n  const lastX = points[lastIndex].x.toFixed(1);\n  const level = levelY.toFixed(1);\n  return `${line} L${lastX} ${level} L${firstX} ${level} Z`;\n}\n\n/** The surface between two lines that share their x positions, for a range around a line. */\nexport function bandPathOf(upper: readonly Point[], lower: readonly Point[]) {\n  if (upper.length === 0) {\n    return '';\n  }\n  const backwards = [...lower].reverse();\n  const outline = [...upper, ...backwards];\n  const line = linePathOf(outline);\n  return `${line} Z`;\n}\n\n/** The pixel height of a value in a plot: the top of the domain is 0, its bottom is the plot height. */\nexport function yOf(value: number, domain: Domain, height: number) {\n  const ratio = ratioOf(value, domain);\n  const fromBottom = ratio * height;\n  return height - fromBottom;\n}\n\n/** One point per value, each in the middle of its column. */\nexport function plotPointsOf(\n  values: readonly number[],\n  domain: Domain,\n  height: number\n): Point[] {\n  return values.map((value, index) => {\n    const share = columnCenterOf(index, values.length);\n    const x = share * VIEW_WIDTH;\n    const y = yOf(value, domain, height);\n    return { x, y };\n  });\n}\n\n/** How many of the pieces lie before a segment when they are shared out evenly. */\nfunction piecesBefore(\n  segment: number,\n  segmentCount: number,\n  pieceCount: number\n) {\n  const share = segment / segmentCount;\n  return Math.floor(share * pieceCount);\n}\n\n/**\n * The same line through exactly `count` points: each segment is cut into equal parts, so two lines\n * of different lengths share one structure and one can glide into the other.\n */\nexport function densifyOf(points: readonly Point[], count: number): Point[] {\n  const segmentCount = points.length - 1;\n  const hasSegments = segmentCount >= 1;\n  const hasRoom = count > points.length;\n  if (!hasSegments || !hasRoom) {\n    return [...points];\n  }\n  const pieceCount = count - 1;\n  const dense: Point[] = [points[0]];\n  for (let segment = 0; segment < segmentCount; segment += 1) {\n    const from = points[segment];\n    const to = points[segment + 1];\n    const start = piecesBefore(segment, segmentCount, pieceCount);\n    const end = piecesBefore(segment + 1, segmentCount, pieceCount);\n    const parts = end - start;\n    for (let part = 1; part <= parts; part += 1) {\n      const amount = part / parts;\n      const x = lerp(from.x, to.x, amount);\n      const y = lerp(from.y, to.y, amount);\n      dense.push({ x, y });\n    }\n  }\n  return dense;\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/path.ts"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/plot.tsx",
      "content": "import { cn } from '@/registry/ndeko/lib/utils';\n\nimport { CategoryAxis, GridLines, ValueAxis, type AxisLabel } from './axis';\nimport { VIEW_WIDTH } from './path';\nimport type { Scale } from './scale';\n\n/**\n * A plot is a query container, so the readout and the marks inside it are placed in shares of its\n * width, and it lets the page scroll vertically under a finger while a sideways move reads values.\n */\nexport const PLOT_SURFACE =\n  'focus-visible:ring-ring/25 @container relative touch-pan-y rounded-md outline-none focus-visible:ring-[3px]';\n\ntype PlotFrameProps = {\n  /** The name of the plot and how to read it, for screen readers. */\n  label: string;\n  scale: Scale;\n  height: number;\n  formatTick: (value: number) => string;\n  axisLabels: readonly AxisLabel[];\n  axisAlign?: 'spread' | 'center';\n  /** Receives the plot element, for a chart that measures the room it has. */\n  plotRef?: (element: HTMLDivElement | null) => void;\n  /** The handlers of the reading: the plot is the one tab stop of the chart. */\n  plotProps?: React.HTMLAttributes<HTMLDivElement>;\n  plotClassName?: string;\n  /** For a chart whose marks carry their own figures, which can drop the axis on a narrow piece. */\n  valueAxisClassName?: string;\n  /** Labels laid out by the chart itself, in place of one row of `axisLabels`. */\n  categoryAxis?: React.ReactNode;\n  className?: string;\n  children: React.ReactNode;\n};\n\n/**\n * A plot between its value axis on the left and its category axis underneath. Each part has its own\n * cell: placed in turn, a plot whose value axis is hidden would fall into the axis column, which is\n * only as wide as its content, and nothing in a plot has a width of its own, so every mark would\n * stack at the left edge.\n */\nexport function PlotFrame({\n  label,\n  scale,\n  height,\n  formatTick,\n  axisLabels,\n  axisAlign,\n  plotRef,\n  plotProps,\n  plotClassName,\n  valueAxisClassName,\n  categoryAxis,\n  className,\n  children,\n}: PlotFrameProps) {\n  return (\n    <div\n      className={cn('grid grid-cols-[auto_minmax(0,1fr)] gap-x-2', className)}\n    >\n      <ValueAxis\n        scale={scale}\n        height={height}\n        format={formatTick}\n        className={cn('col-start-1 row-start-1', valueAxisClassName)}\n      />\n      <div\n        ref={plotRef}\n        role='group'\n        tabIndex={0}\n        aria-label={label}\n        className={cn(PLOT_SURFACE, 'col-start-2 row-start-1', plotClassName)}\n        style={{ height }}\n        {...plotProps}\n      >\n        <GridLines scale={scale} height={height} />\n        {children}\n      </div>\n      <div className='col-start-2 row-start-2 min-w-0'>\n        {categoryAxis}\n        {!categoryAxis && (\n          <CategoryAxis\n            labels={axisLabels}\n            align={axisAlign}\n            className='mt-2'\n          />\n        )}\n      </div>\n    </div>\n  );\n}\n\ntype PathLayerProps = {\n  height: number;\n  className?: string;\n  children: React.ReactNode;\n};\n\n/**\n * The layer the paths are drawn in: `VIEW_WIDTH` units across whatever the width of the plot, and\n * real pixels down. Strokes keep their thickness because each path opts out of the stretch.\n */\nexport function PathLayer({ height, className, children }: PathLayerProps) {\n  return (\n    <svg\n      aria-hidden='true'\n      viewBox={`0 0 ${VIEW_WIDTH} ${height}`}\n      preserveAspectRatio='none'\n      className={cn(\n        'pointer-events-none absolute inset-0 size-full overflow-visible',\n        className\n      )}\n    >\n      {children}\n    </svg>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/plot.tsx"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/scale.ts",
      "content": "export type Domain = {\n  min: number;\n  max: number;\n};\n\nexport type Scale = Domain & {\n  step: number;\n  ticks: number[];\n};\n\nconst NICE_FACTORS = [1, 2, 5, 10];\n\nconst EMPTY_DOMAIN: Domain = { min: 0, max: 0 };\n\nexport function clamp(value: number, min: number, max: number) {\n  const atLeastMin = Math.max(value, min);\n  return Math.min(atLeastMin, max);\n}\n\nexport function lerp(from: number, to: number, amount: number) {\n  const span = to - from;\n  return from + span * amount;\n}\n\nexport function sumOf(values: readonly number[]) {\n  let total = 0;\n  for (const value of values) {\n    total += value;\n  }\n  return total;\n}\n\nexport function extentOf(values: readonly number[]): Domain {\n  if (values.length === 0) {\n    return EMPTY_DOMAIN;\n  }\n  let min = values[0];\n  let max = values[0];\n  for (const value of values) {\n    min = Math.min(min, value);\n    max = Math.max(max, value);\n  }\n  return { min, max };\n}\n\n/** Bars and areas are read from zero, so their domain always holds it. */\nexport function withZero(domain: Domain): Domain {\n  const min = Math.min(domain.min, 0);\n  const max = Math.max(domain.max, 0);\n  return { min, max };\n}\n\n/** Where a value sits in a domain, from 0 at its lowest to 1 at its highest. */\nexport function ratioOf(value: number, domain: Domain) {\n  const span = domain.max - domain.min;\n  if (span === 0) {\n    return 0;\n  }\n  const offset = value - domain.min;\n  return offset / span;\n}\n\n/** A flat series still needs room above and below it to be drawn. */\nfunction spanOf(domain: Domain) {\n  const span = domain.max - domain.min;\n  if (span > 0) {\n    return span;\n  }\n  const size = Math.abs(domain.max);\n  return Math.max(size, 1);\n}\n\nfunction niceStepOf(roughStep: number) {\n  const logarithm = Math.log10(roughStep);\n  const exponent = Math.floor(logarithm);\n  const magnitude = 10 ** exponent;\n  const factor = NICE_FACTORS.find((candidate) => {\n    const candidateStep = candidate * magnitude;\n    return candidateStep >= roughStep;\n  });\n  const safeFactor = factor ?? 10;\n  return safeFactor * magnitude;\n}\n\nfunction decimalsOf(step: number) {\n  const logarithm = Math.log10(step);\n  const exponent = Math.floor(logarithm);\n  return Math.max(0, -exponent);\n}\n\n/** Adding zero turns a negative zero into zero, which a number format would write as -0. */\nfunction roundedTo(value: number, decimals: number) {\n  const factor = 10 ** decimals;\n  const scaled = Math.round(value * factor);\n  const rounded = scaled / factor;\n  return rounded + 0;\n}\n\n/** A scale with round ticks that holds the whole domain, in at most `maxLines` steps. */\nexport function niceScaleOf(domain: Domain, maxLines: number): Scale {\n  const span = spanOf(domain);\n  const roughStep = span / maxLines;\n  const step = niceStepOf(roughStep);\n  const decimals = decimalsOf(step);\n  const stepsBelow = Math.floor(domain.min / step);\n  const lowest = stepsBelow * step;\n  const highestWanted = Math.max(domain.max, lowest + step);\n  const stepsAbove = Math.ceil(highestWanted / step);\n  const lineCount = stepsAbove - stepsBelow;\n  const tickCount = lineCount + 1;\n  const ticks = Array.from({ length: tickCount }, (_, index) => {\n    const tick = lowest + index * step;\n    return roundedTo(tick, decimals);\n  });\n  const lastIndex = ticks.length - 1;\n  return { min: ticks[0], max: ticks[lastIndex], step, ticks };\n}\n\n/** Columns share the plot equally and a mark sits in the middle of its column. */\nexport function columnCenterOf(index: number, count: number) {\n  const center = index + 0.5;\n  return center / count;\n}\n\nexport function columnIndexAt(ratio: number, count: number) {\n  const rawIndex = Math.floor(ratio * count);\n  const lastIndex = Math.max(count - 1, 0);\n  return clamp(rawIndex, 0, lastIndex);\n}\n\nexport function percentOf(share: number) {\n  const percent = share * 100;\n  return `${percent}%`;\n}\n\n/** The whole numbers that lead from one position to another: the start is left out, the end is kept. */\nexport function positionsTo(from: number, to: number) {\n  const gap = to - from;\n  const distance = Math.abs(gap);\n  const direction = Math.sign(gap);\n  return Array.from({ length: distance }, (_, index) => {\n    const travelled = index + 1;\n    const offset = travelled * direction;\n    return from + offset;\n  });\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/scale.ts"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/use-chart-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 chart demo shares: the demonstration, the box that keeps its tallest height so a round\n * never moves the page, and a stop when the keyboard brings focus in. A person who tabs to a plot\n * reads it with the arrow keys from there, and has pressed no key inside the piece yet.\n */\nexport function useChartDemo(\n  steps: readonly AutoplayStep[],\n  options?: AutoplayOptions\n) {\n  const demo = useAutoplay(steps, options);\n  const { ref, takeOver } = demo;\n\n  useKeptHeight(ref);\n\n  function stopOnKeyboardFocus(event: React.FocusEvent<HTMLElement>) {\n    const isKeyboardFocus = event.target.matches(':focus-visible');\n    if (isKeyboardFocus) {\n      takeOver();\n    }\n  }\n\n  return { ...demo, stopOnKeyboardFocus };\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/use-chart-demo.ts"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/use-reading.ts",
      "content": "'use client';\n\nimport { useState } from 'react';\n\nimport { clamp, columnIndexAt } from './scale';\n\ntype ReadingOptions = {\n  /** How many positions the plot has from left to right. */\n  count: number;\n  /** Where the reading opens the first time the plot takes keyboard focus. */\n  defaultIndex: number;\n  /** A position shown from outside while nobody reads the plot, for a demonstration. */\n  guideIndex?: number | null;\n  /** Enter, Space or a click on a position. */\n  onSelect?: (index: number) => void;\n};\n\nfunction columnIndexFrom(\n  event: React.PointerEvent<HTMLElement> | React.MouseEvent<HTMLElement>,\n  count: number\n) {\n  const box = event.currentTarget.getBoundingClientRect();\n  const offset = event.clientX - box.left;\n  const ratio = offset / box.width;\n  return columnIndexAt(ratio, count);\n}\n\nexport function steppedIndexOf(key: string, current: number, count: number) {\n  const lastIndex = Math.max(count - 1, 0);\n  if (key === 'ArrowRight') {\n    const next = current + 1;\n    return Math.min(next, lastIndex);\n  }\n  if (key === 'ArrowLeft') {\n    const previous = current - 1;\n    return Math.max(previous, 0);\n  }\n  if (key === 'Home') {\n    return 0;\n  }\n  if (key === 'End') {\n    return lastIndex;\n  }\n  return null;\n}\n\nexport function activeIndexOf(isActive: boolean, shownIndex: number) {\n  if (isActive) {\n    return shownIndex;\n  }\n  return null;\n}\n\n/** A reading is said aloud only while the arrow keys move it: a pointer and a demonstration stay silent. */\nexport function readingAloud(isReadingByKeys: boolean, reading: string) {\n  if (isReadingByKeys) {\n    return reading;\n  }\n  return '';\n}\n\nfunction isSelectKey(key: string) {\n  const isEnter = key === 'Enter';\n  const isSpace = key === ' ';\n  return isEnter || isSpace;\n}\n\n/**\n * One reading position for a plot that is one tab stop. The pointer wins while it is over the plot,\n * then the arrow keys, then the position a demonstration points at. A reading that opens appears in\n * place; one that moves glides, which `isGliding` tells the readout.\n *\n * A plot read by columns spreads `handlers`. A plot whose marks are their own hit targets spreads\n * `markHandlers` and calls `pointTo` from each mark.\n */\nexport function useReading({\n  count,\n  defaultIndex,\n  guideIndex = null,\n  onSelect,\n}: ReadingOptions) {\n  const [pointerIndex, setPointerIndex] = useState<number | null>(null);\n  const [keyIndex, setKeyIndex] = useState<number | null>(null);\n  const [lastIndex, setLastIndex] = useState(defaultIndex);\n  const [isGliding, setIsGliding] = useState(false);\n  const [seenGuide, setSeenGuide] = useState(guideIndex);\n  const hasNewGuide = seenGuide !== guideIndex;\n\n  if (hasNewGuide) {\n    const wasGuided = seenGuide !== null;\n    const isGuided = guideIndex !== null;\n    setSeenGuide(guideIndex);\n    setIsGliding(wasGuided && isGuided);\n    if (guideIndex !== null) {\n      setLastIndex(guideIndex);\n    }\n  }\n\n  const activeIndex = pointerIndex ?? keyIndex ?? guideIndex;\n  const isActive = activeIndex !== null;\n  const isPointing = pointerIndex !== null;\n  const isReadingByKeys = keyIndex !== null;\n  const wantedIndex = activeIndex ?? lastIndex;\n  const highestIndex = Math.max(count - 1, 0);\n  const shownIndex = clamp(wantedIndex, 0, highestIndex);\n\n  function pointAt(event: React.PointerEvent<HTMLElement>) {\n    const index = columnIndexFrom(event, count);\n    setIsGliding(isPointing);\n    setPointerIndex(index);\n    setLastIndex(index);\n  }\n\n  /** Null when the pointer is over the plot and on no mark. */\n  function pointTo(index: number | null) {\n    if (index === null) {\n      setPointerIndex(null);\n      return;\n    }\n    setIsGliding(isPointing);\n    setPointerIndex(index);\n    setLastIndex(index);\n  }\n\n  function leave(event: React.PointerEvent<HTMLElement>) {\n    if (event.pointerType === 'mouse') {\n      setPointerIndex(null);\n    }\n  }\n\n  function focus(event: React.FocusEvent<HTMLElement>) {\n    const isKeyboardFocus = event.currentTarget.matches(':focus-visible');\n    if (isKeyboardFocus) {\n      setIsGliding(false);\n      setKeyIndex(shownIndex);\n    }\n  }\n\n  function blur() {\n    setKeyIndex(null);\n    setPointerIndex(null);\n  }\n\n  function pressKey(event: React.KeyboardEvent<HTMLElement>) {\n    if (event.key === 'Escape') {\n      setKeyIndex(null);\n      return;\n    }\n    if (isSelectKey(event.key)) {\n      if (onSelect) {\n        event.preventDefault();\n        setKeyIndex(shownIndex);\n        onSelect(shownIndex);\n      }\n      return;\n    }\n    const next = steppedIndexOf(event.key, shownIndex, count);\n    if (next === null) {\n      return;\n    }\n    event.preventDefault();\n    setIsGliding(isActive);\n    setPointerIndex(null);\n    setKeyIndex(next);\n    setLastIndex(next);\n  }\n\n  function click(event: React.MouseEvent<HTMLElement>) {\n    if (!onSelect) {\n      return;\n    }\n    const index = columnIndexFrom(event, count);\n    onSelect(index);\n  }\n\n  const handlers = {\n    onPointerMove: pointAt,\n    onPointerDown: pointAt,\n    onPointerLeave: leave,\n    onFocus: focus,\n    onBlur: blur,\n    onKeyDown: pressKey,\n    onClick: click,\n  };\n\n  const markHandlers = {\n    onPointerLeave: leave,\n    onFocus: focus,\n    onBlur: blur,\n    onKeyDown: pressKey,\n  };\n\n  return {\n    shownIndex,\n    isActive,\n    isGliding,\n    isPointing,\n    isReadingByKeys,\n    handlers,\n    markHandlers,\n    pointTo,\n  };\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/use-reading.ts"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/use-word-stream.ts",
      "content": "'use client';\n\nimport { useState } from 'react';\n\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\n\nexport type StreamStatus = 'idle' | 'thinking' | 'streaming' | 'done';\n\nexport type WordStream = {\n  status: StreamStatus;\n  words: readonly string[];\n  /** How many of the words have arrived. */\n  shown: number;\n};\n\ntype StreamTiming = {\n  /** Milliseconds before the first word. */\n  thinkMs?: number;\n  /** Milliseconds between two words. */\n  wordMs?: number;\n};\n\nconst IDLE: WordStream = { status: 'idle', words: [], shown: 0 };\n\nexport function wordsOf(text: string) {\n  const trimmed = text.trim();\n  if (trimmed === '') {\n    return [];\n  }\n  return trimmed.split(/\\s+/);\n}\n\n/** A text that is already there, with nothing left to arrive. */\nexport function arrivedStreamOf(text: string): WordStream {\n  const words = wordsOf(text);\n  return { status: 'done', words, shown: words.length };\n}\n\nexport function textOf(stream: WordStream) {\n  return stream.words.join(' ');\n}\n\n/** What a screen reader hears: the whole text once it has arrived, never each word on its way. */\nexport function spokenStreamOf(stream: WordStream) {\n  if (stream.status === 'done') {\n    return textOf(stream);\n  }\n  return '';\n}\n\nfunction withShown(shown: number) {\n  return function reveal(current: WordStream): WordStream {\n    return { ...current, shown };\n  };\n}\n\nfunction withStatus(status: StreamStatus) {\n  return function advance(current: WordStream): WordStream {\n    return { ...current, status };\n  };\n}\n\n/**\n * A text that arrives the way a model writes it: a moment of thought, then word after word. A real\n * product replaces it with its own stream and keeps the same `WordStream` shape.\n */\nexport function useWordStream(initial: WordStream = IDLE) {\n  const [stream, setStream] = useState(initial);\n  const { schedule, clearAll } = useTimeouts();\n\n  function start(\n    text: string,\n    { thinkMs = 900, wordMs = 55 }: StreamTiming = {}\n  ) {\n    clearAll();\n    const words = wordsOf(text);\n    setStream({ status: 'thinking', words, shown: 0 });\n    schedule(() => setStream(withStatus('streaming')), thinkMs);\n    for (let shown = 1; shown <= words.length; shown += 1) {\n      const elapsed = shown * wordMs;\n      schedule(() => setStream(withShown(shown)), thinkMs + elapsed);\n    }\n    const streamMs = words.length * wordMs;\n    const lastWordAt = thinkMs + streamMs;\n    const settleMs = wordMs * 2;\n    schedule(() => setStream(withStatus('done')), lastWordAt + settleMs);\n  }\n\n  function show(next: WordStream) {\n    clearAll();\n    setStream(next);\n  }\n\n  return { stream, start, show };\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/use-word-stream.ts"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/wrapping-roll.tsx",
      "content": "'use client';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport { wordsOf } from './use-word-stream';\n\ntype WrappingRollProps = {\n  text: string;\n  /** The words roll up when it grows and down when it falls. */\n  value?: number;\n  className?: string;\n};\n\n/**\n * A sentence that rolls and still wraps on a narrow piece. A `WordRoll` keeps all it holds on one\n * line, so each word gets its own and the line breaks between them.\n */\nexport function WrappingRoll({ text, value, className }: WrappingRollProps) {\n  const words = wordsOf(text);\n\n  return (\n    <span className={cn('block', className)}>\n      <span className='sr-only'>{text}</span>\n      <span aria-hidden='true' className='flex flex-wrap gap-x-[0.25em]'>\n        {words.map((word, index) => (\n          <WordRoll key={index} text={word} value={value} />\n        ))}\n      </span>\n    </span>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/wrapping-roll.tsx"
    }
  ],
  "categories": [
    "components",
    "chart"
  ],
  "type": "registry:component"
}