{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-core",
  "title": "Chart core",
  "description": "What every family of charts shares beside the chart root (how a chart loads, plays its entrance and keeps what leaves, picking, `activeIndex`, its parts, its axes and its words), and the families on it. The cartesian family: the stops along x and the ones leaving, the frame the cartesian model fits, what its parts declare, and the reader that tells the root how the pointer and the keys reach the stops, every series at once, one at a time, or points placed by both values. The family of charts whose stops are a list, such as a donut’s slices, with its reader. The readers of the tree, flow and grid families, for the Treemap, the Sankey and the Heatmap.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/chart-frame.json",
    "https://kinoui.com/r/chart-live.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/chart-root.json",
    "https://kinoui.com/r/controllable.json",
    "https://kinoui.com/r/dates.json",
    "https://kinoui.com/r/spinner.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/chart-base.tsx",
      "content": "'use client'\n\nimport { useSpinner } from '@/registry/components/kino/spinner'\nimport type { ChartLive } from '@/registry/lib/chart-live-clock'\nimport {\n  type ChartConfig,\n  type ChartDatum,\n  type ChartMark,\n  type ChartOrientation,\n  numberOf,\n  rangeOf,\n  type ReadingDirection,\n  type XYValue,\n} from '@/registry/lib/chart-math'\nimport {\n  ChangeText,\n  type ChartFocusProps,\n  type ChartFormat,\n  type ChartItem,\n  type ChartMessages,\n  type ChartMoves,\n  type ChartRootState,\n  forcedSeriesColor,\n  percent,\n  SeriesKey,\n  swatchClassName,\n  swatchStyle,\n  tooltipQuietClassName,\n  useBefore,\n  useChartFocus,\n  useChartGroup,\n  useChartMoves,\n  useChartRootValue,\n  useLeaving,\n} from '@/registry/lib/chart-root'\nimport {\n  type Band,\n  type ChartScale,\n  type DomainEnd,\n  type LinearScale,\n  scaleSignature,\n  type TimeScale,\n} from '@/registry/lib/chart-scale'\nimport {\n  chartStatus,\n  type ChartStatus,\n  type ChartTable,\n  type ChartTarget,\n  indexOfKey,\n  targetKey,\n} from '@/registry/lib/chart-state'\nimport { useControllable } from '@/registry/lib/controllable'\nimport {\n  Children,\n  type ComponentProps,\n  createContext,\n  type CSSProperties,\n  Fragment,\n  isValidElement,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n  use,\n  useCallback,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * What every family of charts shares beside the root (`chart-root`): the\n * props every chart takes, how it loads, plays its entrance and keeps what\n * leaves, `activeIndex` and picking, the parts written inside it and what\n * they declare, the frame its axes read, the words of a chart whose stops\n * hold a value per series, and the tooltip of a share. A family's frame\n * provides the contexts here, so the shared parts (`chart.tsx`) read the\n * root and these, never a family's own.\n */\n\n/* The frame: the scales the axes, the grid and reference lines read. */\n\n/**\n * One axis of the frame: its scale, the one before its last change, so what\n * arrives starts where it would have been, and how it writes and titles its\n * values when its part is given neither.\n */\ninterface FrameAxis<Scale extends ChartScale> {\n  scale: Scale\n  previous: Scale\n  /** How it writes its values; the chart's `format` by default. */\n  format?: ChartFormat\n  /** What it measures, which titles it unless its part is given a `label`. */\n  label?: string\n}\n\n/**\n * The frame the marks stand in: the x axis, categories or numbers, and the\n * value axes by their ids, `'value'` the chart's own. The axes, the grid and\n * reference lines read it, and the pointer and the keys find what is under\n * them by it: along the categories, or among points by both values.\n */\ninterface ChartFrame {\n  x: FrameAxis<ChartScale>\n  /** Each value axis, by its id: the chart's own, `value`, always. */\n  y: Readonly<Record<string, FrameAxis<LinearScale>>> & { value: FrameAxis<LinearScale> }\n  /** Where marks grow from on each value axis, as a fraction of it. */\n  baselines: Readonly<Record<string, number>> & { value: number }\n  /** The id of the value axis a series is read against. */\n  axisOf: (key: string) => string\n  /** Whether a series adds to its category's total, as the tooltip's total row sums it: one that stacks on the chart's own value axis. */\n  totals: (key: string) => boolean\n  /**\n   * Whether its range waits for the plot's size, because a part keeps room\n   * in px past the value axis's end, as labels past the bars do: until the\n   * plot is measured, as in the server's HTML, the plot and its axes hold\n   * their place unseen rather than show a range that then shifts.\n   */\n  measuring: boolean\n  /**\n   * An x of times that shows a window of them, still or live: the clock the\n   * layers placed by x move with (`ChartLiveLayer`). Null for an x that\n   * shows all of it.\n   */\n  live: ChartLive | null\n}\n\n/** An axis of the frame by its id: `'x'`, or a value axis's, `'value'` the chart's own. */\ntype ChartAxis = string\n\n/**\n * A name on an axis that names things: a category's, or on a grid of cells,\n * a column's or a row's, over the band of the axis it names, such as a\n * month over its weeks.\n */\ninterface ChartAxisName {\n  key: string\n  /** The name as the data has it, which the axis writes. */\n  value: unknown\n  /** Its place among the axis's names. */\n  index: number\n  band: Band\n  leaving: boolean\n}\n\n/**\n * The frame's axis `axis` when it runs along numbers: a value axis, or the x\n * axis of a chart whose x is a number, such as a scatter. None for an x\n * axis of categories, or an id the chart has no axis for.\n */\nfunction numberAxis(\n  chart: { frame: ChartFrame },\n  axis: ChartAxis,\n): FrameAxis<LinearScale> | null {\n  if (axis !== 'x') return chart.frame.y[axis] ?? null\n  const { scale, previous, format, label } = chart.frame.x\n  if (scale.kind !== 'linear') return null\n  // A new x of numbers slides from where the same range put it.\n  return { scale, previous: previous.kind === 'linear' ? previous : scale, format, label }\n}\n\n/** The frame's x axis when it runs along times, such as a year of days on a line chart; none otherwise. */\nfunction timeAxis(chart: { frame: ChartFrame }): FrameAxis<TimeScale> | null {\n  const { scale, previous, format, label } = chart.frame.x\n  if (scale.kind !== 'time') return null\n  return { scale, previous: previous.kind === 'time' ? previous : scale, format, label }\n}\n\n/**\n * The scale a value axis had before its last change, by its signature, for\n * each axis of `scales`, so ticks and marks slide from where they were.\n */\nfunction usePreviousScales<Scale extends ChartScale>(\n  scales: Readonly<Record<string, Scale>>,\n): Readonly<Record<string, Scale>> {\n  const signature = Object.entries(scales)\n    .map(([axis, scale]) => `${axis}=${scaleSignature(scale)}`)\n    .join(';')\n  return useBefore(scales, signature)\n}\n\n/** The least room between two value ticks, in px: up the axis, and along it. */\nconst TICK_SPACING = { upright: 32, across: 56 } as const\n\n/* Places on the plot, in CSS and as fractions. */\n\n/** A line along the plot's height, or across its width, that `axisSlide` moves. */\nconst slideLine = {\n  x: 'absolute inset-y-0 left-0 w-0',\n  y: 'absolute inset-x-0 top-0 h-0',\n} as const\n\n/** A layer over an axis's area that its sliding labels measure their slide in. */\nconst axisLayerClassName = 'pointer-events-none absolute inset-0 [container-type:size]'\n\n/**\n * A tick, a grid line or a reference sliding along the value axis: in from\n * where the old range put it, and fading as it leaves. The resting place is\n * a variable too, so an inline style never overrules the starting one.\n */\nconst tickMove =\n  '[translate:var(--tick-to)] transition-none group-data-mounted/chart:transition-[translate,opacity] duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-mounted/chart:starting:[translate:var(--tick-from)] group-data-mounted/chart:starting:opacity-0 data-leaving:opacity-0 motion-reduce:group-data-mounted/chart:transition-opacity'\n\n/**\n * A line of no thickness slid to `place` along one axis of the size\n * container it sits in, a fraction of the value axis from its start, from\n * where `from` put it. Across the page, values run from the reading start;\n * up the page, from the bottom. Being no thicker than a line, it never makes\n * the page scroll wherever it slides. What sits on it is placed from its\n * physical top left.\n */\nfunction axisSlide(\n  axis: 'x' | 'y',\n  place: number,\n  from: number,\n  direction: ReadingDirection,\n): CSSProperties {\n  return {\n    '--tick-to': slideTo(axis, place, direction),\n    '--tick-from': slideTo(axis, from, direction),\n  } as CSSProperties\n}\n\n/** The `translate` that puts a line at `place` along the value axis. */\nfunction slideTo(axis: 'x' | 'y', place: number, direction: ReadingDirection) {\n  return axis === 'x'\n    ? `${plotOffset(direction === 'rtl' ? 1 - place : place, 'cqw')} 0`\n    : `0 ${plotOffset(1 - place, 'cqh')}`\n}\n\n/**\n * Where `place`, a fraction of the plot from its physical left or top, sits\n * along it in CSS, with `unit` the plot's width (`cqw`) or height (`cqh`).\n * A chart with an `inset`, such as a scatter, keeps that many px clear\n * inside each edge, as `--chart-inset`, so a point at either end of an axis\n * is drawn whole; on any other chart it is the place itself.\n */\nfunction plotOffset(place: number, unit: 'cqw' | 'cqh') {\n  const share = Math.round(place * 1e6) / 1e6\n  return `calc(var(--chart-inset, 0px) + ${share} * (100${unit} - 2 * var(--chart-inset, 0px)))`\n}\n\n/**\n * The same place as a fraction of the plot's whole `length` in px, for what\n * JavaScript places, such as a tooltip.\n */\nfunction plotFraction(place: number, length: number, inset: number) {\n  if (length <= 0) return place\n  return (inset + place * Math.max(0, length - inset * 2)) / length\n}\n\n/**\n * Where a point placed by both values sits on the plot, as fractions of it\n * from its physical left and its top, from its place along x from the\n * reading start and up the value axis.\n */\nfunction plotPlace(point: XYValue, direction: ReadingDirection): XYValue {\n  return { x: direction === 'rtl' ? 1 - point.x : point.x, y: 1 - point.y }\n}\n\n/** The physical side a part of a chart that scrolls sideways holds still on: the frame takes the opposite direction to the page, so a logical inset would land on the wrong side. */\nfunction stickTo(side: 'start' | 'end', direction: ReadingDirection) {\n  return (side === 'start') === (direction === 'ltr')\n    ? 'group-data-scrolls/chart:left-0'\n    : 'group-data-scrolls/chart:right-0'\n}\n\n/**\n * The ticks to draw, `drawn` or `scale`'s own, each with its text as `write`\n * gives it, and, until the move their range changed in has ended, every one\n * drawn before that the scale no longer has, which fades as it slides toward\n * where the new scale puts it, so the change of range shows. A tick leaving\n * keeps the text it was written with, so a change of format, such as counts\n * to shares, never rewrites it on its way out. A tick still fading in when\n * the range turns back fades out from where it is. In value order, so no\n * tick's element moves in the page, which would make it jump.\n */\nfunction useTicks(\n  scale: { ticks: readonly number[] } | null,\n  drawn?: readonly number[],\n  write?: (value: number) => string,\n) {\n  const ticks = drawn ?? scale?.ticks ?? NO_TICKS\n  const written = ticks.map((value) => ({ value, text: write?.(value) ?? '' }))\n  const leaving = useLeaving(useChartMoves(), written, tickKey)\n  return [\n    ...written.map((tick) => ({ ...tick, leaving: false })),\n    ...leaving.map((tick) => ({ ...tick, leaving: true })),\n  ].toSorted((a, b) => a.value - b.value)\n}\n\nfunction tickKey(tick: { value: number }) {\n  return String(tick.value)\n}\n\nconst NO_TICKS: readonly number[] = []\n\n/* Times and locales. */\n\n/** A locale for the dates lib: the chart's own when it is one tag. */\nfunction localeTag(locale: Intl.LocalesArgument): string | undefined {\n  if (typeof locale === 'string') return locale\n  if (locale instanceof Intl.Locale) return locale.toString()\n  if (Array.isArray(locale)) return localeTag(locale[0])\n  return undefined\n}\n\n/* The parts written inside a chart, and what they declare as it renders. */\n\n/** A series whose values from the category keyed `from` on are projected. */\ninterface ChartForecast {\n  series: string\n  from: string\n}\n\n/** Whether the value of `series` at `index`, a place among `current`, is a forecast. */\nfunction isForecast(\n  chart: { forecasts: readonly ChartForecast[]; current: readonly { key: string }[] },\n  series: string,\n  index: number,\n) {\n  return chart.forecasts.some((forecast) => {\n    if (forecast.series !== series) return false\n    const from = chart.current.findIndex((category) => category.key === forecast.from)\n    return from !== -1 && index >= from\n  })\n}\n\n/** A component that tells its chart about itself as it renders, with a static `declare` of its props. */\ntype DeclaringPart<Props, Declaration> = ((props: Props) => ReactNode) & {\n  declare: (props: Props) => Declaration\n}\n\n/** What the parts in a chart declared, and each declaration's signature, which a part looks for to know it was read. */\ninterface ChartParts<Declaration> {\n  declarations: readonly Declaration[]\n  signatures: ReadonlySet<string>\n}\n\n/**\n * What the parts in `children` declare: straight inside the chart, in a\n * fragment, or in an array. A part wrapped in a component of yours can't be\n * read, and says so when it renders (`useDeclared`). `signatureOf` tells one\n * declaration from another; an empty signature says nothing to read.\n */\nfunction chartParts<Declaration>(\n  children: ReactNode,\n  signatureOf: (declaration: Declaration) => string,\n): ChartParts<Declaration> {\n  const declarations: Declaration[] = []\n  const visit = (nodes: ReactNode) => {\n    Children.forEach(nodes, (node) => {\n      if (!isValidElement<{ children?: ReactNode }>(node)) return\n      if (node.type === Fragment) {\n        visit(node.props.children)\n        return\n      }\n      // A part a server component wrote reaches the chart not yet loaded, so it can't be read.\n      if ((node.type as { $$typeof?: symbol }).$$typeof === LAZY) {\n        throw new Error(\n          \"A chart's parts are read as it renders, so it is written in a client component: put `'use client'` at the top of the file that composes it.\",\n        )\n      }\n      const declare = (node.type as { declare?: (props: unknown) => Declaration }).declare\n      if (typeof declare === 'function') declarations.push(declare(node.props))\n    })\n  }\n  visit(children)\n  return { declarations, signatures: new Set(declarations.map(signatureOf)) }\n}\n\n/** What React marks a component that is still loading with. */\nconst LAZY = Symbol.for('react.lazy')\n\n/** The signatures of what the chart's parts declared, which each family's frame provides. */\nconst ChartPartsContext = createContext<{ signatures: ReadonlySet<string> } | null>(null)\n\n/**\n * Throws when a part that declares something wasn't read by its chart,\n * because it sits inside a component of yours: the chart would draw a range\n * that leaves it out, or a series it doesn't know.\n */\nfunction useDeclared<Declaration>(\n  name: string,\n  declaration: Declaration,\n  signatureOf: (declaration: Declaration) => string,\n) {\n  const parts = use(ChartPartsContext)\n  if (!parts) throw new Error('Chart parts go inside a chart, such as a `BarChart`.')\n  const signature = signatureOf(declaration)\n  if (signature !== '' && !parts.signatures.has(signature)) {\n    throw new Error(\n      `\\`${name}\\` goes straight inside its chart, or in a fragment there, so the chart reads it as it renders; inside a component of yours, the chart can't see it.`,\n    )\n  }\n}\n\n/**\n * Throws when the config and the parts disagree: a series in the config no\n * part draws, a part's series the config doesn't name, or a part that draws\n * a series as other than the config says. `marks` are the series the parts\n * draw, and as what; `own` is what a series that names no mark is drawn as.\n */\nfunction checkSeries(\n  config: ChartConfig,\n  marks: ReadonlyMap<string, ChartMark>,\n  own: ChartMark,\n) {\n  for (const [key, mark] of marks) {\n    const entry = config[key]\n    if (!entry) {\n      throw new Error(\n        `A part draws the series \\`${key}\\`, which the chart's \\`config\\` doesn't name. Add it to the config.`,\n      )\n    }\n    const says = entry.mark ?? own\n    if (says !== mark) {\n      throw new Error(\n        `The config draws the series \\`${key}\\` as \\`${says}\\`, but its part draws it as \\`${mark}\\`. Set its \\`mark\\` in the config to \\`${mark}\\`.`,\n      )\n    }\n  }\n  for (const key of Object.keys(config)) {\n    if (!marks.has(key)) {\n      throw new Error(\n        `The config names the series \\`${key}\\`, but no part inside the chart draws it. Add one, such as \\`<Bar dataKey='${key}' />\\`, or take it out of the config.`,\n      )\n    }\n  }\n}\n\n/** Values that parts of the chart add while they show, such as the room a radar's names take. */\nfunction useRegistry<T>() {\n  const [values, setValues] = useState<readonly T[]>([])\n  const add = useCallback((value: T) => {\n    setValues((all) => [...all, value])\n    return () =>\n      setValues((all) => {\n        const at = all.indexOf(value)\n        return at === -1 ? all : [...all.slice(0, at), ...all.slice(at + 1)]\n      })\n  }, [])\n  return { values, add }\n}\n\n/* The props every chart takes. */\n\n/** The props every chart with categories takes on its root. */\ninterface CategoryChartProps extends Omit<\n  ComponentProps<'figure'>,\n  'children' | 'onSelect'\n> {\n  /** One row per category: the category under `index`, and a value under each series' key. */\n  data: readonly ChartDatum[]\n  /** The key of each row's category. */\n  index: string\n  config: ChartConfig\n  /** What the chart shows, for screen readers: a short title, such as \"Visitors by month\". */\n  label: string\n  /** A longer account for screen readers, such as the trend the chart shows. */\n  description?: string\n  /** How values are written in the tooltip, the labels and the table, and the value axis by default. */\n  format?: ChartFormat\n  /**\n   * The categories run in order, such as days or months, so the tooltip and\n   * the screen reader give each value's change since the category before.\n   */\n  ordered?: boolean\n  /** How a category is written; `String` by default. */\n  categoryFormat?: (value: unknown) => string\n  /** The locale numbers are written in. Give one, so the server and the browser agree. */\n  locale?: Intl.LocalesArgument\n  /** The values at the ends of the value axis; `'auto'` fits the data. */\n  domain?: readonly [DomainEnd, DomainEnd]\n  /** About how many ticks the value axis marks. */\n  tickCount?: number\n  /** The ticks to mark, in place of round ones. */\n  tickValues?: readonly number[]\n  /** Ticks between whole numbers, such as 0.5; off by default when every value is whole. */\n  allowDecimals?: boolean\n  /** Gives each series after the first a pattern over its colour, so series differ by more than colour. */\n  patterns?: boolean\n  /** The series hidden, for a legend you control. */\n  hiddenSeries?: string[]\n  defaultHiddenSeries?: string[]\n  onHiddenSeriesChange?: (hidden: string[]) => void\n  /** The category under the pointer or the focus, by its place in `data`, for a chart you control. */\n  activeIndex?: number | null\n  defaultActiveIndex?: number | null\n  onActiveIndexChange?: (index: number | null) => void\n  /** The category picked, by its key; giving this, `defaultSelected` or `onSelectedChange` lets a press pick one. */\n  selected?: string | null\n  defaultSelected?: string | null\n  onSelectedChange?: (key: string | null) => void\n  /** Waiting for the data: a placeholder shows, and the marks grow out of it when the data arrives. */\n  loading?: boolean\n  /** The data couldn't load: `true` for the chart's own words, or what to say. */\n  error?: ReactNode\n  /** Shows a button that tries again, with `error`. */\n  onRetry?: () => void\n  /** What shows when `data` is empty. */\n  empty?: ReactNode\n  /** Every word the chart says or reads out, for a chart in another language. */\n  messages?: Partial<ChartMessages>\n  ref?: Ref<HTMLElement>\n  children?: ReactNode\n}\n\n/** The props a chart's root takes that every chart reads, so the root passes the rest to its frame. */\nconst categoryChartKeys = [\n  'data',\n  'index',\n  'config',\n  'label',\n  'description',\n  'format',\n  'ordered',\n  'categoryFormat',\n  'locale',\n  'domain',\n  'tickCount',\n  'tickValues',\n  'allowDecimals',\n  'patterns',\n  'hiddenSeries',\n  'defaultHiddenSeries',\n  'onHiddenSeriesChange',\n  'activeIndex',\n  'defaultActiveIndex',\n  'onActiveIndexChange',\n  'selected',\n  'defaultSelected',\n  'onSelectedChange',\n  'loading',\n  'error',\n  'onRetry',\n  'empty',\n  'messages',\n  'ref',\n  'children',\n  'className',\n] as const satisfies readonly (keyof CategoryChartProps)[]\n\n/** The props a root passes on to its `<figure>`: those that aren't every chart's, nor in `own`, the chart's own. */\nfunction figureProps(\n  props: object,\n  own: readonly string[] = [],\n): ComponentProps<'figure'> {\n  const out: Record<string, unknown> = {}\n  for (const [key, value] of Object.entries(props)) {\n    if (!(categoryChartKeys as readonly string[]).includes(key) && !own.includes(key))\n      out[key] = value\n  }\n  return out as ComponentProps<'figure'>\n}\n\n/* Loading, the entrance, and what leaves. */\n\n/** Where the entrance is: waiting to be seen, playing, or over. */\ntype EntrancePhase = 'waiting' | 'entering' | 'settled'\n\n/** Whether a chart shows its placeholder, and whether its data failed to load. */\ninterface ChartLoad {\n  placeholder: boolean\n  failed: boolean\n}\n\n/**\n * Whether the chart shows its placeholder while it loads, and whether it\n * failed. A chart that mounts loading shows its placeholder from the first\n * paint. Later, the placeholder shows once loading has lasted, then long\n * enough to be seen; until then the marks there are stay.\n */\nfunction useChartLoad({\n  loading = false,\n  error,\n}: {\n  loading?: boolean\n  error?: ReactNode\n}): ChartLoad {\n  const [firstLoad, setFirstLoad] = useState(loading)\n  if (firstLoad && !loading) setFirstLoad(false)\n  const placeholder = useSpinner(loading) || firstLoad\n  return { placeholder, failed: Boolean(error) && !loading }\n}\n\n/** How a chart's marks play their entrance. */\ninterface ChartLifeOptions {\n  /** Whether the marks play an entrance the first time the chart comes into view. */\n  entrance: boolean\n  /**\n   * How the marks start one after another in the entrance, such as bars in\n   * a cascade: the CSS variable on the chart that holds the share of their\n   * role's duration they start over, and its default. Null when they start\n   * together.\n   */\n  cascade: { variable: string; fallback: number } | null\n}\n\n/**\n * What the chart shows (`status`), and where its entrance is: whether the\n * data arrived as the placeholder went, so the marks grow out of the\n * placeholder's (`fromPlaceholder`), the entrance's `phase`, and whether it\n * has played or wasn't asked for (`entered`). `counts` are the rows in the\n * data, the series shown and the rows drawn.\n */\nfunction useChartLife(\n  props: { data: unknown; loading?: boolean },\n  root: Pick<ChartRootState, 'moves' | 'seen' | 'root'>,\n  load: ChartLoad,\n  counts: { rows: number; shown: number; drawn: number },\n  options: ChartLifeOptions,\n) {\n  const { data, loading = false } = props\n  const { placeholder, failed } = load\n  const { moves } = root\n  const status: ChartStatus = chartStatus({ placeholder, loading, failed, ...counts })\n  // The data that arrived as the placeholder went: until it changes, its marks grow out of the\n  // placeholder's.\n  const [loaded, setLoaded] = useState({ placeholder, data: null as unknown })\n  if (loaded.placeholder !== placeholder) {\n    setLoaded({ placeholder, data: placeholder ? null : data })\n  }\n  const fromPlaceholder = !placeholder && loaded.data === data\n  const [phase, setPhase] = useState<EntrancePhase>(\n    options.entrance ? 'waiting' : 'settled',\n  )\n  if (phase === 'waiting' && (root.seen || fromPlaceholder) && status !== 'loading') {\n    setPhase(fromPlaceholder ? 'settled' : 'entering')\n  }\n  // The entrance is over once its move has run, its cascade too.\n  const entering = phase === 'entering'\n  const figure = root.root\n  const cascade = options.cascade?.variable\n  const cascadeFallback = options.cascade?.fallback ?? 0\n  useLayoutEffect(() => {\n    if (!entering) return\n    let live = true\n    const element = figure.current\n    const span = cascade && element ? cascadeSpan(element, cascade, cascadeFallback) : 0\n    void moves.request(span, true).then(() => {\n      if (live) setPhase('settled')\n    })\n    return () => {\n      live = false\n    }\n  }, [entering, moves, figure, cascade, cascadeFallback])\n  return { status, fromPlaceholder, phase, entered: phase !== 'waiting' }\n}\n\n/** The share of its role's duration a cascade's marks start over, from its variable on the chart. */\nfunction cascadeSpan(element: Element, variable: string, fallback: number) {\n  const value = Number.parseFloat(getComputedStyle(element).getPropertyValue(variable))\n  return Number.isFinite(value) ? Math.max(0, value) : fallback\n}\n\n/**\n * Every item to draw: `current`, those in the data, and `leaving`, those\n * just taken out, marked so, in one fixed order by key whatever the data's:\n * an element moved in the page starts again with no transition, so a sort\n * would jump instead of sliding.\n */\nfunction withLeaving<Item extends object>(\n  current: readonly Item[],\n  leaving: readonly Item[],\n  keyOf: (item: Item) => string,\n): (Item & { leaving: boolean })[] {\n  return [\n    ...current.map((item) => ({ ...item, leaving: false })),\n    ...leaving.map((item) => ({ ...item, leaving: true })),\n  ].toSorted((a, b) => {\n    const ka = keyOf(a)\n    const kb = keyOf(b)\n    return ka < kb ? -1 : ka > kb ? 1 : 0\n  })\n}\n\n/**\n * The items to draw: those in the data, and those just taken out, kept\n * where they were until the move they left in has ended, fading out\n * (`withLeaving`).\n */\nfunction useLeavingItems<Item extends object>(\n  moves: ChartMoves,\n  current: readonly Item[],\n  keyOf: (item: Item) => string,\n) {\n  return withLeaving(current, useLeaving(moves, current, keyOf), keyOf)\n}\n\n/* Picking. */\n\n/** What picking is for a chart: whether a press picks, what is picked by key, and the toggle. */\nfunction useChartPick(\n  props: {\n    selected?: string | null\n    defaultSelected?: string | null\n    onSelectedChange?: (key: string | null) => void\n  },\n  keys: readonly string[],\n) {\n  const { selected, defaultSelected = null, onSelectedChange } = props\n  const selectable =\n    selected !== undefined ||\n    props.defaultSelected !== undefined ||\n    onSelectedChange !== undefined\n  const [own, setOwn] = useControllable(selected, defaultSelected, onSelectedChange)\n  // A key the data no longer has is picked by nothing.\n  const picked = own !== null && keys.includes(own) ? own : null\n  return {\n    selectable,\n    picked,\n    /** Picks `key`, or lets it go if it was picked. */\n    toggle: (key: string) => setOwn(picked === key ? null : key),\n  }\n}\n\n/* `activeIndex`: the item under the pointer or the focus, by its place. */\n\n/** The props of a chart you control what is under the pointer or the focus of. */\ninterface ActiveIndexProps {\n  activeIndex?: number | null\n  defaultActiveIndex?: number | null\n  onActiveIndexChange?: (index: number | null) => void\n}\n\n/** The index of `target` among `keys`, or null. */\nfunction toldIndex(keys: readonly string[], target: ChartTarget | null): number | null {\n  return target === null ? null : indexOfKey(keys, targetKey(target))\n}\n\n/** Tells `index` once: not again while it is the one `told` last told or saw. */\nfunction tellIndex(\n  told: { current: number | null },\n  index: number | null,\n  tell: ((index: number | null) => void) | undefined,\n) {\n  if (index === told.current) return\n  told.current = index\n  tell?.(index)\n}\n\n/** The item at `index` of `items`, or null for none. */\nfunction itemAt(items: readonly ChartTarget[], index: number | null | undefined) {\n  return index === null || index === undefined ? null : (items[index] ?? null)\n}\n\n/**\n * The root's focus for a chart whose API counts `items` (`reader.items`):\n * `activeIndex` as the item it counts, and each change told once as an\n * index. `toldRef` holds the index last told or seen, which `IndexActive`\n * reads too.\n */\nfunction useIndexFocus(items: readonly ChartTarget[], props: ActiveIndexProps) {\n  // The index last told to `onActiveIndexChange`, or seen, so each change is told once.\n  const toldRef = useRef<number | null>(null)\n  const keys = items.map(targetKey)\n  const focusProps: ChartFocusProps = {\n    focus: props.activeIndex === undefined ? undefined : itemAt(items, props.activeIndex),\n    defaultFocus: itemAt(items, props.defaultActiveIndex),\n    onFocusChange: (target) =>\n      tellIndex(toldRef, toldIndex(keys, target), props.onActiveIndexChange),\n  }\n  return { focusProps, toldRef }\n}\n\n/**\n * What is under the pointer, kept apart from the rest of the chart, so a\n * hover re-renders only the parts that show it, never the data table or\n * each category's column.\n */\ninterface ChartActiveValue {\n  /** The item under the pointer or the focus, by its place among the items. */\n  active: number | null\n  setActive: (index: number | null) => void\n  /** The item that stays bright: the one under the pointer, or else the one picked. */\n  spotlit: number | null\n}\n\nconst ChartActiveContext = createContext<ChartActiveValue | null>(null)\n\nfunction useChartActive() {\n  const value = use(ChartActiveContext)\n  if (!value) throw new Error('Chart parts go inside a chart, such as a `BarChart`.')\n  return value\n}\n\n/**\n * The focus as the parts of a chart that counts `items` read it: the item it\n * is on, by its place. Told when new data moves the item it is on, for a\n * chart that keeps its own. Each frame renders it inside the root's focus.\n */\nfunction IndexActive({\n  items,\n  active: props,\n  toldRef,\n  children,\n}: {\n  items: readonly ChartTarget[]\n  active: ActiveIndexProps\n  toldRef: RefObject<number | null>\n  children: ReactNode\n}) {\n  const { focus, setFocus, spotlit } = useChartFocus()\n  const grouped = useChartGroup() !== null\n  const keys = items.map(targetKey)\n  const active = toldIndex(keys, focus)\n  const lit = toldIndex(keys, spotlit)\n  const { activeIndex, onActiveIndexChange } = props\n  useLayoutEffect(() => {\n    if (active === toldRef.current) return\n    // Moves the focus made are told as they happen, so this is new data moving its key.\n    toldRef.current = active\n    if (activeIndex === undefined && !grouped && active !== null)\n      onActiveIndexChange?.(active)\n  })\n  // One function for the chart's life, so parts that take it, such as the\n  // Bar list's rows, redraw only when what they show changes, without the\n  // React Compiler.\n  const latest = useRef(items)\n  useLayoutEffect(() => {\n    latest.current = items\n  })\n  const setActive = useCallback(\n    (index: number | null) => setFocus(itemAt(latest.current, index)),\n    [setFocus],\n  )\n  const value = useMemo(\n    () => ({ active, setActive, spotlit: lit }),\n    [active, setActive, lit],\n  )\n  return <ChartActiveContext value={value}>{children}</ChartActiveContext>\n}\n\n/* Words: what a chart whose every stop holds a value per series says. */\n\n/** What a chart whose every stop holds a value per series reads its words from. */\ninterface SeriesWordsInput {\n  /** The stops still in the data, in order. */\n  stops: readonly ChartItem[]\n  seriesText: (item: ChartItem, series: string) => string\n  /**\n   * A series' value at `item` for the tooltip and what is read out: its row\n   * there, with `at` null, or a row of its own near it, with `at` that row's\n   * own time as the axis writes a stop; null leaves the series out there.\n   * The data table writes only a row exactly at the stop.\n   */\n  seriesNear: (\n    item: ChartItem,\n    series: string,\n  ) => { text: string; at: string | null } | null\n  /** How much a series' value changed since `before`, as a share of it, or null. */\n  seriesChange: (item: ChartItem, before: ChartItem, series: string) => number | null\n  /** How a stop is named. */\n  stopText: (item: ChartItem) => string\n  /** The stops run in order, such as days, so a change since the one before means something. */\n  ordered: boolean\n  /** The total of `item`'s shown series, or null where it has none or fewer than two shown series add to it. */\n  totals: (item: ChartItem) => number | null\n  /** Whether the tooltip shows the total when `<ChartTooltip>` doesn't say. */\n  totalByDefault: boolean\n  /** Whether the value of `series` on `item` is projected. */\n  forecast: (series: string, item: ChartItem) => boolean\n  /** The key of the stop picked, or null. */\n  picked: string | null\n  /** The series the keys brought forward, read out alone so Up and Down are heard, or null. */\n  alone: string | null\n  /**\n   * A chart's own words in place of the series' values, with their table\n   * column, or null. A stop with no row of the chart's own, where only a\n   * series' own rows are, reads its series' values and leaves the column\n   * empty.\n   */\n  own: { name: string; text: (item: ChartItem) => string } | null\n}\n\n/** Anything under a series' key as `write` writes a number: a number, a `[from, to]` range, or `noValue` for none. */\nfunction writeDatum(value: unknown, write: (value: number) => string, noValue: string) {\n  const range = rangeOf(value)\n  if (range) return `${write(range[0])} – ${write(range[1])}`\n  const number = numberOf(value)\n  return number === null ? noValue : write(number)\n}\n\n/** What a reader says of its stops: to a screen reader, in the tooltip, and as the data table. */\ninterface ChartWords {\n  describe: (item: ChartItem) => string\n  tooltip: (item: ChartItem) => ReactNode\n  table: ChartTable\n}\n\n/** A stop's name as every chart reads it out: with \", selected\" when it is picked. */\nfunction pickedName(name: string, picked: boolean, messages: ChartMessages): string {\n  return picked ? `${name}, ${messages.selected}` : name\n}\n\n/** A series' name as the chart writes it in words: its label when that is text, else its key. */\nfunction seriesName(config: ChartConfig, key: string) {\n  const label = config[key]?.label\n  return typeof label === 'string' ? label : key\n}\n\n/**\n * The words of a chart whose every stop holds a value per series: each\n * stop's name, then each shown series' value near it, with the time of a\n * row of its own beside the stop, its change since the stop before when\n * they run in order and whether it is projected; or the series brought\n * forward alone; or the chart's own words.\n */\nfunction seriesWords(\n  root: Pick<ChartRootState, 'series' | 'hidden' | 'config' | 'messages' | 'locale'>,\n  input: SeriesWordsInput,\n): ChartWords {\n  const { series, hidden, config, messages, locale } = root\n  const { stops, own } = input\n  const shown = series.filter((key) => !hidden.includes(key))\n  const projected = (key: string, item: ChartItem) =>\n    input.forecast(key, item) ? `, ${messages.forecast}` : ''\n  return {\n    describe: (item) => {\n      const name = pickedName(input.stopText(item), input.picked === item.key, messages)\n      if (own && item.datum !== null) return `${name}: ${own.text(item)}`\n      const at = stops.findIndex((stop) => stop.key === item.key)\n      const before = input.ordered && at > 0 ? stops[at - 1] : undefined\n      const keys =\n        input.alone !== null && shown.includes(input.alone) ? [input.alone] : shown\n      const values = keys.flatMap((key) => {\n        const near = input.seriesNear(item, key)\n        if (!near) return []\n        const change = before ? input.seriesChange(item, before, key) : null\n        const said =\n          change === null\n            ? ''\n            : `, ${messages.change(change, percent(locale).format(Math.abs(change)))}`\n        const when = near.at === null ? '' : ` (${near.at})`\n        return [\n          `${seriesName(config, key)}${when} ${near.text}${projected(key, item)}${said}`,\n        ]\n      })\n      return values.length === 0 ? name : `${name}: ${values.join(', ')}`\n    },\n    tooltip: (item) => <ChartTooltipContent index={item.index} />,\n    table: {\n      header: messages.category,\n      columns: own ? [own.name] : shown.map((key) => seriesName(config, key)),\n      rows: stops.map((stop) => ({\n        key: stop.key,\n        name: input.stopText(stop),\n        // Only a row exactly at the stop: the table never shows a value from beside it.\n        cells: own\n          ? [stop.datum === null ? '' : own.text(stop)]\n          : shown.map((key) =>\n              input.seriesNear(stop, key)?.at === null\n                ? `${input.seriesText(stop, key)}${projected(key, stop)}`\n                : '',\n            ),\n      })),\n      footer: [],\n    },\n  }\n}\n\n/**\n * The total a stop's tooltip adds: the sum of its shown series when the\n * total is on (`own`, the content's, else `told`, the tooltip's, else the\n * chart's default), or null.\n */\nfunction tooltipTotal(\n  words: Pick<SeriesWordsInput, 'totals' | 'totalByDefault'>,\n  item: ChartItem,\n  own: boolean | undefined,\n  told: boolean | undefined,\n): number | null {\n  return (own ?? told ?? words.totalByDefault) ? words.totals(item) : null\n}\n\n/** The words of the chart a part sits in, for `ChartTooltipContent`; each frame that uses `seriesWords` provides them. */\nconst SeriesWordsContext = createContext<SeriesWordsInput | null>(null)\n\n/** Whether a stop's tooltip adds the total of its shown values: the tooltip's `total`, or undefined to follow the chart. */\nconst ChartTooltipTotal = createContext<boolean | undefined>(undefined)\n\n/**\n * The values of the stop at `index`: its name, then a row for each shown\n * series, with its change since the stop before when the stops run in\n * order, and their total with `total`, which follows the tooltip's own, and\n * the chart's, by default.\n */\nfunction ChartTooltipContent({\n  index,\n  total: own,\n  hideLabel = false,\n  className,\n  children,\n  ...props\n}: ComponentProps<'div'> & {\n  index: number\n  total?: boolean\n  hideLabel?: boolean\n}) {\n  const words = use(SeriesWordsContext)\n  const told = use(ChartTooltipTotal)\n  const {\n    id,\n    series,\n    hidden,\n    config,\n    valueText,\n    locale,\n    patternOf,\n    messages,\n    emphasis,\n    markerOf,\n  } = useChartRootValue()\n  if (!words) {\n    throw new Error(\n      '`ChartTooltipContent` goes inside a chart with series, such as a `BarChart`.',\n    )\n  }\n  const at = words.stops.findIndex((stop) => stop.index === index)\n  const item = words.stops[at]\n  if (!item) return null\n  const before = words.ordered && at > 0 ? words.stops[at - 1] : undefined\n  const shown = series.filter((key) => !hidden.includes(key))\n  const sum = tooltipTotal(words, item, own, told)\n  return (\n    // The tooltip sits outside the chart, so it carries the chart's id for its colours.\n    <div data-chart={id} className={cn('grid min-w-36 gap-1', className)} {...props}>\n      {!hideLabel && <div className='font-medium'>{words.stopText(item)}</div>}\n      {shown.map((key) => {\n        const near = words.seriesNear(item, key)\n        if (!near) return null\n        const marker = markerOf(key)\n        return (\n          // The series brought forward reads in full colour; the rest stay as they are, legible.\n          <div\n            key={key}\n            data-lit={emphasis === key ? '' : undefined}\n            className='group/row flex items-center gap-2'\n          >\n            {/* A series drawn in a shape of its own, such as a line or points, keys it by that shape, as the legend does. */}\n            {marker ? (\n              <SeriesKey\n                series={key}\n                slot={series.indexOf(key)}\n                pattern={patternOf(key)}\n                marker={marker}\n              />\n            ) : (\n              <span\n                aria-hidden\n                className={cn(swatchClassName, forcedSeriesColor(series.indexOf(key)))}\n                style={swatchStyle(key, patternOf(key))}\n              />\n            )}\n            <span className={cn(tooltipQuietClassName, 'min-w-0 flex-1 truncate')}>\n              {config[key]?.label ?? key}\n              {near.at !== null && ` (${near.at})`}\n              {words.forecast(key, item) && ` (${messages.forecast})`}\n            </span>\n            {before && (\n              <ChangeText\n                change={words.seriesChange(item, before, key)}\n                locale={locale}\n                className={tooltipQuietClassName}\n              />\n            )}\n            {/* A value with a unit reads in its own order whatever the page's direction. */}\n            <span dir='auto' className='font-medium tabular-nums'>\n              {near.text}\n            </span>\n          </div>\n        )\n      })}\n      {sum !== null && (\n        <div className='border-background/20 mt-0.5 flex items-center gap-2 border-t pt-1 forced-colors:border-[CanvasText]'>\n          <span className='text-background/75 flex-1 forced-colors:text-[CanvasText]'>\n            {messages.total}\n          </span>\n          <span className='font-medium tabular-nums'>{valueText(sum)}</span>\n        </div>\n      )}\n      {children}\n    </div>\n  )\n}\n\n/* The axes: what the axes, the grid and reference parts read. */\n\n/** The names along one axis, and which one a target is under. */\ninterface AxisNames {\n  /** Drawn, the leaving ones too. */\n  all: readonly ChartAxisName[]\n  /** Still in the data. */\n  current: readonly ChartAxisName[]\n  /** The name `target` is under, by its place in `current`, or null. */\n  nameOf: (target: ChartTarget) => number | null\n  /** How the axis writes a name, unless the part is given a `categoryFormat`. */\n  format: (value: unknown) => string\n  /** Whether a name at either end is kept inside the axis. A grid's rows are each a name's height or more, so they centre freely. */\n  keepInside: boolean\n}\n\n/** What a chart's axes, grid and reference parts read, which each family with axes provides. */\ninterface ChartAxesValue {\n  /** The chart's scales, or null on a chart whose axes only name things, such as the Heatmap. */\n  frame: ChartFrame | null\n  orientation: ChartOrientation\n  inset: number\n  /** The names along each axis: categories, a grid's columns or rows, or a time axis's stops (for its lit pill). Null on an axis of values or numbers. */\n  names: { x: AxisNames | null; y: AxisNames | null }\n  /** Every value read against `axis`, for a reference at a summary such as the mean. Empty with no frame. */\n  summaryValues: (axis: string) => readonly unknown[]\n  /** The chart's own value axis is shares of 100% (stack `expand`), so it is written in percent. */\n  percent: boolean\n}\n\nconst ChartAxesContext = createContext<ChartAxesValue | null>(null)\n\nfunction useChartAxes() {\n  const value = use(ChartAxesContext)\n  if (!value) throw new Error('Chart parts go inside a chart, such as a `BarChart`.')\n  return value\n}\n\n/* Shares of a whole, such as the Donut's and the Waffle's. */\n\n/** A share's value: a number above zero, or zero for one that is missing or below it. */\nfunction shareValue(datum: ChartDatum, dataKey: string) {\n  return Math.max(0, numberOf(datum[dataKey]) ?? 0)\n}\n\n/** A share's colour: its own, or the next of the chart's colours for one the config leaves out. */\nfunction shareColor(chart: Pick<ChartRootState, 'series'>, item: ChartItem) {\n  const slot = chart.series.indexOf(item.key)\n  return `var(--color-${item.key}, var(--chart-${((slot === -1 ? item.index : slot) % 5) + 1}))`\n}\n\n/** A row of a share's tooltip: one of its values, and its share. */\ninterface ShareTooltipRow {\n  /** The value's name, when there are several, such as a ring's. */\n  label: string | null\n  /** The value the share is of, or null for a row that is a share alone, such as a share of the whole. */\n  value: string | null\n  /** Its part of the whole, or null for a value that isn't one, such as a second value beside it. */\n  share: string | null\n}\n\n/**\n * The tooltip for a share: its swatch and its name, its share and its\n * value, or under its name, each of its values'. `swatch` stands in for the\n * share's own, for a share drawn otherwise, such as a waffle's remaining\n * cells.\n */\nfunction ShareTooltipContent({\n  chart,\n  category,\n  name,\n  rows,\n  swatch: own,\n}: {\n  chart: Pick<ChartRootState, 'id' | 'series' | 'patternOf'>\n  category: ChartItem\n  name: string\n  rows: readonly ShareTooltipRow[]\n  swatch?: ReactNode\n}) {\n  const slot = chart.series.indexOf(category.key)\n  const swatch = own ?? (\n    <span\n      aria-hidden\n      className={cn(\n        swatchClassName,\n        forcedSeriesColor(slot === -1 ? category.index : slot),\n      )}\n      style={swatchStyle(\n        category.key,\n        slot === -1 ? 'solid' : chart.patternOf(category.key),\n      )}\n    />\n  )\n  const figures = (row: ShareTooltipRow) => (\n    <>\n      {/* A value with a unit reads in its own order whatever the page's direction. */}\n      {row.share !== null && (\n        <span\n          dir='auto'\n          className='text-background/75 tabular-nums forced-colors:text-[CanvasText]'\n        >\n          {row.share}\n        </span>\n      )}\n      {row.value !== null && (\n        <span dir='auto' className='font-medium tabular-nums'>\n          {row.value}\n        </span>\n      )}\n    </>\n  )\n  const single = rows.length === 1 ? rows[0] : undefined\n  return (\n    // The tooltip sits outside the chart, so it carries the chart's id for its colours.\n    <div data-chart={chart.id} className='flex min-w-36 flex-col gap-1'>\n      <div className='flex items-center gap-2'>\n        {swatch}\n        <span\n          className={cn(\n            'min-w-0 flex-1 break-words',\n            single ? 'text-background/75 forced-colors:text-[CanvasText]' : 'font-medium',\n          )}\n        >\n          {name}\n        </span>\n        {single && figures(single)}\n      </div>\n      {!single &&\n        rows.map((row) => (\n          <div key={row.label} className='flex items-center gap-2 ps-4'>\n            <span className='text-background/75 min-w-0 flex-1 break-words forced-colors:text-[CanvasText]'>\n              {row.label}\n            </span>\n            {figures(row)}\n          </div>\n        ))}\n    </div>\n  )\n}\n\n/** The rows whose series isn't hidden, for a chart whose rows each belong to one. */\nfunction rowsShown(\n  rows: readonly ChartDatum[],\n  seriesOf: (row: ChartDatum) => string,\n  hidden: readonly string[],\n) {\n  return rows.filter((row) => !hidden.includes(seriesOf(row)))\n}\n\nexport {\n  type ActiveIndexProps,\n  type AxisNames,\n  axisLayerClassName,\n  axisSlide,\n  cascadeSpan,\n  type CategoryChartProps,\n  categoryChartKeys,\n  type ChartActiveValue,\n  type ChartAxesValue,\n  ChartAxesContext,\n  type ChartAxis,\n  type ChartAxisName,\n  type ChartForecast,\n  type ChartFrame,\n  type ChartLifeOptions,\n  type ChartLoad,\n  type ChartParts,\n  ChartPartsContext,\n  chartParts,\n  ChartTooltipContent,\n  ChartTooltipTotal,\n  type ChartWords,\n  checkSeries,\n  writeDatum,\n  type DeclaringPart,\n  type EntrancePhase,\n  figureProps,\n  type FrameAxis,\n  IndexActive,\n  isForecast,\n  localeTag,\n  numberAxis,\n  pickedName,\n  plotFraction,\n  plotOffset,\n  plotPlace,\n  rowsShown,\n  seriesWords,\n  type SeriesWordsInput,\n  SeriesWordsContext,\n  shareColor,\n  ShareTooltipContent,\n  type ShareTooltipRow,\n  shareValue,\n  slideLine,\n  slideTo,\n  stickTo,\n  TICK_SPACING,\n  tickMove,\n  timeAxis,\n  tellIndex,\n  toldIndex,\n  tooltipTotal,\n  useChartActive,\n  useChartAxes,\n  useChartLife,\n  useChartLoad,\n  useChartPick,\n  useDeclared,\n  useIndexFocus,\n  useLeavingItems,\n  usePreviousScales,\n  useRegistry,\n  useTicks,\n  withLeaving,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-base.tsx"
    },
    {
      "path": "registry/lib/chart-cartesian-reader.ts",
      "content": "import { type ChartWords, plotPlace } from '@/registry/lib/chart-base'\nimport type { ChartLive } from '@/registry/lib/chart-live-clock'\nimport {\n  alongCategories,\n  type ChartDatum,\n  type ChartOrientation,\n  keyAxis,\n  nearestPoint,\n  pointRank,\n  type ReadingDirection,\n  sliderValue,\n  stepIndex,\n  stepPoint,\n  type XYValue,\n} from '@/registry/lib/chart-math'\nimport type { ChartPoint, ChartReader, PlotPoint } from '@/registry/lib/chart-root'\nimport { type Band, bandCentre, indexAt } from '@/registry/lib/chart-scale'\nimport { type ChartTarget, indexOfKey, targetSeries } from '@/registry/lib/chart-state'\n\n/*\n * The reader of the cartesian charts: how the pointer and the keys move\n * among the stops along x, where the tooltip sits and what is read out,\n * for the root (`chart-root`), which knows nothing about an x axis. Each\n * stop is a category, a time, or a scatter's point, held by its key. A\n * chart browses them in one of three ways: every series at a stop, one\n * series at a stop, or points placed by both values.\n */\n\n/** A place along x the keys, the tooltip and the table stop at: a category, a time, or a scatter's point. */\ninterface CartesianStop {\n  key: string\n  /** As the data has it, under the chart's `index`. */\n  value: unknown\n  /** Its place among the stops still in the data; a leaving one keeps its last. */\n  index: number\n  band: Band\n  leaving: boolean\n  /** The chart's own row here, or null where only a series' own rows have one. */\n  datum: ChartDatum | null\n  /** The row here of each series that brings rows of its own and has one. */\n  own: Readonly<Record<string, ChartDatum>>\n}\n\n/** A stop placed by both values: by value, and by place as fractions along x from the reading start and up the value axis. */\ninterface CartesianPoint {\n  value: XYValue\n  place: XYValue\n}\n\n/** How the pointer and the keys move among the stops. */\ntype CartesianBrowse =\n  /** Bar, Line, Area, Composed, Funnel: every series at a stop. */\n  | { kind: 'x' }\n  /**\n   * Bump, a Bar chart with ribbons: one series at a stop, picked by the\n   * pointer, and stepped with the arrows along the value axis, Up and Down\n   * on an upright chart, and on a lying one the arrows along reading order,\n   * which leave Up and Down to the stops. `seriesAt`'s point is in fractions\n   * of the plot from its reading start and its top; `step` is the series a\n   * step toward the value axis's end (-1: up, or on along reading order) or\n   * back (1) from `from` at the stop at `stop`, or null.\n   */\n  | {\n      kind: 'x-series'\n      seriesAt: (point: XYValue) => string | null\n      step: (stop: number, from: string | null, step: -1 | 1) => string | null\n    }\n  /**\n   * Scatter: each stop is a point. Keys step by its values, the pointer\n   * finds it by its place with the `inset` in px kept clear inside the\n   * plot's edges, and the slider ranks along the axis the last key moved\n   * (`along`), which `onAlong` is told of.\n   */\n  | {\n      kind: 'points'\n      point: (stop: CartesianStop) => CartesianPoint | null\n      inset: number\n      along: 'x' | 'y'\n      onAlong: (axis: 'x' | 'y') => void\n    }\n\ninterface CartesianReaderInput {\n  current: readonly CartesianStop[]\n  browse: CartesianBrowse\n  orientation: ChartOrientation\n  direction: ReadingDirection\n  /** Where the tooltip of a stop sits, and its side; `series` for a target on one series. */\n  anchor: (stop: CartesianStop, series: string | null) => ChartPoint | null\n  /** What is said of each stop: a `CartesianStop` is a `ChartItem`. */\n  words: ChartWords\n  /** Where the keys start: the first stop, or the last on a chart that opens at its end (a window, still or live). */\n  start: 'first' | 'last'\n  series: readonly string[]\n  hidden: readonly string[]\n}\n\n/**\n * The step along the value axis a key asks for: -1 toward its end, 1 back\n * toward its start, or null for a key that steps the stops: Up and Down on\n * an upright chart, the arrows along reading order on a lying one.\n */\nfunction valueStep(\n  key: string,\n  orientation: ChartOrientation,\n  direction: ReadingDirection,\n): -1 | 1 | null {\n  const [toEnd, back] =\n    orientation === 'vertical'\n      ? ['ArrowUp', 'ArrowDown']\n      : direction === 'rtl'\n        ? ['ArrowLeft', 'ArrowRight']\n        : ['ArrowRight', 'ArrowLeft']\n  return key === toEnd ? -1 : key === back ? 1 : null\n}\n\n/** Where a stop with no shown value sits among points, so the keys still reach it. */\nconst NO_POINT: XYValue = { x: 0, y: 0 }\n\n/**\n * The reader of a cartesian chart: each stop held by its key, found by the\n * pointer along x, or among points by both values, and stepped by the keys\n * as the slider pattern asks; on a chart whose series are pointed at one by\n * one, the target holds its series too, which it brings forward.\n */\nfunction cartesianReader(input: CartesianReaderInput): ChartReader {\n  const { current, browse, orientation, direction, words } = input\n  const keys = current.map((stop) => stop.key)\n  const count = keys.length\n  const centres = current.map((stop) => bandCentre(stop.band))\n  // Points placed by both values step by value, and the pointer finds the nearest by place.\n  const placed =\n    browse.kind === 'points'\n      ? current.map((stop) => browse.point(stop) ?? { value: NO_POINT, place: NO_POINT })\n      : null\n  const values = placed && placed.map((point) => point.value)\n  const indexOf = (target: ChartTarget) =>\n    target.kind === 'node' ? null : indexOfKey(keys, target.key)\n  const stopOf = (target: ChartTarget) => {\n    const index = indexOf(target)\n    return index === null ? undefined : current[index]\n  }\n  const at = (index: number | null, series: string | null): ChartTarget | null => {\n    const key = index === null ? undefined : keys[index]\n    if (key === undefined) return null\n    return series === null ? { kind: 'x', key } : { kind: 'datum', series, key }\n  }\n  const start = count === 0 ? null : input.start === 'last' ? count - 1 : 0\n  return {\n    holds: (target) => {\n      if (indexOf(target) === null) return false\n      return (\n        target.kind === 'x' ||\n        (target.kind === 'datum' &&\n          input.series.includes(target.series) &&\n          !input.hidden.includes(target.series))\n      )\n    },\n    lights: targetSeries,\n    item: (target) => {\n      const stop = stopOf(target)\n      if (!stop) return null\n      const { key, value, datum, index } = stop\n      return { key, value, datum, index }\n    },\n    items: keys.map((key) => ({ kind: 'x', key })),\n    browse: {\n      targetAt: (point: PlotPoint) => {\n        // The plot's own box, from its top left.\n        const box = { left: 0, top: 0, width: point.width, height: point.height }\n        if (placed) {\n          const inset = browse.kind === 'points' ? browse.inset : 0\n          return at(nearestPlace(placed, point, inset, direction), null)\n        }\n        const index = indexAt(\n          alongCategories(point, box, orientation, direction),\n          centres,\n        )\n        const series =\n          browse.kind === 'x-series'\n            ? browse.seriesAt({\n                x: alongCategories(point, box, 'vertical', direction),\n                y: point.height === 0 ? 0 : point.y / point.height,\n              })\n            : null\n        return at(index, series)\n      },\n      start: at(start, null),\n      step: (from, key) => {\n        const index = indexOf(from)\n        if (index === null) return null\n        const series = targetSeries(from)\n        const along =\n          browse.kind === 'x-series' ? valueStep(key, orientation, direction) : null\n        if (browse.kind === 'x-series' && along !== null) {\n          return at(index, browse.step(index, series, along))\n        }\n        if (browse.kind === 'points' && values) {\n          // Points step by x along it, and by y up and down.\n          const next = stepPoint(values, index, key, direction)\n          if (next === null) return null\n          browse.onAlong(keyAxis(key))\n          return at(next, series)\n        }\n        return at(stepIndex(key, index, count, orientation, direction), series)\n      },\n      rank: (target) => {\n        const index = indexOf(target) ?? 0\n        if (browse.kind === 'points' && values)\n          return pointRank(values, index, browse.along)\n        return sliderValue(index, Math.max(1, count), orientation)\n      },\n      stops: count,\n      orientation: orientation === 'vertical' ? 'horizontal' : 'vertical',\n      anchor: (target) => {\n        const stop = stopOf(target)\n        return stop ? input.anchor(stop, targetSeries(target)) : null\n      },\n      describe: (target) => {\n        const stop = stopOf(target)\n        return stop ? words.describe(stop) : ''\n      },\n      tooltip: (target) => {\n        const stop = stopOf(target)\n        return stop ? words.tooltip(stop) : null\n      },\n      table: words.table,\n      open: () => null,\n      back: null,\n    },\n  }\n}\n\n/**\n * The stop whose point sits nearest `at` on a plot `at.width` by\n * `at.height` px, measured in px, inside `inset` px kept clear at each\n * edge; null with none.\n */\nfunction nearestPlace(\n  points: readonly CartesianPoint[],\n  at: PlotPoint,\n  inset: number,\n  direction: ReadingDirection,\n) {\n  return nearestPoint(\n    points.map((point) => plotPlace(point.place, direction)),\n    {\n      x: placeFromFraction(at.width === 0 ? 0 : at.x / at.width, at.width, inset),\n      y: placeFromFraction(at.height === 0 ? 0 : at.y / at.height, at.height, inset),\n    },\n    {\n      width: Math.max(0, at.width - inset * 2),\n      height: Math.max(0, at.height - inset * 2),\n    },\n  )\n}\n\n/** A fraction of a plot's whole length as a fraction of its inner length, inside `inset` px at each end. */\nfunction placeFromFraction(fraction: number, length: number, inset: number) {\n  const inner = length - inset * 2\n  if (inner <= 0) return 0.5\n  return (fraction * length - inset) / inner\n}\n\n/**\n * The reader of a chart whose plot shows a window of time: its marks sit in\n * a layer the clock moves, so what is under the pointer is read where the\n * layer is now, and a tooltip sits where its mark is on the plot.\n */\nfunction liveReader(\n  reader: ChartReader,\n  live: ChartLive,\n  direction: ReadingDirection,\n): ChartReader {\n  const { browse } = reader\n  if (!browse) return reader\n  // The layer moves toward the reading start: left, or right in right to left.\n  const sign = direction === 'rtl' ? -1 : 1\n  const anchor = (target: ChartTarget) => {\n    const at = browse.anchor(target)\n    return at && { ...at, x: at.x - sign * live.offset() }\n  }\n  // The keys reach only what the plot shows: rows kept past its start, or arrived past its end\n  // while it is held, are out of view.\n  const shown = (target: ChartTarget | null) => {\n    const at = target && anchor(target)\n    return at !== null && at.x >= -1e-6 && at.x <= 1 + 1e-6\n  }\n  const back = direction === 'rtl' ? 'ArrowRight' : 'ArrowLeft'\n  const on = direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight'\n  /** From `target`, stepping `key` while it is out of view, the first in view, or null. */\n  const toView = (target: ChartTarget | null, key: string) => {\n    let at = target\n    for (let steps = 0; at && !shown(at) && steps < browse.stops; steps += 1) {\n      const next = browse.step(at, key)\n      if (!next || next === at) return null\n      at = next\n    }\n    return at && shown(at) ? at : null\n  }\n  return {\n    ...reader,\n    browse: {\n      ...browse,\n      targetAt: (point) =>\n        browse.targetAt({ ...point, x: point.x + sign * live.offset() * point.width }),\n      anchor,\n      start: toView(browse.start, back),\n      step: (from, key) => {\n        const next = browse.step(from, key)\n        if (!next) return null\n        if (key === 'Home') return toView(next, on) ?? from\n        if (key === 'End') return toView(next, back) ?? from\n        return shown(next) ? next : from\n      },\n    },\n  }\n}\n\nexport {\n  type CartesianBrowse,\n  type CartesianPoint,\n  cartesianReader,\n  type CartesianReaderInput,\n  type CartesianStop,\n  liveReader,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-cartesian-reader.ts"
    },
    {
      "path": "registry/lib/chart-cartesian.tsx",
      "content": "'use client'\n\nimport {\n  type ActiveIndexProps,\n  type CategoryChartProps,\n  ChartAxesContext,\n  type ChartAxesValue,\n  type ChartForecast,\n  type ChartFrame,\n  type ChartParts,\n  ChartPartsContext,\n  chartParts,\n  type ChartWords,\n  checkSeries,\n  type EntrancePhase,\n  IndexActive,\n  isForecast,\n  localeTag,\n  rowsShown,\n  SeriesWordsContext,\n  type SeriesWordsInput,\n  useChartActive,\n  useChartLife,\n  useChartLoad,\n  useChartPick,\n  useIndexFocus,\n  useLeavingItems,\n  usePreviousScales,\n  writeDatum,\n} from '@/registry/lib/chart-base'\nimport {\n  type CartesianBrowse,\n  type CartesianPoint,\n  cartesianReader,\n  type CartesianStop,\n  liveReader,\n} from '@/registry/lib/chart-cartesian-reader'\nimport {\n  type CartesianModel,\n  type CartesianX,\n  cartesianModel,\n  type ChartReference,\n  type MarkKind,\n  nearestRow,\n  timeKey,\n  VALUE_AXIS,\n  type ValueAxisOptions,\n} from '@/registry/lib/chart-frame'\nimport { usualGap } from '@/registry/lib/chart-live'\nimport { useLiveClock } from '@/registry/lib/chart-live-clock'\nimport {\n  addsUp,\n  changeSince,\n  type ChartDatum,\n  type ChartMark,\n  type ChartOrientation,\n  type ChartStack,\n  numberOf,\n} from '@/registry/lib/chart-math'\nimport {\n  ChartFrame as RootFrame,\n  type ChartFormat,\n  type ChartItem,\n  type ChartPoint,\n  type ChartRootState,\n  type ChartRootValue,\n  formatterOf,\n  useChartRoot,\n} from '@/registry/lib/chart-root'\nimport type { BandGaps } from '@/registry/lib/chart-scale'\nimport type { ChartStatus, ChartTable } from '@/registry/lib/chart-state'\nimport {\n  onOneDay,\n  readTime,\n  timeLabel,\n  type TimeUnit,\n  timeUnitOf,\n  unitLength,\n  useLocale,\n  useTimeZone,\n  weekStart,\n} from '@/registry/lib/dates'\nimport {\n  type ComponentProps,\n  createContext,\n  type ReactNode,\n  use,\n  useLayoutEffect,\n  useState,\n} from 'react'\n\n/*\n * The cartesian family: the charts whose marks stand between an x axis and\n * one or more value axes, such as bars, lines, areas and points. It keeps\n * the stops along x and the ones leaving, the frame the cartesian model\n * fits to the rows (`chart-frame`), what the parts inside a chart declare,\n * and how values are written, and hands the root the cartesian reader\n * (`chart-cartesian-reader`). Its parts read it with `useCartesian()`. On\n * an x of times, a series' part may bring rows of its own (`data`): the\n * stops are every dataset's times joined, and a series reads only its own.\n */\n\n/* What the parts written inside a chart declare. */\n\n/**\n * What a part written inside a chart tells it before anything draws, so the\n * chart fits its range, reads its forecasts and keeps its room as it renders,\n * on the server as in the browser: the series it draws and as what, the\n * values its axis must reach, and the px it draws past the far end of the\n * value axis. A part says it with a static `declare` of its props.\n */\ninterface ChartPartDeclaration {\n  series?: { key: string; mark: ChartMark }\n  /** The series' own rows, on an x of times, read in place of the chart's: each with the chart's `index` and the series' key. */\n  rows?: readonly ChartDatum[]\n  forecast?: ChartForecast\n  /** Values the axes must reach: `'x'`, or a value axis's id. */\n  references?: readonly ChartReference[]\n  /** The px it draws past the far end of the value axis, worked out from what the chart shows. */\n  room?: (chart: ChartRoomState) => number\n}\n\n/** What a part's room is worked out from: the chart before its scales are made, and the rows it draws. */\ntype ChartRoomState = Pick<\n  ChartRootState,\n  'series' | 'config' | 'hidden' | 'locale' | 'format' | 'textWidth'\n> & {\n  stack: ChartStack\n  orientation: ChartOrientation\n  rows: readonly ChartDatum[]\n  /** The kinds of mark the chart draws, as its options give them. */\n  kinds: CartesianChartOptions['kinds']\n}\n\n/**\n * What tells a declaration apart, but for its room, which is a function,\n * and its rows, which change as data arrives; empty for one that says\n * nothing.\n */\nfunction cartesianSignature(declaration: ChartPartDeclaration) {\n  const { series, forecast, references, room } = declaration\n  if (!series && !forecast && !references?.length && !room) return ''\n  return JSON.stringify([\n    series ?? null,\n    forecast ?? null,\n    references ?? null,\n    room ? 'room' : null,\n  ])\n}\n\n/** What the parts of a chart declared, read by what each says. */\ninterface CartesianParts extends ChartParts<ChartPartDeclaration> {\n  /** The series the parts draw, and as what. */\n  marks: ReadonlyMap<string, ChartMark>\n  /** The rows of each series that brings its own, by its key. */\n  own: ReadonlyMap<string, readonly ChartDatum[]>\n  forecasts: readonly ChartForecast[]\n  references: readonly ChartReference[]\n  /** The room each part keeps, with the series whose rows it is worked out from, or null for the chart's. */\n  rooms: readonly { room: (chart: ChartRoomState) => number; series: string | null }[]\n}\n\n/** What `declarations` say, gathered by kind. */\nfunction cartesianParts(\n  declarations: readonly ChartPartDeclaration[],\n): Omit<CartesianParts, keyof ChartParts<ChartPartDeclaration>> {\n  const marks = new Map<string, ChartMark>()\n  const own = new Map<string, readonly ChartDatum[]>()\n  for (const { series, rows } of declarations) {\n    if (series) marks.set(series.key, series.mark)\n    if (series && rows) own.set(series.key, rows)\n  }\n  return {\n    marks,\n    own,\n    forecasts: declarations.flatMap((part) => (part.forecast ? [part.forecast] : [])),\n    references: declarations.flatMap((part) => part.references ?? []),\n    rooms: declarations.flatMap((part) =>\n      part.room\n        ? [{ room: part.room, series: part.rows ? (part.series?.key ?? null) : null }]\n        : [],\n    ),\n  }\n}\n\n/** What `children` declare, read as the chart renders. */\nfunction useCartesianParts(children: ReactNode): CartesianParts {\n  const declared = chartParts(children, cartesianSignature)\n  return { ...declared, ...cartesianParts(declared.declarations) }\n}\n\n/* The props. */\n\n/** The props a chart on the cartesian frame takes, such as a line chart, beside those every chart takes. */\ninterface CartesianChartProps extends CategoryChartProps {\n  /**\n   * What `index` holds: categories, laid out evenly in the data's order, or\n   * times, each where it falls, so a missing date stays a gap. A time is a\n   * `yyyy-mm-dd` date, a `yyyy-mm` month or a `yyyy-mm-ddTHH:mm[:ss]` date\n   * and time, each the same everywhere, or an instant: an ISO string with\n   * `Z` or an offset, a `Date`, or milliseconds. Rows come in time order.\n   */\n  indexType?: 'category' | 'time'\n  /**\n   * The IANA time zone instants are written in, such as `Europe/London`;\n   * the visitor's own by default, after the page loads, and UTC on the\n   * server. Give one, so the server and the browser agree. Dates and times\n   * with no zone are written as they are.\n   */\n  timeZone?: string\n}\n\n/** The props of a chart on the cartesian frame whose x of times can show a window of them, still or live. */\ninterface LiveChartProps {\n  /**\n   * How much time the plot shows, in ms, of an x of times: the latest, from\n   * the newest row back, or with `live`, from now back. It sets how fast a\n   * live chart scrolls.\n   */\n  window?: number\n  /** The plot's end is now, and it scrolls with the clock: a stream, such as requests per second. Needs a `window`. */\n  live?: boolean\n  /** Holds a live chart still, as hovering or focusing its plot does; rows keep arriving past its end. */\n  paused?: boolean\n}\n\n/** The props of a chart on the cartesian frame that aren't its `<figure>`'s. */\nconst cartesianChartKeys = [\n  'indexType',\n  'timeZone',\n  'window',\n  'live',\n  'paused',\n] as const satisfies readonly (keyof (CartesianChartProps & LiveChartProps))[]\n\n/** A value axis other than the chart's own: how it fits what its series reach, and how it writes and titles its values. */\ninterface NamedValueAxis extends Pick<\n  ValueAxisOptions,\n  'domain' | 'tickCount' | 'zero' | 'align' | 'allowDecimals'\n> {\n  /** How its values are written, on the axis, in the tooltip, the table and what is read out; the chart's `format` by default. */\n  format?: ChartFormat\n  /** What it measures, which titles it unless its `ChartYAxis` is given a `label`. */\n  label?: string\n}\n\ninterface CartesianChartOptions {\n  /** The kinds of mark the chart draws, its own first: a series that names no mark is drawn as that. */\n  kinds: readonly [MarkKind, ...MarkKind[]]\n  orientation: ChartOrientation\n  stack: ChartStack\n  /** Whether the chart's marks play an entrance the first time it comes into view. */\n  entrance: boolean\n  /**\n   * How the marks start one after another in the entrance, such as bars in\n   * a cascade: the CSS variable on the chart that holds the share of their\n   * role's duration they start over, and its default. None when they start\n   * together.\n   */\n  cascade?: { variable: string; fallback: number }\n  /**\n   * The series each row is of, for a chart whose rows each belong to one,\n   * such as a scatter's points: hiding a series takes its rows out, so they\n   * leave as a removed stop does.\n   */\n  seriesOfRow?: (row: ChartDatum) => string\n  /**\n   * What tells each row's stop apart from the rest, its `index` value by\n   * default: a scatter's rows in series of their own may share a name, as\n   * the same month for each team does.\n   */\n  keyOf?: (row: ChartDatum) => string\n  /** The px kept clear inside the plot's edges, on both axes, for marks drawn around a point, such as a scatter's bubbles; none by default. */\n  inset?: number\n  /** Along numbers, the x axis, in place of the categories. */\n  x?: Omit<Extract<CartesianX, { kind: 'number' }>, 'kind'> & {\n    format?: ChartFormat\n    label?: string\n  }\n  /** The chart's own value axis, beside the root's `domain`, `tickCount`, `tickValues` and `allowDecimals`. */\n  y?: Pick<ValueAxisOptions, 'nice' | 'zero' | 'base'> & { label?: string }\n  /** Every other value axis a series names, by its id: how it fits, writes and titles its values. */\n  axes?: Readonly<Record<string, NamedValueAxis>>\n  /** Gaps between the bands of categories, when its bars stand in them. */\n  gaps?: BandGaps\n}\n\n/* What the cartesian parts read. */\n\n/** What `useCartesian()` gives the cartesian parts. */\ninterface CartesianValue {\n  /** Every stop to draw, the leaving ones too, in a fixed order that sorting the data doesn't change. */\n  stops: readonly CartesianStop[]\n  /** The stops still in the data, in order. */\n  current: readonly CartesianStop[]\n  /**\n   * The stops the pointer, the keys, the tooltip and the table reach: the\n   * current ones where a shown series has a row, so a hidden series' own\n   * times hold their place along x without a stop that shows nothing.\n   */\n  browsed: readonly CartesianStop[]\n  orientation: ChartOrientation\n  stack: ChartStack\n  frame: ChartFrame\n  /** The px kept clear inside each edge of the plot, as `--chart-inset`, for marks drawn round a point. */\n  inset: number\n  /** The row a series is drawn from at a stop: its own, or the chart's for a series with none; null where it has none. */\n  rowOf: (series: string, stop: ChartItem) => ChartDatum | null\n  /** A series' value at a stop: a number, a `[from, to]` range, or no value, as where it has no row. */\n  valueOf: (series: string, stop: ChartItem) => unknown\n  /** How a series' value at a stop is written in the tooltip, the data table and what is read out. */\n  seriesText: (stop: ChartItem, series: string) => string\n  /**\n   * The stop of the row a series is read from at `stop`, in the tooltip, in\n   * what is read out and by the lit marks: `stop` where it has a row, else\n   * on an x of times the stop of its nearest own row (`nearestRow`); null\n   * with none near.\n   */\n  nearOf: (series: string, stop: ChartItem) => CartesianStop | null\n  /** A series' value at a stop or near it, for the tooltip and what is read out (`SeriesWordsInput`). */\n  seriesNear: SeriesWordsInput['seriesNear']\n  /**\n   * How much a series' value changed since its row before, as a share of\n   * it, which the tooltip and what is read out give, when there is a stop\n   * `before`; none for a series written as a percent, whose change as a\n   * share of a share would read as points.\n   */\n  seriesChange: (stop: ChartItem, before: ChartItem, series: string) => number | null\n  /** How a stop is named. */\n  stopText: (stop: ChartItem) => string\n  /** The picked stop's key. */\n  selected: string | null\n  /** The entrance has played, or wasn't asked for. */\n  entered: boolean\n  status: ChartStatus\n  /** The stops run in order, such as days, so a change since the one before means something. */\n  ordered: boolean\n  /** What the parts written inside the chart say about themselves, read as it renders. */\n  parts: CartesianParts\n  /** The series whose values from a stop on are projected. */\n  forecasts: readonly ChartForecast[]\n}\n\n/** What the cartesian parts read: the family's value and the root's state. */\ntype CartesianChartValue = CartesianValue & ChartRootState\n\nconst CartesianContext = createContext<CartesianChartValue | null>(null)\n\nfunction useCartesian() {\n  const chart = use(CartesianContext)\n  if (!chart) throw new Error('Chart parts go inside a chart, such as a `BarChart`.')\n  return chart\n}\n\n/** What `useCartesianChart` returns, which a chart hands its frame. */\ninterface CartesianChart {\n  chart: CartesianChartValue\n  placeholder: boolean\n  /** The data arrived as the placeholder went, so the marks grow out of the placeholder's. */\n  fromPlaceholder: boolean\n  phase: EntrancePhase\n  model: CartesianModel\n  /** What the axes, the grid and reference parts read. */\n  axes: ChartAxesValue\n  /** Whether a press picks a stop, and the toggle, by key. */\n  pick: { selectable: boolean; toggle: (key: string) => void }\n  /** The stop under the pointer or the focus, for a chart you control. */\n  active: ActiveIndexProps\n}\n\n/** The rows of a chart that loads or failed: one array, so what compares rows sees no change. */\nconst NO_ROWS: readonly ChartDatum[] = []\n\n/** The own rows at a stop of a chart whose series bring none. */\nconst NO_OWN: Readonly<Record<string, ChartDatum>> = {}\n\n/** The key of the chart's own rows among its datasets, beside each series' own. */\nconst CHART_ROWS = ''\n\n/** A dataset's rows, their times in ms, in order, and their usual gap (`usualGap`). */\ninterface TimedRows {\n  rows: readonly ChartDatum[]\n  times: readonly number[]\n  gap: number | null\n}\n\n/** The chart's rows (`CHART_ROWS`) and each series' own, with their times as the frame read them (`timesOf`). */\nfunction datasetsOf(\n  rows: readonly ChartDatum[],\n  own: Readonly<Record<string, readonly ChartDatum[]>>,\n  timesOf: (series: string | null) => readonly number[],\n): ReadonlyMap<string, TimedRows> {\n  const timed = (rows: readonly ChartDatum[], series: string | null): TimedRows => {\n    const times = timesOf(series)\n    return { rows, times, gap: usualGap(times) }\n  }\n  return new Map([\n    [CHART_ROWS, timed(rows, null)],\n    ...Object.entries(own).map(([key, rows]) => [key, timed(rows, key)] as const),\n  ])\n}\n\nconst NO_DATASETS: ReadonlyMap<string, TimedRows> = new Map()\n\n/**\n * The unit each stop's time is written in: the finest of the datasets with\n * a row there, each as fine as its own times, so a day's bars stay days\n * beside a trend at noon. A dataset of one row takes the axis's `unit`.\n */\nfunction stopUnits(\n  stops: readonly {\n    time: number\n    datum: ChartDatum | null\n    own: Readonly<Record<string, ChartDatum>>\n  }[],\n  datasets: ReadonlyMap<string, TimedRows>,\n  unit: Exclude<TimeUnit, 'week'>,\n  timeZone: string,\n): (time: number) => Exclude<TimeUnit, 'week'> {\n  const units = new Map(\n    [...datasets].map(([key, { times }]) => [\n      key,\n      times.length > 1 ? timeUnitOf(times, timeZone) : unit,\n    ]),\n  )\n  const byTime = new Map(\n    stops.map((stop) => {\n      const keys = [...(stop.datum ? [CHART_ROWS] : []), ...Object.keys(stop.own)]\n      const finest = keys\n        .map((key) => units.get(key) ?? unit)\n        .reduce<Exclude<TimeUnit, 'week'> | null>(\n          (best, each) =>\n            best === null || unitLength(each) < unitLength(best) ? each : best,\n          null,\n        )\n      return [stop.time, finest ?? unit]\n    }),\n  )\n  return (time) => byTime.get(time) ?? unit\n}\n\n/**\n * A cartesian chart: its rows, the frame the cartesian model fits to them,\n * its parts and their declarations, its stops, what is picked and how its\n * values are written. A chart's root adds where its tooltip sits, how it is\n * browsed and what it says, and draws its marks inside\n * `CartesianChartFrame`.\n */\nfunction useCartesianChart(\n  props: CartesianChartProps & LiveChartProps,\n  options: CartesianChartOptions,\n): CartesianChart {\n  const {\n    data,\n    index,\n    config,\n    domain,\n    tickCount,\n    tickValues,\n    allowDecimals,\n    format,\n    ordered = false,\n    activeIndex,\n    defaultActiveIndex = null,\n    onActiveIndexChange,\n  } = props\n  const times = props.indexType === 'time'\n  if (props.window !== undefined && !times) {\n    throw new Error('A `window` is a stretch of time: give `indexType=\"time\"` too.')\n  }\n  if (props.live && props.window === undefined) {\n    throw new Error(\n      'A live chart scrolls through a `window` of time: give one, in ms, such as `window={60_000}`.',\n    )\n  }\n  if (times && options.x) {\n    throw new Error('A chart whose x is a number of its own takes no `indexType`.')\n  }\n  if (times && options.orientation === 'horizontal') {\n    throw new Error(\n      'Lying bars take categories down the side, not times: give `indexType=\"time\"` to upright bars.',\n    )\n  }\n  const timeZone = useTimeZone(props.timeZone)\n  // The week starts on the same day on the server and on the first paint in the browser.\n  const firstDay = weekStart(useLocale(localeTag(props.locale)))\n  const state = useChartRoot(props, { entrance: options.entrance, heightFromData: false })\n  const { moves, plotSize, hidden, series } = state\n  const load = useChartLoad(props)\n  const loaded = load.placeholder || load.failed ? NO_ROWS : data\n  const shownRows = options.seriesOfRow\n    ? rowsShown(loaded, options.seriesOfRow, hidden)\n    : loaded\n  const shown = series.filter((key) => !hidden.includes(key))\n  const parts = useCartesianParts(props.children)\n  const keyOf = times\n    ? (row: ChartDatum) => timeKey(row[index])\n    : (options.keyOf ?? ((row: ChartDatum) => String(row[index])))\n  const waiting = load.placeholder || load.failed\n  const ownLoaded = new Map(\n    [...parts.own].map(([key, rows]) => [key, waiting ? NO_ROWS : rows]),\n  )\n  // A window keeps the rows each dataset lets go while they still show, so its line runs on to\n  // the plot's start; nothing while it loads or failed.\n  const clock = useLiveClock({\n    window: props.window ?? null,\n    live: props.live ?? false,\n    paused: props.paused ?? false,\n    datasets: [\n      { key: CHART_ROWS, rows: shownRows },\n      ...[...ownLoaded].map(([key, rows]) => ({ key, rows })),\n    ],\n    timeOf: (row) => readTime(row[index])?.time ?? Number.NaN,\n    root: state.root,\n    plot: state.plot,\n    direction: state.direction,\n  })\n  const drawn = waiting ? shownRows : (clock.datasets.get(CHART_ROWS) ?? NO_ROWS)\n  const own: Record<string, readonly ChartDatum[]> = Object.fromEntries(\n    [...ownLoaded].map(([key, rows]) => [\n      key,\n      waiting ? rows : (clock.datasets.get(key) ?? NO_ROWS),\n    ]),\n  )\n  checkSeries(config, parts.marks, options.kinds[0].mark)\n  const numbersAlong = options.x !== undefined\n  // A value given for an x of categories or times marks the value axis.\n  const references = parts.references.map((ref) =>\n    ref.axis === 'x' && !numbersAlong ? { ...ref, axis: VALUE_AXIS } : ref,\n  )\n  const roomState: ChartRoomState = {\n    ...state,\n    rows: drawn,\n    stack: options.stack,\n    orientation: options.orientation,\n    kinds: options.kinds,\n  }\n  // A part with rows of its own works its room out from them.\n  const room = Math.max(\n    0,\n    ...parts.rooms.map((part) =>\n      part.room(\n        part.series === null\n          ? roomState\n          : { ...roomState, rows: own[part.series] ?? NO_ROWS },\n      ),\n    ),\n  )\n  const valueLength =\n    options.orientation === 'vertical' ? plotSize.height : plotSize.width\n  const model = cartesianModel({\n    rows: drawn,\n    own,\n    config,\n    hidden,\n    kinds: options.kinds,\n    stack: options.stack,\n    x: options.x\n      ? { kind: 'number', ...options.x }\n      : times\n        ? {\n            kind: 'time',\n            key: index,\n            timeZone,\n            firstDay,\n            gaps: options.gaps,\n            window: clock.scaleWindow,\n          }\n        : { kind: 'category', keys: drawn.map(keyOf), gaps: options.gaps },\n    y: { domain, tickCount, tickValues, allowDecimals, ...options.y },\n    axes: options.axes,\n    references,\n    room: { px: room, length: valueLength },\n  })\n  const x = model.x\n  const current: CartesianStop[] = model.timeStops\n    ? model.timeStops.map((stop, at) => ({\n        key: stop.key,\n        value: stop.value,\n        datum: stop.datum,\n        own: stop.own,\n        index: at,\n        band: model.bandOf(at),\n        leaving: false,\n      }))\n    : drawn.map((datum, at) => ({\n        key: keyOf(datum),\n        value: datum[index],\n        datum,\n        own: NO_OWN,\n        index: at,\n        band: model.bandOf(at),\n        leaving: false,\n      }))\n  const stops = useLeavingItems(moves, current, stopKey)\n  const previousY = usePreviousScales(model.y)\n  const previousX = usePreviousScales({ x }).x ?? x\n  const frame: ChartFrame = {\n    x: {\n      scale: x,\n      previous: previousX,\n      format: options.x?.format,\n      label: options.x?.label,\n    },\n    y: {\n      ...Object.fromEntries(\n        Object.entries(model.y).map(([axis, scale]) => [\n          axis,\n          {\n            scale,\n            previous: previousY[axis] ?? scale,\n            format: options.axes?.[axis]?.format,\n            label: options.axes?.[axis]?.label,\n          },\n        ]),\n      ),\n      value: {\n        scale: model.y.value,\n        previous: previousY.value ?? model.y.value,\n        label: options.y?.label,\n      },\n    },\n    baselines: model.baselines,\n    axisOf: model.axisOf,\n    totals: model.totals,\n    measuring: room > 0 && valueLength <= 0 && drawn.length > 0,\n    live: clock.live,\n  }\n  // Each dataset's times, in order, which the words read a series' rows near a stop from.\n  const datasets = model.timesOf ? datasetsOf(drawn, own, model.timesOf) : NO_DATASETS\n  const timeline = model.timeStops\n  // A row's time is written as fine as the times of the datasets with a row there are, and\n  // on one day, as its time of day alone.\n  const oneDay =\n    x.kind === 'time' &&\n    onOneDay(\n      current.flatMap((stop) => readTime(stop.value)?.time ?? []),\n      x.timeZone,\n    )\n  const unitAt =\n    x.kind === 'time' && timeline\n      ? stopUnits(timeline, datasets, x.unit, x.timeZone)\n      : null\n  const nameText =\n    props.categoryFormat ??\n    (x.kind === 'time'\n      ? (value: unknown) => {\n          const read = readTime(value)\n          return read\n            ? timeLabel(\n                read.time,\n                unitAt?.(read.time) ?? x.unit,\n                props.locale,\n                x.timeZone,\n                oneDay,\n              )\n            : String(value)\n        }\n      : String)\n  const { status, fromPlaceholder, phase, entered } = useChartLife(\n    props,\n    state,\n    load,\n    // The rows a window keeps count as the data's; empty only with no row in any dataset.\n    {\n      rows:\n        (drawn === shownRows ? loaded.length : drawn.length) +\n        Object.values(own).reduce((all, rows) => all + rows.length, 0),\n      shown: shown.length,\n      drawn: model.count,\n    },\n    { entrance: options.entrance, cascade: options.cascade ?? null },\n  )\n  const pick = useChartPick(\n    props,\n    current.map((stop) => stop.key),\n  )\n  const { messages, valueText } = state\n  // A series reads in its value axis's own format, where it has one.\n  const writers = new Map<string, (value: number) => string>()\n  const writerOf = (key: string) => {\n    const axis = frame.axisOf(key)\n    const own = frame.y[axis]?.format\n    if (own === undefined) return valueText\n    const made = writers.get(axis) ?? formatterOf(state.locale, own)\n    writers.set(axis, made)\n    return made\n  }\n  // A series with rows of its own reads them at each stop, the leaving ones too; every other\n  // series reads the chart's.\n  const byKey = new Map(stops.map((stop) => [stop.key, stop]))\n  const rowOf = (key: string, stop: ChartItem): ChartDatum | null =>\n    Object.hasOwn(own, key) ? (byKey.get(stop.key)?.own[key] ?? null) : stop.datum\n  const valueOf = (key: string, stop: ChartItem) => rowOf(key, stop)?.[key]\n  const seriesText = (stop: ChartItem, key: string) =>\n    writeDatum(valueOf(key, stop), writerOf(key), messages.noValue)\n  // On an x of times, the row a series reads at a stop in words: its row there, or its own\n  // nearest (`nearestRow`) with the stop that row is at; null with none near.\n  const chartGap = datasets.get(CHART_ROWS)?.gap ?? null\n  const stopAt = new Map(timeline?.map((stop, at) => [stop.time, current[at]!]))\n  const readNear = (key: string, stop: ChartItem) => {\n    const time = timeline?.[stop.index]?.time\n    const dataset = datasets.get(Object.hasOwn(own, key) ? key : CHART_ROWS)\n    if (time === undefined || !dataset) return null\n    const at = nearestRow(dataset.times, time, { own: dataset.gap, chart: chartGap })\n    const near = at === null ? undefined : stopAt.get(dataset.times[at]!)\n    if (at === null || !near) return null\n    return { row: dataset.rows[at] ?? null, before: dataset.rows[at - 1] ?? null, near }\n  }\n  const browsed =\n    Object.keys(own).length === 0\n      ? current\n      : current.filter((stop) => shown.some((key) => rowOf(key, stop) !== null))\n  const nearOf = (key: string, stop: ChartItem) =>\n    timeline ? (readNear(key, stop)?.near ?? null) : (current[stop.index] ?? null)\n  const chart: CartesianChartValue = {\n    ...state,\n    stops,\n    current,\n    browsed,\n    orientation: options.orientation,\n    stack: options.stack,\n    frame,\n    inset: options.inset ?? 0,\n    rowOf,\n    valueOf,\n    nearOf,\n    seriesText,\n    // Along categories or numbers every stop is a row of the chart's.\n    seriesNear: (stop, key) => {\n      if (!timeline) {\n        // A row that leaves a series' key out has none of it at this stop, as a pace has only\n        // on the day still coming in: no line in the tooltip or the table. Null is a missing value.\n        const row = rowOf(key, stop)\n        if (row !== null && !Object.hasOwn(row, key)) return null\n        return { text: seriesText(stop, key), at: null }\n      }\n      const read = readNear(key, stop)\n      if (!read) return null\n      return read.near.key === stop.key\n        ? { text: seriesText(stop, key), at: null }\n        : {\n            text: writeDatum(read.row?.[key], writerOf(key), messages.noValue),\n            at: nameText(read.near.value),\n          }\n    },\n    seriesChange: (stop, before, key) => {\n      const written = frame.y[frame.axisOf(key)]?.format ?? format\n      if (typeof written === 'object' && written.style === 'percent') return null\n      if (!timeline) return changeSince(valueOf(key, stop), valueOf(key, before))\n      // A series compares its own rows: the one it reads here, and the one before that.\n      const read = readNear(key, stop)\n      return read ? changeSince(read.row?.[key], read.before?.[key]) : null\n    },\n    stopText: (stop) => nameText(stop.value),\n    selected: pick.picked,\n    entered,\n    status,\n    ordered,\n    parts,\n    forecasts: parts.forecasts,\n  }\n  return {\n    chart,\n    placeholder: load.placeholder,\n    fromPlaceholder,\n    phase,\n    model,\n    axes: cartesianAxes(chart, model, nameText),\n    pick: { selectable: pick.selectable, toggle: pick.toggle },\n    active: { activeIndex, defaultActiveIndex, onActiveIndexChange },\n  }\n}\n\nfunction stopKey(stop: CartesianStop) {\n  return stop.key\n}\n\n/**\n * What the shared axes, grid and reference parts read of a cartesian chart:\n * its frame; the stops along x when it names them, upright bars or lines\n * over categories or times, or down the side for lying bars; and every value\n * a reference at a summary reads.\n */\nfunction cartesianAxes(\n  chart: CartesianChartValue,\n  model: CartesianModel,\n  nameText: (value: unknown) => string,\n): ChartAxesValue {\n  const { frame, orientation, current, stops, series, hidden, stack } = chart\n  const keys = current.map((stop) => stop.key)\n  const named = {\n    all: stops,\n    current,\n    nameOf: (target: { kind: string; key?: string }) => {\n      const at = target.key === undefined ? -1 : keys.indexOf(target.key)\n      return at === -1 ? null : at\n    },\n    format: nameText,\n    keepInside: true,\n  }\n  const numbersAlong = frame.x.scale.kind === 'linear'\n  return {\n    frame,\n    orientation,\n    inset: chart.inset,\n    names: {\n      x: !numbersAlong && orientation === 'vertical' ? named : null,\n      y: !numbersAlong && orientation === 'horizontal' ? named : null,\n    },\n    summaryValues: (axis) => {\n      // Points placed by both values each have a value on either axis.\n      if (numbersAlong) {\n        return current.map((stop) => {\n          const point = model.point(stop.index)?.value\n          return point ? (axis === 'x' ? point.x : point.y) : null\n        })\n      }\n      // Only the series read against the axis.\n      const onAxis = series.filter(\n        (key) => !hidden.includes(key) && frame.axisOf(key) === axis,\n      )\n      if (!addsUp(stack)) {\n        return current.flatMap((stop) => onAxis.map((key) => chart.valueOf(key, stop)))\n      }\n      // A stop's sum adds the series that share the chart's rows, where it has a row of the chart's;\n      // a series with rows of its own stacks with nothing, so its values count one by one.\n      const ownRows = onAxis.filter((key) => chart.parts.own.has(key))\n      const shared = onAxis.filter((key) => !chart.parts.own.has(key))\n      return current.flatMap((stop) => [\n        ...(stop.datum && shared.length > 0\n          ? [\n              shared.reduce(\n                (sum, key) => sum + (numberOf(chart.valueOf(key, stop)) ?? 0),\n                0,\n              ),\n            ]\n          : []),\n        ...ownRows.map((key) => chart.valueOf(key, stop)),\n      ])\n    },\n    percent: stack === 'expand',\n  }\n}\n\n/* What a cartesian chart says. */\n\n/**\n * The words of a cartesian chart as `seriesWords` reads them: its stops,\n * each series' value as the chart writes it, the total of what stacks on\n * the chart's own value axis, and the chart's `own` words, or null.\n */\nfunction cartesianWords(\n  chart: CartesianChartValue,\n  own: SeriesWordsInput['own'],\n): SeriesWordsInput {\n  const shown = chart.series.filter((key) => !chart.hidden.includes(key))\n  // Only what stacks adds up, never a line or a point beside it or a series on another axis.\n  const summed = shown.filter((key) => chart.frame.totals(key))\n  return {\n    stops: chart.browsed,\n    seriesText: chart.seriesText,\n    seriesNear: chart.seriesNear,\n    seriesChange: chart.seriesChange,\n    stopText: chart.stopText,\n    ordered: chart.ordered,\n    // A stop where only a series' own rows are has nothing stacked to add up.\n    totals: (stop) =>\n      summed.length > 1 && stop.datum !== null\n        ? summed.reduce((all, key) => all + (numberOf(chart.valueOf(key, stop)) ?? 0), 0)\n        : null,\n    totalByDefault: addsUp(chart.stack),\n    forecast: (series, stop) => isForecast(chart, series, stop.index),\n    picked: chart.selected,\n    alone: null,\n    own,\n  }\n}\n\n/** The data table of a chart that writes its own: a row for each stop, under `columns`, with `cells` of each. */\nfunction cartesianTable(\n  chart: CartesianChartValue,\n  columns: readonly string[],\n  cells: (stop: CartesianStop) => readonly string[],\n): ChartTable {\n  return {\n    header: chart.messages.category,\n    columns,\n    rows: chart.current.map((stop) => ({\n      key: stop.key,\n      name: chart.stopText(stop),\n      cells: cells(stop),\n    })),\n    footer: [],\n  }\n}\n\n/* The frame. */\n\ninterface CartesianChartFrameProps extends Omit<ComponentProps<'figure'>, 'children'> {\n  chart: CartesianChart\n  slot: string\n  description?: string\n  /** What shows while the data loads; nothing once it has. */\n  placeholder: ReactNode\n  empty?: ReactNode\n  /** A series' marker shape for its legend swatch (the Scatter's, the Composed chart's), or null. */\n  markerOf: (series: string) => string | null\n  /** Where the tooltip of a stop sits, and its side; `series` for a target on one series. */\n  anchor: (stop: CartesianStop, series: string | null) => ChartPoint | null\n  words: ChartWords\n  /** How the pointer and the keys move among the stops; the frame keeps the axis a scatter's keys last moved along. */\n  browse:\n    | Extract<CartesianBrowse, { kind: 'x' | 'x-series' }>\n    | {\n        kind: 'points'\n        point: (stop: CartesianStop) => CartesianPoint | null\n        inset: number\n      }\n  children: ReactNode\n}\n\n/**\n * The `<figure>` of a cartesian chart, on the root's frame: the chart's\n * reader and focus from its stops, a live chart's clock, the parts written\n * inside it, and the chart's placeholder while it loads.\n */\nfunction CartesianChartFrame({\n  chart: cartesian,\n  slot,\n  description,\n  placeholder,\n  empty,\n  markerOf,\n  anchor,\n  words,\n  browse,\n  children,\n  ...props\n}: CartesianChartFrameProps) {\n  const { chart, axes, pick, active } = cartesian\n  // The axis the last arrow stepped along among points, which the slider's value counts on.\n  const [along, setAlong] = useState<'x' | 'y'>('x')\n  const live = chart.frame.live\n  const own = cartesianReader({\n    current: chart.browsed,\n    browse: browse.kind === 'points' ? { ...browse, along, onAlong: setAlong } : browse,\n    orientation: chart.orientation,\n    direction: chart.direction,\n    anchor,\n    words,\n    // A window opens at its end, so the keys start there too.\n    start: live ? 'last' : 'first',\n    series: chart.series,\n    hidden: chart.hidden,\n  })\n  const reader = live ? liveReader(own, live, chart.direction) : own\n  const keys = chart.current.map((stop) => stop.key)\n  const root: ChartRootValue = {\n    ...chart,\n    reader,\n    markerOf,\n    selectable: pick.selectable,\n    picked: chart.selected === null ? null : { kind: 'x', key: chart.selected },\n    togglePicked: (target) => {\n      if (target.kind !== 'node' && keys.includes(target.key)) pick.toggle(target.key)\n    },\n  }\n  const { focusProps, toldRef } = useIndexFocus(reader.items, active)\n  return (\n    <RootFrame\n      root={root}\n      focus={focusProps}\n      slot={slot}\n      description={description}\n      empty={empty}\n      measuring={chart.frame.measuring}\n      inset={chart.inset}\n      data-orientation={chart.orientation}\n      {...props}\n    >\n      <CartesianContext value={chart}>\n        <ChartPartsContext value={chart.parts}>\n          <ChartAxesContext value={axes}>\n            <SeriesWordsContext value={cartesianWords(chart, null)}>\n              <IndexActive items={reader.items} active={active} toldRef={toldRef}>\n                {live && <LiveHold hold={live.hold} />}\n                {children}\n                {placeholder}\n              </IndexActive>\n            </SeriesWordsContext>\n          </ChartAxesContext>\n        </ChartPartsContext>\n      </CartesianContext>\n    </RootFrame>\n  )\n}\n\n/** Holds a live plot still while anything on it is lit, by the pointer or the keys, so it can be read. */\nfunction LiveHold({ hold }: { hold: (held: boolean) => void }) {\n  const lit = useChartActive().spotlit !== null\n  useLayoutEffect(() => {\n    hold(lit)\n  }, [hold, lit])\n  return null\n}\n\nexport {\n  type CartesianChart,\n  CartesianChartFrame,\n  type CartesianChartFrameProps,\n  type CartesianChartOptions,\n  type CartesianChartProps,\n  type CartesianChartValue,\n  cartesianChartKeys,\n  type CartesianParts,\n  cartesianParts,\n  type CartesianPoint,\n  cartesianSignature,\n  type CartesianStop,\n  cartesianTable,\n  type CartesianValue,\n  cartesianWords,\n  type ChartPartDeclaration,\n  type ChartRoomState,\n  datasetsOf,\n  type LiveChartProps,\n  type NamedValueAxis,\n  stopUnits,\n  useCartesian,\n  useCartesianChart,\n  useCartesianParts,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-cartesian.tsx"
    },
    {
      "path": "registry/lib/chart-list.tsx",
      "content": "'use client'\n\nimport {\n  type ActiveIndexProps,\n  type CategoryChartProps,\n  writeDatum,\n  IndexActive,\n  useChartLife,\n  useChartLoad,\n  useChartPick,\n  useIndexFocus,\n  useLeavingItems,\n} from '@/registry/lib/chart-base'\nimport type { ListStop } from '@/registry/lib/chart-list-reader'\nimport type { ChartDatum } from '@/registry/lib/chart-math'\nimport {\n  ChartFrame,\n  type ChartReader,\n  type ChartRootState,\n  type ChartRootValue,\n  useChartRoot,\n} from '@/registry/lib/chart-root'\nimport { type ChartStatus, indexOfKey } from '@/registry/lib/chart-state'\nimport type { ComponentProps, ReactNode, Ref } from 'react'\n\n/*\n * What the charts whose stops are a list share on the root: the Donut, the\n * Radial chart and the Radar. Each row of the data is a stop, kept by its\n * key while it leaves, and the chart hands the root a list reader\n * (`chart-list-reader`) for them. The chart draws its own marks and works\n * out its own words; this keeps the rest the same for every one of them.\n */\n\n/** A stop to draw: still in the data, or leaving it, where it keeps its last place. */\ntype ListChartStop = ListStop & { datum: ChartDatum; leaving: boolean }\n\n/** What a list chart keeps before it draws its marks. */\ninterface ListChart {\n  state: ChartRootState\n  /** The rows of the data, none while it loads or failed. */\n  rows: readonly ChartDatum[]\n  /** The rows still drawn with the hidden series hidden. */\n  drawn: readonly ChartDatum[]\n  /** The series not hidden. */\n  shown: readonly string[]\n  /** The stops still in the data, in its order. */\n  current: readonly (ListStop & { datum: ChartDatum })[]\n  /** Every stop to draw, the leaving ones too, in a fixed order that sorting the data doesn't change. */\n  stops: readonly ListChartStop[]\n  status: ChartStatus\n  /** The placeholder shows while the data loads. */\n  placeholder: boolean\n  /** The entrance is playing. */\n  entering: boolean\n  /** The entrance has played, or wasn't asked for. */\n  entered: boolean\n  /** The key of the stop picked, or null. */\n  picked: string | null\n  selectable: boolean\n  /** Picks the stop keyed `key`, or lets it go if it was picked. */\n  togglePicked: (key: string) => void\n  activeProps: ActiveIndexProps\n  /** How a stop is named: the chart's `categoryFormat`, or `String`. */\n  stopText: (value: unknown) => string\n  /** Anything under a series' key as the chart writes it: a number, a `[from, to]` range, or no value. */\n  datumText: (value: unknown) => string\n}\n\n/** What the frame of a chart whose stops are held by key reads of it: a list chart's, or the Waffle's, whose remaining room is a stop with no row. */\ntype ListChartRoot = Pick<\n  ListChart,\n  'state' | 'status' | 'drawn' | 'selectable' | 'picked' | 'togglePicked' | 'activeProps'\n>\n\n/** The rows of a chart that loads or failed: one array, so what compares rows sees no change. */\nconst NO_ROWS: readonly ChartDatum[] = []\n\n/**\n * A list chart's root state, its rows and its stops, what it shows, where\n * its entrance is and what is picked. With `rowsAreSeries`, each row is a\n * series of its own under the chart's `index`, as a donut's slices are, so\n * hiding the series takes its row out.\n */\nfunction useListChart(\n  props: CategoryChartProps,\n  { entrance, rowsAreSeries }: { entrance: boolean; rowsAreSeries: boolean },\n): ListChart {\n  const { data, index, categoryFormat = String } = props\n  const state = useChartRoot(props, { entrance, heightFromData: false })\n  const load = useChartLoad(props)\n  const rows = load.placeholder || load.failed ? NO_ROWS : data\n  const keyOf = (row: ChartDatum) => String(row[index])\n  const drawn = rowsAreSeries\n    ? rows.filter((row) => !state.hidden.includes(keyOf(row)))\n    : rows\n  const shown = state.series.filter((key) => !state.hidden.includes(key))\n  const current = drawn.map((datum, at) => ({\n    key: keyOf(datum),\n    value: datum[index],\n    datum,\n    index: at,\n  }))\n  const stops = useLeavingItems(state.moves, current, stopKey)\n  const { status, phase, entered } = useChartLife(\n    props,\n    state,\n    load,\n    { rows: rows.length, shown: shown.length, drawn: drawn.length },\n    { entrance, cascade: null },\n  )\n  const keys = current.map(stopKey)\n  const pick = useChartPick(props, keys)\n  return {\n    state,\n    rows,\n    drawn,\n    shown,\n    current,\n    stops,\n    status,\n    placeholder: load.placeholder,\n    entering: phase === 'entering',\n    entered,\n    picked: pick.picked,\n    selectable: pick.selectable,\n    togglePicked: (key) => {\n      if (indexOfKey(keys, key) !== null) pick.toggle(key)\n    },\n    activeProps: {\n      activeIndex: props.activeIndex,\n      defaultActiveIndex: props.defaultActiveIndex ?? null,\n      onActiveIndexChange: props.onActiveIndexChange,\n    },\n    stopText: categoryFormat,\n    datumText: (value) => writeDatum(value, state.valueText, state.messages.noValue),\n  }\n}\n\nfunction stopKey(stop: { key: string }) {\n  return stop.key\n}\n\n/**\n * The `<figure>` of a list chart, on the root's frame: its reader, the focus\n * by the stops' places for `activeIndex`, its marks and its placeholder.\n */\nfunction ListChartFrame({\n  chart,\n  reader,\n  slot,\n  description,\n  empty,\n  measuring,\n  placeholder,\n  children,\n  ...props\n}: Omit<ComponentProps<'figure'>, 'ref'> & {\n  chart: ListChartRoot\n  reader: ChartReader\n  slot: string\n  description?: string\n  empty?: ReactNode\n  /**\n   * Whether the chart's range needs its plot's size. It waits for it unseen,\n   * as `ChartFrame` does, only while it has rows to draw: the placeholder,\n   * no data and the error show at once.\n   */\n  measuring: boolean\n  placeholder: ReactNode\n  ref?: Ref<HTMLElement>\n}) {\n  const root: ChartRootValue = {\n    ...chart.state,\n    status: chart.status,\n    reader,\n    markerOf: () => null,\n    selectable: chart.selectable,\n    picked: chart.picked === null ? null : { kind: 'x', key: chart.picked },\n    togglePicked: (target) => {\n      if (target.kind !== 'node') chart.togglePicked(target.key)\n    },\n  }\n  const { focusProps, toldRef } = useIndexFocus(reader.items, chart.activeProps)\n  return (\n    <ChartFrame\n      root={root}\n      focus={focusProps}\n      slot={slot}\n      description={description}\n      empty={empty}\n      measuring={measuring && chart.drawn.length > 0}\n      inset={0}\n      {...props}\n    >\n      <IndexActive items={reader.items} active={chart.activeProps} toldRef={toldRef}>\n        {children}\n        {placeholder}\n      </IndexActive>\n    </ChartFrame>\n  )\n}\n\nexport {\n  type ListChart,\n  ListChartFrame,\n  type ListChartRoot,\n  type ListChartStop,\n  useListChart,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-list.tsx"
    },
    {
      "path": "registry/lib/chart-list-reader.ts",
      "content": "import {\n  type ChartOrientation,\n  type ReadingDirection,\n  sliderValue,\n  stepIndex,\n} from '@/registry/lib/chart-math'\nimport type {\n  ChartItem,\n  ChartPoint,\n  ChartReader,\n  PlotPoint,\n} from '@/registry/lib/chart-root'\nimport {\n  type ChartTable,\n  type ChartTarget,\n  indexOfKey,\n  targetSeries,\n} from '@/registry/lib/chart-state'\nimport type { ReactNode } from 'react'\n\n/*\n * The reader of a chart whose stops are a list in order: a donut's slices, a\n * radial chart's rings, a radar's spokes, a waffle's categories. The keys\n * walk the list round or straight, and on a chart whose stops hold several\n * series, Up and Down step between them. Pure, so it is tested on its own.\n */\n\n/** One thing the keys stop at: a slice, a ring, a spoke, a waffle's category. Its `index` is its place among the stops still in the data. */\ntype ListStop = ChartItem\n\n/** How the arrows walk the list. */\ntype ListWalk =\n  /** Donut, Radar: Right and Up go on (clockwise), Left and Down back, in either reading direction, as the marks aren't mirrored. */\n  | { kind: 'round' }\n  /** Radial, Waffle: along the orientation, mirrored in right to left. */\n  | { kind: 'straight'; orientation: ChartOrientation }\n\n/** Whether Up and Down move between series on a stop. */\ntype ListSeries =\n  | { kind: 'none' }\n  /**\n   * Radar: the series Up (`step` -1) or Down (1) brings forward from `from`\n   * on the stop at `stop`, or null for none. The pointer's series is always\n   * null, so pointing at a stop never lights a series.\n   */\n  | {\n      kind: 'step'\n      step: (stop: number, from: string | null, step: -1 | 1) => string | null\n      /** The series not hidden, which a stop's series target may bring forward. */\n      shown: readonly string[]\n    }\n\n/** What a list chart says of its stops: to a screen reader, in the tooltip, and as the data table. */\ninterface ListWords {\n  describe: (stop: ListStop) => string\n  tooltip: (stop: ListStop) => ReactNode\n  table: ChartTable\n}\n\ninterface ListReaderInput {\n  /** The stops still in the data, in order. */\n  current: readonly ListStop[]\n  walk: ListWalk\n  series: ListSeries\n  direction: ReadingDirection\n  /** The stop under the pointer, by its place in `current`, or null. */\n  hit: (point: PlotPoint) => number | null\n  /** Where the stop's tooltip sits, or null before the plot is measured. */\n  anchor: (stop: ListStop) => ChartPoint | null\n  words: ListWords\n}\n\n/** The reader of a chart whose stops are a list: each stop is held by its key, as an `x` target, or with a series as a `datum` one. */\nfunction listReader(input: ListReaderInput): ChartReader {\n  const { current, walk, series, direction, words } = input\n  const keys = current.map((stop) => stop.key)\n  const count = keys.length\n  // Round the circle, Right steps clockwise, the way the marks run, as they aren't mirrored in\n  // right to left; the round marks run like upright bars.\n  const orientation: ChartOrientation =\n    walk.kind === 'round' ? 'vertical' : walk.orientation\n  const reading: ReadingDirection = walk.kind === 'round' ? 'ltr' : direction\n  const indexOf = (target: ChartTarget) =>\n    target.kind === 'node' ? null : indexOfKey(keys, target.key)\n  const stopOf = (target: ChartTarget) => {\n    const index = indexOf(target)\n    return index === null ? null : (current[index] ?? null)\n  }\n  const at = (index: number | null, lit: string | null): ChartTarget | null => {\n    const key = index === null ? undefined : keys[index]\n    if (key === undefined) return null\n    return lit === null ? { kind: 'x', key } : { kind: 'datum', series: lit, key }\n  }\n  return {\n    holds: (target) => {\n      if (indexOf(target) === null) return false\n      if (target.kind === 'x') return true\n      return (\n        target.kind === 'datum' &&\n        series.kind === 'step' &&\n        series.shown.includes(target.series)\n      )\n    },\n    lights: targetSeries,\n    item: stopOf,\n    items: keys.map((key) => ({ kind: 'x', key })),\n    browse: {\n      targetAt: (point) => at(input.hit(point), null),\n      start: at(0, null),\n      step: (from, key) => {\n        const index = indexOf(from)\n        if (index === null) return null\n        const lit = targetSeries(from)\n        if (series.kind === 'step' && (key === 'ArrowUp' || key === 'ArrowDown')) {\n          return at(index, series.step(index, lit, key === 'ArrowUp' ? -1 : 1))\n        }\n        return at(stepIndex(key, index, count, orientation, reading), lit)\n      },\n      rank: (target) =>\n        sliderValue(indexOf(target) ?? 0, Math.max(1, count), orientation),\n      stops: count,\n      // The slider runs across the stops: across the page for those that run like upright bars.\n      orientation: orientation === 'vertical' ? 'horizontal' : 'vertical',\n      anchor: (target) => {\n        const stop = stopOf(target)\n        return stop ? input.anchor(stop) : null\n      },\n      describe: (target) => {\n        const stop = stopOf(target)\n        return stop ? words.describe(stop) : ''\n      },\n      tooltip: (target) => {\n        const stop = stopOf(target)\n        return stop ? words.tooltip(stop) : null\n      },\n      table: words.table,\n      open: () => null,\n      back: null,\n    },\n  }\n}\n\nexport {\n  type ListReaderInput,\n  type ListSeries,\n  type ListStop,\n  type ListWalk,\n  type ListWords,\n  listReader,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-list-reader.ts"
    },
    {
      "path": "registry/lib/chart-tree-reader.ts",
      "content": "import {\n  type ChartDatum,\n  type ReadingDirection,\n  stepIndex,\n} from '@/registry/lib/chart-math'\nimport type {\n  ChartItem,\n  ChartPoint,\n  ChartReader,\n  PlotPoint,\n} from '@/registry/lib/chart-root'\nimport type { ChartTable, ChartTarget } from '@/registry/lib/chart-state'\nimport type { ReactNode } from 'react'\n\n/*\n * The tree family's reader: charts whose marks are the nodes of a tree, such\n * as a treemap's tiles. Each node in view is a stop the keys step through in\n * the order the chart gives, depth first, and a group's own place, such as a\n * treemap's header, brings its group forward without being a stop.\n */\n\n/** A node the keys and the tooltip stop at: a tile, an arc, a circle. */\ninterface TreeStop {\n  /** Its key path, joined as `chart-tiles` joins it: unique in the tree. */\n  id: string\n  /** How it is named, in the tooltip and to a screen reader. */\n  name: string\n  value: number\n  datum: ChartDatum\n  /** Its place among the stops, in the order the keys walk. */\n  index: number\n}\n\n/** What is under the pointer: a stop, a group's own place (a treemap's group header), or nothing. */\ntype TreeHit = { kind: 'stop'; index: number } | { kind: 'group'; key: string } | null\n\ninterface TreeReaderInput {\n  /** The nodes in view in the order the keys walk: depth first, a parent before its children. */\n  stops: readonly TreeStop[]\n  direction: ReadingDirection\n  hit: (point: PlotPoint) => TreeHit\n  /** What a press at the point zooms to, or null. */\n  openAt: (point: PlotPoint) => (() => void) | null\n  /** What Enter or Space on the stop zooms to, or null. */\n  open: (stop: TreeStop) => (() => void) | null\n  /** Escape once nothing is lit: zoom out one level, or null at the whole. */\n  back: (() => void) | null\n  anchor: (stop: TreeStop) => ChartPoint | null\n  words: {\n    describe: (stop: TreeStop) => string\n    tooltip: (stop: TreeStop) => ReactNode\n    table: ChartTable\n  }\n}\n\n/** What starts a group's own target id: a character no key path holds, so it never meets a stop's. */\nconst GROUP = '\\u0000group:'\n\n/** The target id of the group keyed `key`'s own place, such as a treemap's header. */\nfunction groupTarget(key: string): string {\n  return `${GROUP}${key}`\n}\n\n/** The key of the group whose own place `target` is, or null for any other target. */\nfunction groupOf(target: ChartTarget): string | null {\n  return target.kind === 'node' && target.id.startsWith(GROUP)\n    ? target.id.slice(GROUP.length)\n    : null\n}\n\n/** What the chart's parts read of a stop, such as its tooltip's heading. */\nfunction treeItem(stop: TreeStop): ChartItem {\n  return { key: stop.id, value: stop.name, datum: stop.datum, index: stop.index }\n}\n\nfunction stopTarget(stop: TreeStop): ChartTarget {\n  return { kind: 'node', id: stop.id }\n}\n\n/**\n * The reader of a chart of a tree: each stop is a node target held by its\n * id. The arrows step through the stops in order, as a slider's do, Home\n * and End go to the first and last, Enter and Space open, Escape goes back.\n * A group's own place lights its group and is never a stop.\n */\nfunction treeReader(input: TreeReaderInput): ChartReader {\n  const { stops, direction, words } = input\n  const byId = new Map(stops.map((stop) => [stop.id, stop]))\n  const stopOf = (target: ChartTarget) =>\n    target.kind === 'node' ? (byId.get(target.id) ?? null) : null\n  // What a press under the pointer opens, by the target it found, so the press opens it.\n  const opens = new WeakMap<ChartTarget, () => void>()\n  const first = stops[0]\n  return {\n    holds: (target) => stopOf(target) !== null,\n    lights: groupOf,\n    item: (target) => {\n      const stop = stopOf(target)\n      return stop ? treeItem(stop) : null\n    },\n    items: stops.map(stopTarget),\n    browse: {\n      targetAt: (point) => {\n        const hit = input.hit(point)\n        const stop = hit?.kind === 'stop' ? stops[hit.index] : undefined\n        const target: ChartTarget | null =\n          hit === null\n            ? null\n            : hit.kind === 'group'\n              ? { kind: 'node', id: groupTarget(hit.key) }\n              : stop\n                ? stopTarget(stop)\n                : null\n        const open = target && input.openAt(point)\n        if (target && open) opens.set(target, open)\n        return target\n      },\n      start: first ? stopTarget(first) : null,\n      step: (from, key) => {\n        const stop = stopOf(from)\n        if (!stop) return null\n        const next = stepIndex(key, stop.index, stops.length, 'vertical', direction)\n        const to = next === null ? undefined : stops[next]\n        return to ? stopTarget(to) : null\n      },\n      rank: (target) => (stopOf(target)?.index ?? 0) + 1,\n      stops: stops.length,\n      // The stops run in one line, so the slider runs across, as on a row of categories.\n      orientation: 'horizontal',\n      anchor: (target) => {\n        const stop = stopOf(target)\n        return stop ? input.anchor(stop) : null\n      },\n      describe: (target) => {\n        const stop = stopOf(target)\n        return stop ? words.describe(stop) : ''\n      },\n      tooltip: (target) => {\n        const stop = stopOf(target)\n        return stop ? words.tooltip(stop) : null\n      },\n      table: words.table,\n      open: (target) => {\n        const own = opens.get(target)\n        if (own) return own\n        const stop = stopOf(target)\n        return stop ? input.open(stop) : null\n      },\n      back: input.back,\n    },\n  }\n}\n\nexport {\n  groupTarget,\n  type TreeHit,\n  treeItem,\n  type TreeReaderInput,\n  treeReader,\n  type TreeStop,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-tree-reader.ts"
    },
    {
      "path": "registry/lib/chart-flow-reader.ts",
      "content": "import type { ChartDatum } from '@/registry/lib/chart-math'\nimport type {\n  ChartItem,\n  ChartPoint,\n  ChartReader,\n  PlotPoint,\n} from '@/registry/lib/chart-root'\nimport type { ChartTable, ChartTarget } from '@/registry/lib/chart-state'\nimport type { ReactNode } from 'react'\n\n/*\n * The flow family's reader: charts of nodes and the flows between them, such\n * as a Sankey. Every node and flow is a target the pointer finds and the\n * tooltip shows; the keys walk the nodes only, the chart's own way, and from\n * a flow the pointer lit they start at its source.\n */\n\n/** A node or a flow, as the chart's API counts it. */\ntype FlowStop =\n  | { kind: 'node'; key: string; name: string; value: number; index: number }\n  | {\n      kind: 'link'\n      key: string\n      source: string\n      target: string\n      value: number\n      datum: ChartDatum\n      index: number\n    }\n\ninterface FlowReaderInput {\n  /** Every node, then every link, in the data's order: what `activeIndex` counts. */\n  items: readonly FlowStop[]\n  /** The nodes in the order they are drawn: what the keys reach and the slider counts. */\n  drawnOrder: readonly string[]\n  /** The node a key goes to from the node keyed `from`, or null for a key the chart doesn't take. */\n  step: (from: string, key: string) => string | null\n  hit: (point: PlotPoint) => FlowStop | null\n  anchor: (stop: FlowStop) => ChartPoint | null\n  words: {\n    describe: (stop: FlowStop) => string\n    tooltip: (stop: FlowStop) => ReactNode\n    table: ChartTable\n  }\n}\n\n/** What the chart's parts read of a stop, such as its tooltip's heading: a link's row, and no row for a node. */\nfunction flowItem(stop: FlowStop): ChartItem {\n  return {\n    key: stop.key,\n    value: stop.key,\n    datum: stop.kind === 'link' ? stop.datum : null,\n    index: stop.index,\n  }\n}\n\nfunction flowTarget(key: string): ChartTarget {\n  return { kind: 'node', id: key }\n}\n\n/** The node the keys go on from: the node itself, or a flow's source. */\nfunction nodeFrom(stop: FlowStop) {\n  return stop.kind === 'node' ? stop.key : stop.source\n}\n\n/**\n * The reader of a chart of flows: each node and flow is a node target held\n * by its key, lighting no series. The keys reach the nodes in `drawnOrder`,\n * which the slider counts.\n */\nfunction flowReader(input: FlowReaderInput): ChartReader {\n  const { items, drawnOrder, words } = input\n  const byKey = new Map(items.map((stop) => [stop.key, stop]))\n  const stopOf = (target: ChartTarget) =>\n    target.kind === 'node' ? (byKey.get(target.id) ?? null) : null\n  const first = drawnOrder.find((key) => byKey.get(key)?.kind === 'node')\n  return {\n    holds: (target) => stopOf(target) !== null,\n    lights: () => null,\n    item: (target) => {\n      const stop = stopOf(target)\n      return stop ? flowItem(stop) : null\n    },\n    items: items.map((stop) => flowTarget(stop.key)),\n    browse: {\n      targetAt: (point) => {\n        const stop = input.hit(point)\n        return stop ? flowTarget(stop.key) : null\n      },\n      start: first === undefined ? null : flowTarget(first),\n      step: (from, key) => {\n        const stop = stopOf(from)\n        if (!stop) return null\n        const next = input.step(nodeFrom(stop), key)\n        return next !== null && byKey.has(next) ? flowTarget(next) : null\n      },\n      rank: (target) => {\n        const stop = stopOf(target)\n        return stop ? Math.max(1, drawnOrder.indexOf(nodeFrom(stop)) + 1) : 1\n      },\n      stops: drawnOrder.length,\n      // The stops run in one line, so the slider runs across, as on a row of categories.\n      orientation: 'horizontal',\n      anchor: (target) => {\n        const stop = stopOf(target)\n        return stop ? input.anchor(stop) : null\n      },\n      describe: (target) => {\n        const stop = stopOf(target)\n        return stop ? words.describe(stop) : ''\n      },\n      tooltip: (target) => {\n        const stop = stopOf(target)\n        return stop ? words.tooltip(stop) : null\n      },\n      table: words.table,\n      open: () => null,\n      back: null,\n    },\n  }\n}\n\nexport { flowItem, type FlowReaderInput, flowReader, type FlowStop }\n",
      "type": "registry:lib",
      "target": "@lib/chart-flow-reader.ts"
    },
    {
      "path": "registry/lib/chart-grid-reader.ts",
      "content": "import { type ReadingDirection, stepCell } from '@/registry/lib/chart-math'\nimport type {\n  ChartItem,\n  ChartPoint,\n  ChartReader,\n  PlotPoint,\n} from '@/registry/lib/chart-root'\nimport { type ChartTable, type ChartTarget, indexOfKey } from '@/registry/lib/chart-state'\nimport type { ReactNode } from 'react'\n\n/*\n * The reader of a chart drawn as a grid of cells, such as a heatmap: each\n * cell is a stop, held by its key, and the keys step through them as the\n * WAI-ARIA grid's do. Where each key goes comes from the grid's layout, so\n * cells of another shape add a layout and nothing else. Pure, so it is\n * tested on its own.\n */\n\n/** A cell the keys stop at. */\ninterface GridStop extends ChartItem {\n  column: number\n  row: number\n  /** The cell's name, such as a calendar cell's date, written out. */\n  value: string\n}\n\n/** How a grid's cells sit, which says where each arrow goes. */\ninterface GridLayout {\n  /**\n   * The cell `key` goes to from the cell at `index`, or null for a key the\n   * grid doesn't take. The WAI-ARIA grid's keys: the arrows one cell (where\n   * no cell is there, the cell reached stays), Home and End to the first and\n   * last cell of its row, Page Up and Page Down to the top and bottom of its\n   * column.\n   */\n  step: (\n    cells: readonly GridStop[],\n    index: number,\n    key: string,\n    direction: ReadingDirection,\n  ) => number | null\n}\n\n/** Square cells, in columns and rows. */\nconst squareLayout: GridLayout = {\n  step: (cells, index, key, direction) => stepCell(cells, index, key, direction),\n}\n\n/** What a grid chart says of its cells: to a screen reader, in the tooltip, and as the data table. */\ninterface GridWords {\n  describe: (stop: GridStop) => string\n  tooltip: (stop: GridStop) => ReactNode\n  table: ChartTable\n}\n\ninterface GridReaderInput {\n  /** The cells still in the data, in order. */\n  current: readonly GridStop[]\n  layout: GridLayout\n  direction: ReadingDirection\n  /** The cell under the pointer, by its place in `current`, or null. */\n  hit: (point: PlotPoint) => number | null\n  /** Where the cell's tooltip sits, or null before the plot is measured. */\n  anchor: (stop: GridStop) => ChartPoint | null\n  words: GridWords\n  /** The last cell on a grid that scrolls and opens at its end, such as a year of weeks; else the first. */\n  start: 'first' | 'last'\n}\n\n/** The reader of a grid of cells: each cell is held by its key, as an `x` target. */\nfunction gridReader(input: GridReaderInput): ChartReader {\n  const { current, layout, direction, words } = input\n  const keys = current.map((stop) => stop.key)\n  const count = keys.length\n  const indexOf = (target: ChartTarget) =>\n    target.kind === 'x' ? indexOfKey(keys, target.key) : null\n  const stopOf = (target: ChartTarget) => {\n    const index = indexOf(target)\n    return index === null ? null : (current[index] ?? null)\n  }\n  const at = (index: number | null): ChartTarget | null => {\n    const key = index === null ? undefined : keys[index]\n    return key === undefined ? null : { kind: 'x', key }\n  }\n  return {\n    holds: (target) => indexOf(target) !== null,\n    lights: () => null,\n    item: stopOf,\n    items: keys.map((key) => ({ kind: 'x', key })),\n    browse: {\n      targetAt: (point) => at(input.hit(point)),\n      start: at(count === 0 ? null : input.start === 'last' ? count - 1 : 0),\n      step: (from, key) => {\n        const index = indexOf(from)\n        return index === null ? null : at(layout.step(current, index, key, direction))\n      },\n      rank: (target) => (indexOf(target) ?? 0) + 1,\n      stops: count,\n      // The slider runs along the cells, across the page.\n      orientation: 'horizontal',\n      anchor: (target) => {\n        const stop = stopOf(target)\n        return stop ? input.anchor(stop) : null\n      },\n      describe: (target) => {\n        const stop = stopOf(target)\n        return stop ? words.describe(stop) : ''\n      },\n      tooltip: (target) => {\n        const stop = stopOf(target)\n        return stop ? words.tooltip(stop) : null\n      },\n      table: words.table,\n      open: () => null,\n      back: null,\n    },\n  }\n}\n\nexport {\n  type GridLayout,\n  type GridReaderInput,\n  gridReader,\n  type GridStop,\n  type GridWords,\n  squareLayout,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-grid-reader.ts"
    }
  ],
  "type": "registry:lib"
}