{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-14",
  "title": "Bridge",
  "description": "A waterfall from last month to this month that you pour by dragging across it or with the arrow keys: each floating bar fills as the pour reaches it and the running total rolls step by step.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/chart/chart-14.tsx",
      "content": "'use client';\n\nimport {\n  animate,\n  motion,\n  useMotionValue,\n  useMotionValueEvent,\n  useTransform,\n  type MotionValue,\n} from 'motion/react';\nimport { useEffect, useImperativeHandle, useRef, 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 { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { hold } from '@/registry/ndeko/lib/demonstration';\nimport { EASE_OUT_STRONG } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\n\nimport { CategoryAxis, type AxisLabel } from './_parts/axis';\nimport { ChartCard } from './_parts/chart-card';\nimport { DataTable, type DataRow } from './_parts/data-table';\nimport { formatUsd } from './_parts/format';\nimport { yOf } from './_parts/path';\nimport { PlotFrame } from './_parts/plot';\nimport {\n  clamp,\n  columnCenterOf,\n  extentOf,\n  niceScaleOf,\n  percentOf,\n  type Scale,\n} from './_parts/scale';\nimport { useChartDemo } from './_parts/use-chart-demo';\n\ntype ValueFormat = (value: number) => string;\n\nexport type BridgeStep = {\n  id: string;\n  name: string;\n  /** What the step adds to the total, or takes from it when below zero. */\n  change: number;\n};\n\nexport type BridgeHandle = {\n  /** Empties the chart and pours the total across it again. */\n  pour: () => void;\n};\n\nexport type BridgeProps = {\n  title: string;\n  /** A short mark beside the title, such as \"Illustrative\" over sample data. */\n  note?: string;\n  /** Where the total starts, and what the first and the last column are called. */\n  startValue: number;\n  startLabel: string;\n  endLabel: string;\n  steps: readonly BridgeStep[];\n  formatValue?: ValueFormat;\n  /** The same format as options, for the total that rolls. */\n  numberFormat?: Intl.NumberFormatOptions;\n  /** Pour the total again from outside, for a demonstration. */\n  handleRef?: React.Ref<BridgeHandle>;\n  className?: string;\n};\n\ntype Column = {\n  id: string;\n  name: string;\n  /** The total before and after the column. The first and the last column do not move it. */\n  before: number;\n  after: number;\n  change: number;\n  isLevel: boolean;\n};\n\nconst PLOT_HEIGHT = 176;\n\nconst MAX_LINES = 5;\n\n/** A bar fills while the pour crosses this share of its column, then stays full. */\nconst FILL_SPAN = 0.85;\n\n/** How long the pour takes to cross one column when it is replayed, in seconds. */\nconst SECONDS_PER_COLUMN = 0.5;\n\nconst STEP_SECONDS = 0.35;\n\nconst USD_ROLL_FORMAT: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  notation: 'compact',\n  minimumFractionDigits: 1,\n  maximumFractionDigits: 1,\n};\n\nfunction columnsOf(\n  startValue: number,\n  startLabel: string,\n  endLabel: string,\n  steps: readonly BridgeStep[]\n) {\n  const first: Column = {\n    id: 'start',\n    name: startLabel,\n    before: startValue,\n    after: startValue,\n    change: 0,\n    isLevel: true,\n  };\n  const columns = [first];\n  let total = startValue;\n  for (const step of steps) {\n    const before = total;\n    total += step.change;\n    columns.push({\n      id: step.id,\n      name: step.name,\n      before,\n      after: total,\n      change: step.change,\n      isLevel: false,\n    });\n  }\n  columns.push({\n    id: 'end',\n    name: endLabel,\n    before: total,\n    after: total,\n    change: 0,\n    isLevel: true,\n  });\n  return columns;\n}\n\nfunction scaleOf(columns: readonly Column[]) {\n  const totals = columns.flatMap((column) => [column.before, column.after]);\n  const extent = extentOf(totals);\n  return niceScaleOf(extent, MAX_LINES);\n}\n\n/** How many columns the pour has crossed completely. */\nfunction crossedCountOf(pour: number, columnCount: number) {\n  const crossed = Math.floor(pour * columnCount + 0.0001);\n  return clamp(crossed, 0, columnCount);\n}\n\n/** The total once the pour has crossed that many columns. */\nfunction totalAfter(columns: readonly Column[], crossedCount: number) {\n  const lastCrossed = Math.max(crossedCount - 1, 0);\n  const column = columns[lastCrossed];\n  return column?.after ?? 0;\n}\n\nfunction standingOf(\n  columns: readonly Column[],\n  crossedCount: number,\n  startLabel: string\n) {\n  const lastIndex = columns.length - 1;\n  const lastCrossed = crossedCount - 1;\n  const column = columns[lastCrossed];\n  const isAtStart = lastCrossed <= 0 || column === undefined;\n  if (isAtStart) {\n    return startLabel;\n  }\n  if (lastCrossed === lastIndex) {\n    return column.name;\n  }\n  return `after ${column.name.toLowerCase()}`;\n}\n\n/**\n * Every phrase the standing can read. Given to the roll, its line keeps the widest one, so the\n * words change on each step without its width being animated frame by frame.\n */\nfunction standingsOf(columns: readonly Column[], startLabel: string) {\n  const standings: string[] = [];\n  for (let crossed = 0; crossed <= columns.length; crossed += 1) {\n    const standing = standingOf(columns, crossed, startLabel);\n    standings.push(standing);\n  }\n  return standings;\n}\n\n/** The shares of the plot the pour has crossed when the fill of a bar starts, and when it is full. */\nfunction fillRangeOf(index: number, columnCount: number) {\n  const start = index / columnCount;\n  const span = FILL_SPAN / columnCount;\n  const end = start + span;\n  return [start, end];\n}\n\n/** Where the fill waits before the pour reaches its bar: under a gain, above a loss. */\nfunction emptyOffsetOf(isGain: boolean) {\n  if (isGain) {\n    return '100%';\n  }\n  return '-100%';\n}\n\ntype BarFillProps = {\n  pour: MotionValue<number>;\n  index: number;\n  columnCount: number;\n  isGain: boolean;\n};\n\n/**\n * The fill follows the pour through a motion value written to this element alone. A value set on\n * the plot and inherited by every mark restyled the whole plot on each frame. At rest the pour is\n * whole and the bar full, which is the picture before any script runs.\n */\nfunction BarFill({ pour, index, columnCount, isGain }: BarFillProps) {\n  const range = fillRangeOf(index, columnCount);\n  const empty = emptyOffsetOf(isGain);\n  const offset = useTransform(pour, range, [empty, '0%']);\n\n  return (\n    <motion.span\n      className={cn(\n        'absolute inset-0',\n        isGain && 'bg-primary rounded-t-[4px]',\n        !isGain && 'bg-destructive rounded-b-[4px]'\n      )}\n      style={{ y: offset }}\n    />\n  );\n}\n\nfunction cursorTransformOf(pour: number) {\n  const percent = pour * 100;\n  return `translateX(${percent}cqw)`;\n}\n\nfunction shownUnless(isHidden: boolean) {\n  if (isHidden) {\n    return 'opacity-0';\n  }\n  return undefined;\n}\n\nfunction changeTextOf(change: number, format: ValueFormat) {\n  const amount = Math.abs(change);\n  const size = format(amount);\n  if (change < 0) {\n    return `-${size}`;\n  }\n  return `+${size}`;\n}\n\ntype BridgeColumnProps = {\n  column: Column;\n  index: number;\n  columnCount: number;\n  scale: Scale;\n  pour: MotionValue<number>;\n  /** True once the pour has gone past the column: its figure and the line to the next column show. */\n  isCrossed: boolean;\n  format: ValueFormat;\n};\n\n/** The room above a level for its figure, and above a bar for its change. */\nconst LEVEL_LABEL_LIFT = 22;\n\nconst BAR_LABEL_LIFT = 18;\n\nconst BAR_LABEL_DROP = 4;\n\n/** A level is a mark at the height of the total. A step is a bar that floats from the total before it to the total after it. */\nfunction BridgeColumn({\n  column,\n  index,\n  columnCount,\n  scale,\n  pour,\n  isCrossed,\n  format,\n}: BridgeColumnProps) {\n  const centre = columnCenterOf(index, columnCount);\n  const left = percentOf(centre);\n  const beforeY = yOf(column.before, scale, PLOT_HEIGHT);\n  const afterY = yOf(column.after, scale, PLOT_HEIGHT);\n  const top = Math.min(beforeY, afterY);\n  const height = Math.abs(afterY - beforeY);\n  const isGain = column.change >= 0;\n  const isLast = index === columnCount - 1;\n  const hidden = shownUnless(!isCrossed);\n  const columnWidth = 100 / columnCount;\n  const link = (\n    <span\n      className={cn(\n        'hairline-t border-foreground/25 absolute left-0 transition-opacity duration-200',\n        hidden,\n        isLast && 'hidden'\n      )}\n      style={{ top: afterY, width: `${columnWidth}cqw` }}\n    />\n  );\n\n  if (column.isLevel) {\n    return (\n      <div className='absolute inset-y-0 w-0' style={{ left }}>\n        {link}\n        <span\n          className={cn(\n            'bg-foreground absolute left-0 h-1 w-8 -translate-1/2 rounded-full transition-opacity duration-200',\n            hidden\n          )}\n          style={{ top: afterY }}\n        />\n        <span\n          className={cn(\n            'absolute left-0 -translate-x-1/2 text-[11px] font-medium whitespace-nowrap tabular-nums transition-opacity duration-200',\n            hidden\n          )}\n          style={{ top: afterY - LEVEL_LABEL_LIFT }}\n        >\n          {format(column.after)}\n        </span>\n      </div>\n    );\n  }\n\n  return (\n    <div className='absolute inset-y-0 w-0' style={{ left }}>\n      {link}\n      <span\n        className='absolute left-0 w-6 -translate-x-1/2 overflow-hidden'\n        style={{ top, height }}\n      >\n        <BarFill\n          pour={pour}\n          index={index}\n          columnCount={columnCount}\n          isGain={isGain}\n        />\n      </span>\n      <span\n        className={cn(\n          'text-muted-foreground absolute left-0 -translate-x-1/2 text-[11px] whitespace-nowrap tabular-nums transition-opacity duration-200',\n          hidden\n        )}\n        style={{ top: labelTopOf(top, height, isGain) }}\n      >\n        {changeTextOf(column.change, format)}\n      </span>\n    </div>\n  );\n}\n\nfunction isEvenIndex(index: number) {\n  return index % 2 === 0;\n}\n\ntype StepAxisProps = {\n  labels: readonly AxisLabel[];\n};\n\n/**\n * The names under the bars. On a piece too narrow for them side by side, every other name drops to\n * a second row, so each one has the room of two columns; the hidden table keeps them all in order.\n */\nfunction StepAxis({ labels }: StepAxisProps) {\n  const upper = labels.filter((_, index) => isEvenIndex(index));\n  const lower = labels.filter((_, index) => !isEvenIndex(index));\n\n  return (\n    <div className='mt-2'>\n      <CategoryAxis\n        labels={labels}\n        align='center'\n        className='hidden @lg:block'\n      />\n      <div className='flex flex-col gap-0.5 @lg:hidden'>\n        <CategoryAxis labels={upper} align='center' />\n        <CategoryAxis labels={lower} align='center' />\n      </div>\n    </div>\n  );\n}\n\n/** A gain is labelled above its bar and a loss under it: on the side the bar points to. */\nfunction labelTopOf(top: number, height: number, isGain: boolean) {\n  if (isGain) {\n    return top - BAR_LABEL_LIFT;\n  }\n  const bottom = top + height;\n  return bottom + BAR_LABEL_DROP;\n}\n\nexport function Bridge({\n  title,\n  note,\n  startValue,\n  startLabel,\n  endLabel,\n  steps,\n  formatValue = formatUsd,\n  numberFormat = USD_ROLL_FORMAT,\n  handleRef,\n  className,\n}: BridgeProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const columns = columnsOf(startValue, startLabel, endLabel, steps);\n  const columnCount = columns.length;\n  const scale = scaleOf(columns);\n  const pour = useMotionValue(1);\n  const cursorTransform = useTransform(pour, cursorTransformOf);\n  const pouring = useRef<ReturnType<typeof animate> | null>(null);\n  const isDragging = useRef(false);\n  const [crossedCount, setCrossedCount] = useState(columnCount);\n  const total = totalAfter(columns, crossedCount);\n  const standing = standingOf(columns, crossedCount, startLabel);\n  const standings = standingsOf(columns, startLabel);\n  const isPoured = crossedCount === columnCount;\n  const endTotal = columns.at(-1)?.after ?? startValue;\n  const startText = formatValue(startValue);\n  const endText = formatValue(endTotal);\n  const totalText = formatValue(total);\n  const summary = `${startLabel} ${startText}, ${endLabel} ${endText}, through ${steps.length} steps.`;\n\n  useMotionValueEvent(pour, 'change', (latest) => {\n    setCrossedCount(crossedCountOf(latest, columnCount));\n  });\n\n  useEffect(() => {\n    return () => pouring.current?.stop();\n  }, []);\n\n  function stopPouring() {\n    pouring.current?.stop();\n    pouring.current = null;\n  }\n\n  function pourTo(target: number, seconds: number) {\n    stopPouring();\n    if (shouldReduceMotion) {\n      pour.set(target);\n      return;\n    }\n    pouring.current = animate(pour, target, {\n      duration: seconds,\n      ease: EASE_OUT_STRONG,\n    });\n  }\n\n  function pourAgain() {\n    stopPouring();\n    if (shouldReduceMotion) {\n      pour.set(1);\n      return;\n    }\n    pour.set(0);\n    pouring.current = animate(pour, 1, {\n      duration: columnCount * SECONDS_PER_COLUMN,\n      ease: 'linear',\n    });\n  }\n\n  useImperativeHandle(handleRef, () => ({ pour: pourAgain }));\n\n  function pourAt(event: React.PointerEvent<HTMLElement>) {\n    const box = event.currentTarget.getBoundingClientRect();\n    const offset = event.clientX - box.left;\n    const share = offset / box.width;\n    pour.set(clamp(share, 0, 1));\n  }\n\n  function startDrag(event: React.PointerEvent<HTMLElement>) {\n    if (event.button !== 0) {\n      return;\n    }\n    stopPouring();\n    event.currentTarget.setPointerCapture(event.pointerId);\n    isDragging.current = true;\n    pourAt(event);\n  }\n\n  function drag(event: React.PointerEvent<HTMLElement>) {\n    if (isDragging.current) {\n      pourAt(event);\n    }\n  }\n\n  function endDrag() {\n    isDragging.current = false;\n  }\n\n  function pressKey(event: React.KeyboardEvent<HTMLElement>) {\n    const target = keyTargetOf(event.key, crossedCount, columnCount);\n    if (target === null) {\n      return;\n    }\n    event.preventDefault();\n    pourTo(target / columnCount, STEP_SECONDS);\n  }\n\n  const axisLabels: AxisLabel[] = columns.map((column, index) => ({\n    id: column.id,\n    text: column.name,\n    ratio: columnCenterOf(index, columnCount),\n    isStrong: column.isLevel,\n  }));\n\n  const rows: DataRow[] = columns.map((column) => ({\n    id: column.id,\n    label: column.name,\n    cells: [cellChangeOf(column, formatValue), formatValue(column.after)],\n  }));\n\n  return (\n    <ChartCard\n      title={title}\n      note={note}\n      summary={summary}\n      className={className}\n      actions={<ReplayButton isShown onReplay={pourAgain} label='Pour again' />}\n    >\n      <div className='flex flex-col gap-0.5'>\n        <MotionNumber\n          value={total}\n          format={numberFormat}\n          className='text-2xl leading-8 font-semibold'\n        />\n        <p className='text-muted-foreground text-xs'>\n          <WordRoll text={standing} labels={standings} value={crossedCount} />\n        </p>\n      </div>\n      <PlotFrame\n        label={title}\n        scale={scale}\n        height={PLOT_HEIGHT}\n        formatTick={formatValue}\n        axisLabels={axisLabels}\n        categoryAxis={<StepAxis labels={axisLabels} />}\n        valueAxisClassName='hidden @xs:block'\n        className='gap-x-0 @xs:gap-x-2'\n        plotClassName='cursor-ew-resize touch-pan-y select-none'\n        plotProps={{\n          role: 'slider',\n          'aria-label': `${title}. Pour the total across the steps with the arrow keys.`,\n          'aria-orientation': 'horizontal',\n          'aria-valuemin': 0,\n          'aria-valuemax': columnCount,\n          'aria-valuenow': crossedCount,\n          'aria-valuetext': `${totalText}, ${standing}`,\n          onPointerDown: startDrag,\n          onPointerMove: drag,\n          onPointerUp: endDrag,\n          onPointerCancel: endDrag,\n          onKeyDown: pressKey,\n        }}\n      >\n        <div\n          aria-hidden='true'\n          className='pointer-events-none absolute inset-0'\n        >\n          {columns.map((column, index) => (\n            <BridgeColumn\n              key={column.id}\n              column={column}\n              index={index}\n              columnCount={columnCount}\n              scale={scale}\n              pour={pour}\n              isCrossed={isCrossedAt(index, crossedCount)}\n              format={formatValue}\n            />\n          ))}\n          <motion.span\n            className={cn(\n              'bg-foreground/25 absolute inset-y-0 left-0 w-px transition-opacity duration-200',\n              shownUnless(isPoured)\n            )}\n            style={{ transform: cursorTransform }}\n          />\n        </div>\n      </PlotFrame>\n      <p className='text-muted-foreground text-xs'>\n        Drag across the steps, or use the arrow keys, to pour the total\n      </p>\n      <DataTable\n        caption={title}\n        columns={['Step', 'Change', 'Total after it']}\n        rows={rows}\n      />\n    </ChartCard>\n  );\n}\n\n/** The first column is where the pour starts from: its level is there before anything is poured. */\nfunction isCrossedAt(index: number, crossedCount: number) {\n  const isStart = index === 0;\n  return isStart || index < crossedCount;\n}\n\nfunction cellChangeOf(column: Column, format: ValueFormat) {\n  if (column.isLevel) {\n    return '';\n  }\n  return changeTextOf(column.change, format);\n}\n\n/** How many columns to have crossed after a key: one more, one fewer, none or all of them. */\nfunction keyTargetOf(key: string, crossedCount: number, columnCount: number) {\n  const isForward = key === 'ArrowRight' || key === 'ArrowUp';\n  const isBackward = key === 'ArrowLeft' || key === 'ArrowDown';\n  if (isForward) {\n    return Math.min(crossedCount + 1, columnCount);\n  }\n  if (isBackward) {\n    return Math.max(crossedCount - 1, 0);\n  }\n  if (key === 'Home') {\n    return 0;\n  }\n  if (key === 'End') {\n    return columnCount;\n  }\n  return null;\n}\n\nconst MRR_STEPS: BridgeStep[] = [\n  { id: 'new', name: 'New', change: 6400 },\n  { id: 'expansion', name: 'Expansion', change: 3100 },\n  { id: 'contraction', name: 'Contraction', change: -1800 },\n  { id: 'churn', name: 'Churn', change: -2600 },\n];\n\nconst MRR_LAST_MONTH = 48_200;\n\n/** The pour crosses six columns: the round waits for it, then leaves the full chart to be read. */\nconst POUR_MS = 6 * SECONDS_PER_COLUMN * 1000;\n\nconst READ_AFTER_MS = POUR_MS + 2600;\n\nexport default function Chart14() {\n  const handle = useRef<BridgeHandle>(null);\n\n  const steps: AutoplayStep[] = [\n    { after: 1800, run: () => handle.current?.pour() },\n    { after: READ_AFTER_MS, run: hold },\n  ];\n  const { ref, stopOnKeyboardFocus } = useChartDemo(steps, {\n    loopAfter: 1200,\n  });\n\n  return (\n    <div\n      ref={ref}\n      onFocus={stopOnKeyboardFocus}\n      className='flex min-h-[23rem] w-full max-w-[34rem]'\n    >\n      <Bridge\n        title='Monthly recurring revenue'\n        note='Illustrative'\n        startValue={MRR_LAST_MONTH}\n        startLabel='Last month'\n        endLabel='This month'\n        steps={MRR_STEPS}\n        handleRef={handle}\n        className='w-full'\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/chart/chart-14.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/data-table.tsx",
      "content": "export type DataRow = {\n  id: string;\n  /** The heading of the row: a day, a category, a step. */\n  label: string;\n  cells: readonly string[];\n};\n\ntype DataTableProps = {\n  caption: string;\n  /** The heading of the label column first, then one per cell. */\n  columns: readonly string[];\n  rows: readonly DataRow[];\n};\n\n/**\n * The numbers a chart draws, as a table for screen readers. It is taken out of the flow, so the\n * piece it sits in has to be positioned: a hidden box inside an area that scrolls sideways widens\n * the page otherwise.\n */\nexport function DataTable({ caption, columns, rows }: DataTableProps) {\n  return (\n    <table className='sr-only'>\n      <caption>{caption}</caption>\n      <thead>\n        <tr>\n          {columns.map((column) => (\n            <th key={column} scope='col'>\n              {column}\n            </th>\n          ))}\n        </tr>\n      </thead>\n      <tbody>\n        {rows.map((row) => (\n          <tr key={row.id}>\n            <th scope='row'>{row.label}</th>\n            {row.cells.map((cell, index) => (\n              <td key={index}>{cell}</td>\n            ))}\n          </tr>\n        ))}\n      </tbody>\n    </table>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/data-table.tsx"
    },
    {
      "path": "registry/ndeko/components/chart/_parts/format.ts",
      "content": "const LOCALE = 'en-US';\n\nexport const COUNT_FORMAT: Intl.NumberFormatOptions = {\n  maximumFractionDigits: 0,\n};\n\nexport const SIGNED_FORMAT: Intl.NumberFormatOptions = {\n  maximumFractionDigits: 0,\n  signDisplay: 'exceptZero',\n};\n\nexport const USD_COMPACT_FORMAT: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  notation: 'compact',\n  maximumFractionDigits: 1,\n};\n\nconst COMPACT_FORMAT: Intl.NumberFormatOptions = {\n  notation: 'compact',\n  maximumFractionDigits: 1,\n};\n\nconst COUNT = new Intl.NumberFormat(LOCALE, COUNT_FORMAT);\n\nconst SIGNED = new Intl.NumberFormat(LOCALE, SIGNED_FORMAT);\n\nconst COMPACT = new Intl.NumberFormat(LOCALE, COMPACT_FORMAT);\n\nconst USD_COMPACT = new Intl.NumberFormat(LOCALE, USD_COMPACT_FORMAT);\n\nconst DAY = new Intl.DateTimeFormat(LOCALE, {\n  month: 'short',\n  day: 'numeric',\n  timeZone: 'UTC',\n});\n\nconst MS_PER_DAY = 86_400_000;\n\nexport function formatCount(value: number) {\n  return COUNT.format(value);\n}\n\nexport function formatSigned(value: number) {\n  return SIGNED.format(value);\n}\n\nexport function formatCompact(value: number) {\n  return COMPACT.format(value);\n}\n\nexport function formatUsd(value: number) {\n  return USD_COMPACT.format(value);\n}\n\nexport function formatShare(share: number) {\n  const percent = Math.round(share * 100);\n  return `${percent}%`;\n}\n\n/** A start at zero has no percentage to grow from: it reads as no change. */\nexport function percentChangeOf(current: number, previous: number) {\n  if (previous === 0) {\n    return 0;\n  }\n  const difference = current - previous;\n  const ratio = difference / Math.abs(previous);\n  return Math.round(ratio * 100);\n}\n\nexport function changeWordsOf(percent: number, reference: string) {\n  if (percent === 0) {\n    return `level with ${reference}`;\n  }\n  const size = Math.abs(percent);\n  if (percent > 0) {\n    return `up ${size}% on ${reference}`;\n  }\n  return `down ${size}% on ${reference}`;\n}\n\nexport function nounOf(count: number, singular: string, plural: string) {\n  if (count === 1) {\n    return singular;\n  }\n  return plural;\n}\n\n/**\n * One label per day, or per `everyDays` days for a weekly series. Days are counted in UTC so the\n * server and the browser write the same label.\n */\nexport function dayLabelsOf(firstDay: string, count: number, everyDays = 1) {\n  const start = Date.parse(`${firstDay}T00:00:00Z`);\n  const stride = everyDays * MS_PER_DAY;\n  return Array.from({ length: count }, (_, index) => {\n    const elapsed = index * stride;\n    return DAY.format(start + elapsed);\n  });\n}\n",
      "type": "registry:component",
      "target": "components/chart/_parts/format.ts"
    },
    {
      "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"
    }
  ],
  "categories": [
    "components",
    "chart"
  ],
  "type": "registry:component"
}