{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-root",
  "title": "Chart root",
  "description": "The root every chart sits on, whatever its shape: its series and their colours, what is hidden and brought forward, the frame, the plot that takes the pointer and the keys, the one tooltip, the loading, empty and error states, the data table, the announcements, the focus held by key, the moves, and what an agent reads and does through ui-sdk’s agent bridge.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/cut.json",
    "https://kinoui.com/r/animated-number.json",
    "https://kinoui.com/r/announce.json",
    "https://kinoui.com/r/button.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/controllable.json",
    "https://kinoui.com/r/glide.json",
    "https://kinoui.com/r/popup.json",
    "https://kinoui.com/r/theme.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/scroll.json",
    "https://kinoui.com/r/swap.json"
  ],
  "files": [
    {
      "path": "registry/lib/chart-root.tsx",
      "content": "'use client'\n\nimport { AnimatedNumber } from '@/registry/components/kino/animated-number'\nimport { Button, buttonVariants } from '@/registry/components/kino/button'\nimport { announce } from '@/registry/lib/announce'\nimport {\n  type ChartAgentMoves,\n  chart as chartPrimitive,\n  stillChart,\n} from '@/registry/lib/chart-agent'\nimport {\n  type ChartConfig,\n  type ChartDatum,\n  type ChartPattern,\n  labelLength,\n  type ReadingDirection,\n} from '@/registry/lib/chart-math'\nimport {\n  type ChartStatus,\n  type ChartTable,\n  type ChartTarget,\n  durationOf,\n  leavingAfter,\n  moveTiming,\n  resolveFocus,\n  sameTarget,\n  targetKey,\n  travelOf,\n} from '@/registry/lib/chart-state'\nimport { useControllable } from '@/registry/lib/controllable'\nimport { CutTooltip } from '@/registry/lib/cut'\nimport {\n  GlideContent,\n  tooltipBoxClassName,\n  tooltipLabelClassName,\n  TooltipSurface,\n} from '@/registry/lib/glide'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport { POPUP_COLLISION_PADDING } from '@/registry/lib/popup'\nimport { reducesMotion } from '@/registry/lib/reduce-motion'\nimport { markMounted, mergeRefs } from '@/registry/lib/refs'\nimport { FOLLOWS_TRANSITION, holdResizing } from '@/registry/lib/resize'\nimport { revealBehavior, revealBy } from '@/registry/lib/scroll'\nimport { Swap } from '@/registry/lib/swap'\nimport { isRTL } from '@ui-sdk/core'\nimport { type PartProps, usePart, usePrimitive } from '@ui-sdk/react/primitive'\nimport { Toggle as TogglePrimitive } from '@ui-sdk/react/toggle'\nimport {\n  createTooltipController,\n  TooltipContent as TooltipContentPrimitive,\n  type TooltipController,\n  TooltipTrigger as TooltipTriggerPrimitive,\n} from '@ui-sdk/react/tooltip'\nimport {\n  type ComponentProps,\n  createContext,\n  type CSSProperties,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n  use,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\nimport { flushSync } from 'react-dom'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The root every chart sits on, whatever its shape: its series and their\n * colours, what is hidden and brought forward, its status and its words,\n * the figure and its plot, the one tooltip, the data table, what a screen\n * reader hears, the focus and the moves. It knows nothing about categories,\n * bands or axes: each family of charts hands it a reader (`ChartReader`)\n * that answers for its own marks.\n */\n\n/** A point of the plot under the pointer, in px from its top left, and the plot's size. */\ninterface PlotPoint {\n  x: number\n  y: number\n  width: number\n  height: number\n}\n\n/** Where a tooltip sits, as fractions of the plot from its top left, and the side it opens on. */\ninterface ChartPoint {\n  x: number\n  y: number\n  side: 'top' | 'bottom' | 'left' | 'right' | 'inline-start' | 'inline-end'\n}\n\n/** One thing a chart's API counts and hands back: a category, a tile, a slice, a flow. */\ninterface ChartItem {\n  key: string\n  /** As the data has it: the category, or a tile's or a node's name. */\n  value: unknown\n  /** Its row of your data, or null where none sits: a Sankey node, the Waffle's remaining share, a heatmap cell the data leaves out, a stop only a series' own data has. */\n  datum: ChartDatum | null\n  /** Its place in the chart's items: what `activeIndex` counts. */\n  index: number\n}\n\n/**\n * What a family of charts answers for its marks, so the root can keep the\n * focus, bring series forward and hand items back through the chart's API.\n */\ninterface ChartReader {\n  /** Whether `target` is one of the chart's now: a stop the keys reach and the tooltip shows. */\n  holds: (target: ChartTarget) => boolean\n  /** The series `target` brings forward, or null. */\n  lights: (target: ChartTarget) => string | null\n  /** The item `target` is on, as the public API hands it back, or null. */\n  item: (target: ChartTarget) => ChartItem | null\n  /** Every item, in the order `activeIndex` counts. */\n  items: readonly ChartTarget[]\n  /** What the pointer, the keys, the tooltip and the data table read, or null on a chart they don't reach, such as the Bar list. */\n  browse: ChartBrowseReader | null\n}\n\n/**\n * How the pointer and the keys move through a chart's marks, where its\n * tooltip sits and what it says, and how the chart is read out.\n */\ninterface ChartBrowseReader {\n  /** What is under the pointer, or null for nothing. */\n  targetAt: (point: PlotPoint) => ChartTarget | null\n  /** Where the keys start when nothing is reached or picked yet. */\n  start: ChartTarget | null\n  /** Where `key` goes from `from`, or null for a key the chart doesn't take. */\n  step: (from: ChartTarget, key: string) => ChartTarget | null\n  /** The place of `target` among the stops, from 1, as the slider's value. */\n  rank: (target: ChartTarget) => number\n  /** How many stops the keys reach, as the slider's most. */\n  stops: number\n  /** The way the keys step, as the slider's orientation. */\n  orientation: 'horizontal' | 'vertical'\n  /** Where the tooltip of `target` sits, or null before the plot is measured. */\n  anchor: (target: ChartTarget) => ChartPoint | null\n  /** What a screen reader hears on `target`. */\n  describe: (target: ChartTarget) => string\n  /** What the tooltip shows on `target`. */\n  tooltip: (target: ChartTarget) => ReactNode\n  table: ChartTable\n  /** What opening `target` does, such as zooming into its group, or null. */\n  open: (target: ChartTarget) => (() => void) | null\n  /** What Escape goes back to once nothing is lit, such as zooming back out, or null. */\n  back: (() => void) | null\n}\n\n/** Every word the chart says or reads out, for a chart in another language. */\ninterface ChartMessages {\n  /** The data table's name. */\n  table: string\n  /** The data table's first column. */\n  category: string\n  /** The name of the layer that steps through the categories by keyboard. */\n  browse: string\n  noValue: string\n  /** A value's column of the data table, when the chart has no name for its values. */\n  value: string\n  total: string\n  /** A value's share of the whole, as a column of the data table. */\n  share: string\n  /** The legend's name. */\n  series: string\n  selected: string\n  /** Said of a value that is projected, not measured. */\n  forecast: string\n  /** A change since the category before, such as \"up 22%\". */\n  change: (change: number, size: string) => string\n  /** A value against the most it could be, such as \"86 of 120\". */\n  outOf: (value: string, most: string) => string\n  /** The column of the data table naming the group a value is in, such as a treemap tile's. */\n  group: string\n  /** The whole of a chart that zooms, such as a treemap's first crumb. */\n  whole: string\n  /** The data table's columns for where a flow starts and where it ends, such as a Sankey's. */\n  from: string\n  to: string\n  /** A flow from one node to another, with their names. */\n  flow: (from: string, to: string) => string\n  /** A share of a part, read out, such as \"38% of src\". */\n  shareOf: (share: string, part: string) => string\n  /** A row of a tooltip, or a column of the data table, for a share of a part, such as \"Of src\". */\n  ofPart: (part: string) => string\n  /** How deep a node of a tree is, read out, such as \"level 2\" for the parts of a top. */\n  level: (depth: number) => string\n  /** The way back out of a chart that zooms, with the chart's `label`, so each chart's is its own. */\n  zoomPath: (label: string) => string\n  /** Said once a chart that zooms shows another part of it, with the part's name. */\n  zoomedTo: (name: string) => string\n  /** A funnel step's share of the first step, as a row of its tooltip and a column of the data table. */\n  ofFirst: string\n  /** A funnel step's share of the step before. */\n  ofPrevious: string\n  /** How many a funnel lost since the step before. */\n  droppedOff: string\n  /** The data table's first column on a bridge, whose categories are steps. */\n  step: string\n  /** A bridge step's change, as a row of its tooltip and a column of the data table. */\n  stepChange: string\n  /** A bridge's total after each step, as a row of its tooltip and a column of the data table. */\n  runningTotal: string\n  /** What a bridge's step says after its name: its change, such as \"down 120\", and the running total after it. */\n  bridgeStep: (change: string, total: string) => string\n  /** What a bridge's total says after its name, with its value. */\n  bridgeTotal: (total: string) => string\n  loading: string\n  /** Said when the data arrives, with the chart's `label`. */\n  loaded: (label: string) => string\n  empty: string\n  allHidden: string\n  showAll: (count: number) => string\n  error: string\n  retry: string\n}\n\nconst defaultMessages: ChartMessages = {\n  table: 'Chart data',\n  category: 'Category',\n  browse: 'Values',\n  noValue: 'No value',\n  value: 'Value',\n  total: 'Total',\n  share: 'Share',\n  series: 'Series',\n  selected: 'selected',\n  forecast: 'forecast',\n  change: (change, size) =>\n    change > 0 ? `up ${size}` : change < 0 ? `down ${size}` : 'no change',\n  outOf: (value, most) => `${value} of ${most}`,\n  group: 'Group',\n  whole: 'All',\n  from: 'From',\n  to: 'To',\n  flow: (from, to) => `${from} to ${to}`,\n  shareOf: (share, part) => `${share} of ${part}`,\n  ofPart: (part) => `Of ${part}`,\n  level: (depth) => `level ${depth}`,\n  zoomPath: (label) => `Zoom path for ${label}`,\n  zoomedTo: (name) => `Showing ${name}`,\n  ofFirst: 'Of the first step',\n  ofPrevious: 'Of the step before',\n  droppedOff: 'Dropped off',\n  step: 'Step',\n  stepChange: 'Change',\n  runningTotal: 'Running total',\n  bridgeStep: (change, total) => `${change}, running total ${total}`,\n  bridgeTotal: (total) => `${total}, total`,\n  loading: 'Loading chart',\n  loaded: (label) => `${label} loaded`,\n  empty: 'No data for this range',\n  allHidden: 'Every series is hidden',\n  showAll: (count) => `Show all ${count} series`,\n  error: 'The chart couldn’t load',\n  retry: 'Try again',\n}\n\n/** How values are written: Intl's number options, or a function of your own. */\ntype ChartFormat = Intl.NumberFormatOptions | ((value: number) => string)\n\n/** The series' colour as a CSS value, set on the chart as `--color-<key>`. */\nfunction seriesColor(key: string) {\n  return `var(--color-${key})`\n}\n\n/**\n * Each series' colour as `--color-<key>`, from its `color`, its `theme`, or\n * else the next of `--chart-1` to `--chart-5`, as shadcn's chart does. While\n * the chart changes size, nothing in it eases, so the bars keep up with the\n * axes.\n */\nfunction ChartStyle({\n  id,\n  config,\n  series,\n}: {\n  id: string\n  config: ChartConfig\n  series: readonly string[]\n}) {\n  const rule = (theme: 'light' | 'dark') =>\n    series\n      .map((key, slot) => {\n        const entry = config[key]\n        const color =\n          entry?.theme?.[theme] ?? entry?.color ?? `var(--chart-${(slot % 5) + 1})`\n        return `--color-${key}: ${color};`\n      })\n      .join(' ')\n  return (\n    // oxlint-disable-next-line react/no-danger -- the colours are the chart's own config\n    <style\n      dangerouslySetInnerHTML={{\n        __html: `[data-chart='${id}'] { ${rule('light')} } .dark [data-chart='${id}'] { ${rule('dark')} } [data-chart='${id}'][data-resizing] * { transition-property: none; }`,\n      }}\n    />\n  )\n}\n\n/**\n * The colour forced colours draw a series in, by its place: system colours\n * stand in for the chart's, five apart so neighbours differ.\n */\nconst forcedSeriesColors = [\n  'forced-colors:bg-[CanvasText]',\n  'forced-colors:bg-[Highlight]',\n  'forced-colors:bg-[LinkText]',\n  'forced-colors:bg-[GrayText]',\n  'forced-colors:bg-[VisitedText]',\n] as const\n\nfunction forcedSeriesColor(slot: number) {\n  return forcedSeriesColors[slot % forcedSeriesColors.length]\n}\n\n/** The same colours for a mark drawn in its text colour, such as a line. */\nconst forcedSeriesTextColors = [\n  'forced-colors:text-[CanvasText]',\n  'forced-colors:text-[Highlight]',\n  'forced-colors:text-[LinkText]',\n  'forced-colors:text-[GrayText]',\n  'forced-colors:text-[VisitedText]',\n] as const\n\nfunction forcedSeriesTextColor(slot: number) {\n  return forcedSeriesTextColors[slot % forcedSeriesTextColors.length]\n}\n\n/**\n * The patterns the chart's `patterns` hands out, in series order, the first\n * left plain: fine lines and dots that tell series apart in grey and in\n * print without fighting their colours.\n */\nconst patternOrder: readonly ChartPattern[] = [\n  'solid',\n  'diagonal',\n  'dots',\n  'stripes',\n  'grid',\n]\n\n/**\n * A pattern's ink: the page's background, a little see-through, so it reads\n * as a lighter tone of a series' colour in light mode and a darker one in\n * dark.\n */\nconst ink = 'color-mix(in oklab, var(--background) 42%, transparent)'\n\n/** A pattern's tile, in px: its lines are a px wide, this far apart. */\nconst PATTERN_TILE = 6\n\n/** A swatch's tile, in px: finer, so a swatch shows a few of its lines. */\nconst SWATCH_TILE = 3\n\n/**\n * The pattern as a `background-image` over the series' colour, or none, its\n * lines `tile` px apart: a swatch takes a finer one, so a few show in it.\n */\nfunction patternImage(pattern: ChartPattern, tile = PATTERN_TILE): string | undefined {\n  switch (pattern) {\n    case 'stripes':\n      return `repeating-linear-gradient(90deg, ${ink} 0 1px, transparent 1px ${tile}px)`\n    case 'diagonal':\n      return `repeating-linear-gradient(45deg, ${ink} 0 1px, transparent 1px ${tile / Math.SQRT2}px)`\n    case 'dots':\n      // Two dots a tile, staggered, so they sit evenly rather than in rows.\n      return `radial-gradient(${ink} 0.9px, transparent 1.2px) 0 0 / ${tile}px ${tile}px, radial-gradient(${ink} 0.9px, transparent 1.2px) ${tile / 2}px ${tile / 2}px / ${tile}px ${tile}px`\n    case 'grid':\n      return `linear-gradient(${ink} 1px, transparent 1px) 0 0 / ${tile}px ${tile}px, linear-gradient(90deg, ${ink} 1px, transparent 1px) 0 0 / ${tile}px ${tile}px`\n    default:\n      return undefined\n  }\n}\n\n/**\n * The same pattern for an SVG mark, as a `<pattern>` with the id `id`, drawn\n * over `currentColor` in px. `turn` undoes a rotation of the mark that uses\n * it, in degrees, so its lines run the way the swatches' do.\n */\nfunction ChartSvgPattern({\n  id,\n  pattern,\n  turn = 0,\n}: {\n  id: string\n  pattern: ChartPattern\n  turn?: number\n}) {\n  // A CSS gradient at 45deg runs its stripes down to the right, so the SVG's turn the other way.\n  const angle = turn + (pattern === 'diagonal' ? -45 : 0)\n  // Diagonal lines a tile apart across, as the gradient's are.\n  const tile = pattern === 'diagonal' ? PATTERN_TILE / Math.SQRT2 : PATTERN_TILE\n  const half = tile / 2\n  return (\n    <pattern\n      id={id}\n      width={tile}\n      height={tile}\n      patternUnits='userSpaceOnUse'\n      patternTransform={angle === 0 ? undefined : `rotate(${angle})`}\n    >\n      <rect width={tile} height={tile} fill='currentColor' />\n      {(pattern === 'stripes' || pattern === 'diagonal') && (\n        <rect width={1} height={tile} style={{ fill: ink }} />\n      )}\n      {pattern === 'dots' && (\n        <>\n          <circle cx={0} cy={0} r={0.9} style={{ fill: ink }} />\n          <circle cx={tile} cy={0} r={0.9} style={{ fill: ink }} />\n          <circle cx={0} cy={tile} r={0.9} style={{ fill: ink }} />\n          <circle cx={tile} cy={tile} r={0.9} style={{ fill: ink }} />\n          <circle cx={half} cy={half} r={0.9} style={{ fill: ink }} />\n        </>\n      )}\n      {pattern === 'grid' && (\n        <>\n          <rect width={tile} height={1} style={{ fill: ink }} />\n          <rect width={1} height={tile} style={{ fill: ink }} />\n        </>\n      )}\n    </pattern>\n  )\n}\n\n/** A swatch of a series: its colour and its pattern, as the legend and the tooltip draw it. */\nfunction swatchStyle(key: string, pattern: ChartPattern): CSSProperties {\n  const image = patternImage(pattern, SWATCH_TILE)\n  return {\n    '--swatch': seriesColor(key),\n    background: image ? `${image}, var(--swatch)` : undefined,\n  } as CSSProperties\n}\n\n/**\n * One of the legend's toggles, which shows and hides `series`: its colour\n * fills the swatch while it shows. Pointing at it, or focusing it, asks for\n * its series to be brought forward. Every chart's legend is drawn from\n * these, so each looks and answers the same.\n */\nfunction ChartLegendToggle({\n  series,\n  slot,\n  shown,\n  pattern,\n  marker,\n  onShownChange,\n  onEmphasisChange,\n  children,\n}: {\n  series: string\n  /** The series' place, for its colour in forced colours. */\n  slot: number\n  shown: boolean\n  pattern: ChartPattern\n  /** The shape its marks take, as `markerOf` gives it, which the swatch takes in place of a square. */\n  marker?: string\n  onShownChange: (shown: boolean) => void\n  /** Whether the series is pointed at or focused, so it can come forward. */\n  onEmphasisChange: (emphasised: boolean) => void\n  children: ReactNode\n}) {\n  return (\n    <CutTooltip\n      render={\n        <TogglePrimitive\n          pressed={shown}\n          onPressedChange={onShownChange}\n          onPointerEnter={() => onEmphasisChange(true)}\n          onPointerLeave={() => onEmphasisChange(false)}\n          onFocus={(event) => {\n            if (event.currentTarget.matches(':focus-visible')) onEmphasisChange(true)\n          }}\n          onBlur={() => onEmphasisChange(false)}\n          className={cn(\n            buttonVariants({ variant: 'ghost', size: 'xs' }),\n            'group/legend text-muted-foreground data-pressed:text-foreground gap-1.5 font-medium',\n          )}\n        >\n          {marker ? (\n            <svg\n              aria-hidden\n              viewBox='-1.2 -1.2 2.4 2.4'\n              className={cn(\n                'size-3 shrink-0 overflow-visible fill-transparent stroke-(--swatch) [stroke-width:1.5] transition-[fill] duration-(--motion-press-duration) ease-(--motion-press-fade-easing) [vector-effect:non-scaling-stroke] group-data-pressed/legend:fill-(--swatch)',\n                forcedMarkerColors[slot % forcedMarkerColors.length],\n              )}\n              style={{ '--swatch': seriesColor(series) } as CSSProperties}\n            >\n              <path d={marker} vectorEffect='non-scaling-stroke' />\n            </svg>\n          ) : (\n            <span\n              aria-hidden\n              className={cn(\n                'size-2.5 shrink-0 rounded-[calc(var(--control-radius-xs)/2.5)] border-2 border-(--swatch) bg-transparent transition-[background-color] duration-(--motion-press-duration) ease-(--motion-press-fade-easing) group-data-pressed/legend:bg-(--swatch)',\n                forcedSwatchColors[slot % forcedSwatchColors.length],\n              )}\n              style={swatchStyle(series, shown ? pattern : 'solid')}\n            />\n          )}\n          <span data-cut className='truncate'>\n            {children}\n          </span>\n        </TogglePrimitive>\n      }\n    />\n  )\n}\n\n/**\n * A series' key beside words that name it, such as a value axis's title:\n * its colour and pattern in a square, or its marks' shape, as the legend's\n * pressed toggle draws it, and in forced colours, the series' system colour.\n */\nfunction SeriesKey({\n  series,\n  slot,\n  pattern,\n  marker,\n}: {\n  series: string\n  /** The series' place, for its colour in forced colours. */\n  slot: number\n  pattern: ChartPattern\n  /** The shape its marks take, as `markerOf` gives it, in place of a square. */\n  marker?: string\n}) {\n  return marker ? (\n    <svg\n      aria-hidden\n      viewBox='-1.2 -1.2 2.4 2.4'\n      className={cn(\n        'size-3 shrink-0 overflow-visible fill-(--swatch)',\n        forcedMarkerFills[slot % forcedMarkerFills.length],\n      )}\n      style={{ '--swatch': seriesColor(series) } as CSSProperties}\n    >\n      <path d={marker} />\n    </svg>\n  ) : (\n    <span\n      aria-hidden\n      className={cn(\n        'size-2.5 shrink-0 rounded-[calc(var(--control-radius-xs)/2.5)] bg-(--swatch)',\n        forcedSeriesColor(slot),\n      )}\n      style={swatchStyle(series, pattern)}\n    />\n  )\n}\n\n/**\n * A toggle for each of `series`, as every chart's legend draws them: one\n * pressed off hides its series, and pointing at or focusing one that shows\n * brings it forward.\n */\nfunction ChartLegendToggles({\n  series,\n  labelOf,\n  patternOf,\n  markerOf,\n  hidden,\n  onHiddenChange,\n  onEmphasisChange,\n}: {\n  series: readonly string[]\n  labelOf: (key: string) => ReactNode\n  patternOf: (key: string) => ChartPattern\n  markerOf?: (key: string) => string | undefined\n  hidden: readonly string[]\n  onHiddenChange: (hidden: string[]) => void\n  /** The series brought forward, or null for none. */\n  onEmphasisChange: (key: string | null) => void\n}) {\n  return series.map((key, slot) => {\n    const shown = !hidden.includes(key)\n    return (\n      <ChartLegendToggle\n        key={key}\n        series={key}\n        slot={slot}\n        shown={shown}\n        pattern={patternOf(key)}\n        marker={markerOf?.(key)}\n        onShownChange={(pressed) => {\n          onHiddenChange(pressed ? hidden.filter((k) => k !== key) : [...hidden, key])\n          onEmphasisChange(pressed ? key : null)\n        }}\n        onEmphasisChange={(emphasised) =>\n          onEmphasisChange(emphasised && shown ? key : null)\n        }\n      >\n        {labelOf(key)}\n      </ChartLegendToggle>\n    )\n  })\n}\n\n/** The legend's swatch in forced colours: its outline always, its fill while the series shows. */\nconst forcedSwatchColors = [\n  'forced-colors:border-[CanvasText] forced-colors:group-data-pressed/legend:bg-[CanvasText]',\n  'forced-colors:border-[Highlight] forced-colors:group-data-pressed/legend:bg-[Highlight]',\n  'forced-colors:border-[LinkText] forced-colors:group-data-pressed/legend:bg-[LinkText]',\n  'forced-colors:border-[GrayText] forced-colors:group-data-pressed/legend:bg-[GrayText]',\n  'forced-colors:border-[VisitedText] forced-colors:group-data-pressed/legend:bg-[VisitedText]',\n] as const\n\n/** The same for a swatch drawn as a marker's shape, which an SVG strokes and fills. */\nconst forcedMarkerColors = [\n  'forced-colors:stroke-[CanvasText] forced-colors:group-data-pressed/legend:fill-[CanvasText]',\n  'forced-colors:stroke-[Highlight] forced-colors:group-data-pressed/legend:fill-[Highlight]',\n  'forced-colors:stroke-[LinkText] forced-colors:group-data-pressed/legend:fill-[LinkText]',\n  'forced-colors:stroke-[GrayText] forced-colors:group-data-pressed/legend:fill-[GrayText]',\n  'forced-colors:stroke-[VisitedText] forced-colors:group-data-pressed/legend:fill-[VisitedText]',\n] as const\n\n/** The series' system colours for a marker that stands alone, beside an axis's title or in the tooltip. */\nconst forcedMarkerFills = [\n  'forced-colors:fill-[CanvasText]',\n  'forced-colors:fill-[Highlight]',\n  'forced-colors:fill-[LinkText]',\n  'forced-colors:fill-[GrayText]',\n  'forced-colors:fill-[VisitedText]',\n] as const\n\n/**\n * How much of its colour a mark keeps while it steps back for one that is\n * lit, from 0 to 1: a buyer's `--chart-dim`, set on a chart or anywhere\n * above it, resolved once where the chart starts.\n */\nconst stepBackScopeClassName = '[--chart-step-back:var(--chart-dim,0.65)]'\n\n/**\n * A mark that steps back: it paints with `--mark-ink`, its `--mark-color`\n * with less colour, the same lightness and hue. It steps back while\n * `data-dim`, or as far as a `--mark-step` from 0 to 1 that it inherits says,\n * which a part such as a gradient's stop takes from the mark around it. In\n * forced colours its system colour stays.\n */\nconst stepBackInkClassName =\n  '[--mark-ink:oklch(from_var(--mark-color)_l_calc(c*(1-var(--mark-step,0)*(1-var(--chart-step-back))))_h)] not-forced-colors:data-dim:[--mark-step:1]'\n\n/**\n * A layer of many marks that steps back as one while `data-dim`, with a\n * filter the compositor runs, never a colour on each mark (motion.md, rule\n * 7): all the way, or as far as its own `--mark-step` from 0 to 1 says.\n */\nconst stepBackLayerClassName =\n  'transition-[filter] duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing) not-forced-colors:data-dim:[filter:saturate(calc(1-var(--mark-step,1)*(1-var(--chart-step-back))))]'\n\n/**\n * The chart's frame: an optional legend above and below, an axis on each\n * side of the plot, and the plot. Every part takes its own area, and the\n * plot's layers share one.\n */\nconst chartFrameClassName = cn(\n  'group/chart @container/chart relative isolate grid h-72 min-w-0 grid-cols-[auto_minmax(0,1fr)_auto] grid-rows-[auto_auto_minmax(0,1fr)_auto_auto] [grid-template-areas:\"top_top_top\"_\"._top-axis_.\"_\"start-axis_plot_end-axis\"_\"._bottom-axis_.\"_\"bottom_bottom_bottom\"] text-xs',\n  stepBackScopeClassName,\n)\n\n/** A tooltip row's quieter text, in full colour on the row of the series brought forward. */\nconst tooltipQuietClassName =\n  'text-background/75 transition-colors duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing) group-data-lit/row:text-background forced-colors:text-[CanvasText]'\n\n/**\n * Text written on a mark, such as a slice's or a tile's label: white or near\n * black, whichever reads on the mark's colour, `--label-on`, at 4.5:1 or\n * more; in forced colours, the page's text on a box of its own, or on an\n * SVG label, which takes no box, a 3px halo of the page's colour. The choice\n * reads the colour's luminance, `--label-y`, as contrast is measured: a\n * switch on lightness alone fell to 4.2:1 on a blue and 4.4:1 on a red, the\n * two sides of it (2026-11-22, LGL-606: the Sunburst's outer rings in dark\n * mode). The switch sits where white and black read alike, and the black\n * deepens to pure black on the marks just past it.\n */\nconst labelOnClassName =\n  '[--label-y:(0.2126_*_pow((max(0,_r)_+_0.055)_/_1.055,_2.4)_+_0.7152_*_pow((max(0,_g)_+_0.055)_/_1.055,_2.4)_+_0.0722_*_pow((max(0,_b)_+_0.055)_/_1.055,_2.4))] [--label-white:clamp(0,_(0.179_-_var(--label-y))_*_1000,_1)] [--label-v:calc(var(--label-white)_+_(1_-_var(--label-white))_*_clamp(0,_(var(--label-y)_-_0.179)_*_0.4,_0.044))] text-[color(from_var(--label-on)_srgb_var(--label-v)_var(--label-v)_var(--label-v))] forced-colors:rounded-(--control-radius-xs) forced-colors:bg-[Canvas] forced-colors:px-1 forced-colors:text-[CanvasText] forced-colors:[paint-order:stroke] forced-colors:stroke-[Canvas] forced-colors:[stroke-width:3px] forced-colors:[stroke-linejoin:round]'\n\n/** A series' colour beside its name in a tooltip, on its `--swatch` (`swatchStyle`). */\nconst swatchClassName =\n  'size-2 shrink-0 rounded-[calc(var(--control-radius-xs)/4)] bg-(--swatch)'\n\n/**\n * The size a chart draws at: its plot's, or before the plot is measured, as\n * on the page's first paint from the server, a stand-in that its SVGs fit to\n * the plot with `drawingFrame`, so the marks show from the first frame.\n */\nfunction drawingSize(size: { width: number; height: number }) {\n  return isMeasured(size) ? size : UNMEASURED\n}\n\n/** Whether the plot has been measured: a size of 0 is one the page hasn't laid out yet. */\nfunction isMeasured(size: { width: number; height: number }) {\n  return size.width > 0 && size.height > 0\n}\n\n/**\n * An SVG's frame for `drawingSize`: none once the plot is measured, else the\n * stand-in fitted to the plot, stretched (`none`) for marks whose shape follows\n * the plot's, such as lines, or kept square (`xMidYMid meet`), such as a ring.\n */\nfunction drawingFrame(\n  size: { width: number; height: number },\n  fit: 'none' | 'xMidYMid meet',\n) {\n  return isMeasured(size)\n    ? {}\n    : {\n        viewBox: `0 0 ${UNMEASURED.width} ${UNMEASURED.height}`,\n        preserveAspectRatio: fit,\n      }\n}\n\n/** About a plot's size, so what a chart draws in pixels, such as a ring's gaps, starts out near it. */\nconst UNMEASURED = { width: 240, height: 240 }\n\n/** A layer of the plot: the size of the plot, and the box its insets are measured in. */\nconst plotLayerClassName =\n  'pointer-events-none relative min-h-0 min-w-0 [grid-area:plot] [container-type:size]'\n\n/**\n * Whether the chart has come into view, so its entrance plays then and not on\n * a page that loads with it out of sight. `skip` is there at once.\n */\nfunction useEntered(ref: { current: Element | null }, skip: boolean) {\n  const [entered, setEntered] = useState(skip)\n  useEffect(() => {\n    const element = ref.current\n    if (entered || !element) return\n    const observer = new IntersectionObserver(\n      (entries) => {\n        if (entries.some((entry) => entry.isIntersecting)) {\n          // A frame after it is first painted, so the bars rise from the baseline.\n          requestAnimationFrame(() => setEntered(true))\n          observer.disconnect()\n        }\n      },\n      { threshold: 0.3 },\n    )\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [entered, ref])\n  return entered\n}\n\n/**\n * Marks `root` with `data-resizing` while it changes size after it is\n * first laid out, and for two frames after, which stops every transition in\n * it: a size change moves everything by the same amount at once, rather\n * than easing the bars behind the axes. Only the chart's own size counts: the\n * plot also changes size when new values widen the value axis, and that move\n * eases with the rest. A chart whose height comes from its data, such as a\n * grid of cells growing a row or its legend arriving, counts only a change\n * of width, so its data still arrives as it moves.\n */\nfunction useResizing(root: RefObject<HTMLElement | null>, widthOnly: boolean) {\n  useEffect(() => {\n    const element = root.current\n    if (!element) return\n    let width: number | null = null\n    const resizing = holdResizing(element)\n    const observer = new ResizeObserver(([entry]) => {\n      if (!entry) return\n      const was = width\n      width = entry.contentRect.width\n      if (was === null || (widthOnly && was === width)) return\n      resizing.hold()\n    })\n    observer.observe(element)\n    return () => {\n      observer.disconnect()\n      resizing.stop()\n    }\n  }, [root, widthOnly])\n}\n\n/** An element's size in px, kept up to date. */\nfunction useSize(ref: RefObject<HTMLElement | null>) {\n  const [size, setSize] = useState({ width: 0, height: 0 })\n  useLayoutEffect(() => {\n    const element = ref.current\n    if (!element) return\n    const { width, height } = element.getBoundingClientRect()\n    setSize({ width, height })\n    const observer = new ResizeObserver(([entry]) => {\n      if (!entry) return\n      const { width, height } = entry.contentRect\n      setSize((was) =>\n        was.width === width && was.height === height ? was : { width, height },\n      )\n    })\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [ref])\n  return size\n}\n\n/**\n * A value that rolls to each new one: digit by digit for Intl's options,\n * crossfading for a format of your own, such as a bar list's values or a\n * funnel's rates.\n */\nfunction ChartNumber({\n  value,\n  format,\n  locale,\n}: {\n  value: number\n  format: ChartFormat | undefined\n  locale: Intl.LocalesArgument\n}) {\n  if (typeof format === 'function') {\n    return (\n      <Swap align='end'>\n        <span>{format(value)}</span>\n      </Swap>\n    )\n  }\n  return <AnimatedNumber value={value} locale={locale} format={format} />\n}\n\n/** The formatter of `format`: a function of yours, or Intl's options, once per locale. */\nfunction formatterOf(\n  locale: Intl.LocalesArgument,\n  format: ChartFormat | undefined,\n): (value: number) => string {\n  if (typeof format === 'function') return format\n  const formatter = numberFormatter(locale, format)\n  return (value) => formatter.format(value)\n}\n\n/** How a chart writes a change: with its sign, so a rise reads `+120`. */\nfunction signedWriter(locale: Intl.LocalesArgument, format: ChartFormat | undefined) {\n  if (typeof format === 'function') {\n    return (value: number) => (value > 0 ? `+${format(value)}` : format(value))\n  }\n  const formatter = numberFormatter(locale, {\n    ...format,\n    signDisplay: 'exceptZero',\n  })\n  return (value: number) => formatter.format(value)\n}\n\n/**\n * Charts in a group share the category under the pointer by its key, so\n * pointing at a day on one chart lights that day on the others, as the\n * dashboards of a product compare one day across several charts.\n */\nconst ChartGroupContext = createContext<{\n  active: string | null\n  setActive: (key: string | null) => void\n} | null>(null)\n\nfunction ChartGroup({ children }: { children: ReactNode }) {\n  const [active, setActive] = useState<string | null>(null)\n  const value = useMemo(() => ({ active, setActive }), [active])\n  return <ChartGroupContext value={value}>{children}</ChartGroupContext>\n}\n\n/** The group the chart is in, or null for a chart on its own. */\nfunction useChartGroup() {\n  return use(ChartGroupContext)\n}\n\nfunction percent(locale: Intl.LocalesArgument) {\n  return numberFormatter(locale, {\n    style: 'percent',\n    maximumFractionDigits: 0,\n  })\n}\n\n/** A change since the category before, as a share: `▲ 22%`, `▼ 4%`, or `0%` for none. */\nfunction ChangeText({\n  change,\n  locale,\n  format,\n  className,\n}: {\n  change: number | null\n  locale: Intl.LocalesArgument\n  /** Writes the size of the change; a share by default, such as `12%`. */\n  format?: (size: number) => string\n  className?: string\n}) {\n  if (change === null) return null\n  const size = format\n    ? format(Math.abs(change))\n    : percent(locale).format(Math.abs(change))\n  // A change too small to write as more than zero takes no arrow, which would say it moved.\n  const moved = /[1-9]/.test(size)\n  return (\n    // Sign and number read left to right in either direction, as a number does.\n    <span dir='ltr' className={cn('text-[0.625rem] tabular-nums', className)}>\n      {moved && change > 0 ? '▲ ' : moved && change < 0 ? '▼ ' : ''}\n      {size}\n    </span>\n  )\n}\n\n/** The part of a chart that scrolls sideways that its marks show in: inside the axes that stay at its sides. */\nfunction inView(frame: HTMLElement): { left: number; right: number } {\n  const view = frame.getBoundingClientRect()\n  let { left, right } = view\n  const middle = (view.left + view.right) / 2\n  for (const axis of frame.querySelectorAll(\n    ':scope > [data-side=start], :scope > [data-side=end]',\n  )) {\n    const box = axis.getBoundingClientRect()\n    if (box.right <= middle) left = Math.max(left, box.right)\n    else right = Math.min(right, box.left)\n  }\n  return { left, right }\n}\n\n/**\n * Measures text in the chart's own font, at medium weight, as its labels\n * are written; measured again once the page's fonts load. Before the chart\n * is drawn, it guesses from the number of characters.\n */\nfunction useTextWidth(root: RefObject<HTMLElement | null>) {\n  const [font, setFont] = useState<string | null>(null)\n  useLayoutEffect(() => {\n    const element = root.current\n    if (!element) return\n    let live = true\n    const read = () => {\n      if (!live) return\n      const style = getComputedStyle(element)\n      setFont(`500 ${style.fontSize} ${style.fontFamily}`)\n    }\n    read()\n    void document.fonts?.ready.then(read)\n    return () => {\n      live = false\n    }\n  }, [root])\n  return useMemo(() => textMeasure(font), [font])\n}\n\n/** Measures text in `font`, remembering each width; an estimate until the font is known. */\nfunction textMeasure(font: string | null) {\n  const context = font ? document.createElement('canvas').getContext('2d') : null\n  if (context && font) context.font = font\n  const widths = new Map<string, number>()\n  return (text: string) => {\n    if (!context) return labelLength(text) - 12\n    let width = widths.get(text)\n    if (width === undefined) {\n      width = context.measureText(text).width\n      widths.set(text, width)\n    }\n    return width\n  }\n}\n\nfunction useChartId() {\n  return useId().replaceAll(':', '')\n}\n\n/*\n * Moves. The root owns every move: whatever changes in one commit, such as\n * new data, a series hidden or the entrance, starts one run of the chart's\n * clock, a Web Animation timed by the feel's roles. Marks that move in a\n * straight line in CSS keep their own transitions on the same roles; what\n * redraws each frame, such as a line's path, follows the run's progress;\n * and what leaves is let go when the run ends. Nothing waits on a CSS\n * property by name.\n */\n\n/** The roles a chart's marks move on. */\ntype MoveRole = 'enter' | 'exit' | 'layout' | 'morph' | 'draw'\n\nconst MOVE_ROLES: readonly MoveRole[] = ['enter', 'exit', 'layout', 'morph', 'draw']\n\n/** A role's timing where `element` is, from the feel's variables, or null for one that doesn't run. */\nfunction roleTiming(style: CSSStyleDeclaration, role: MoveRole) {\n  const duration = durationOf(style.getPropertyValue(`--motion-${role}-duration`))\n  if (duration === null || duration <= 0) return null\n  return {\n    duration,\n    easing: style.getPropertyValue(`--motion-${role}-easing`).trim() || 'linear',\n  }\n}\n\n/** A clock for the length of a run, which the playground's Speed retimes as it does CSS. */\nfunction playClock(target: Element, timing: KeyframeEffectOptions) {\n  const clock = new Animation(new KeyframeEffect(target, null, timing), document.timeline)\n  clock.id = FOLLOWS_TRANSITION\n  clock.play()\n  return clock\n}\n\n/** How far a clock is through its role, 0 to 1 on its easing. */\nfunction clockProgress(clock: Animation) {\n  if (clock.playState === 'finished') return 1\n  return clock.effect?.getComputedTiming().progress ?? 0\n}\n\n/** A run of the clock that a part follows. */\ninterface MoveRun {\n  /** How far along it is, 0 to 1 on its role's easing. */\n  progress: () => number\n  /** Whether its role's clock is still running, stopped or not. */\n  running: () => boolean\n}\n\ntype Draw = (progress: number, done: boolean) => void\n\ninterface Follower {\n  role: MoveRole\n  /** The share of its role's duration it runs for: less than 1 when it turns back mid-move. */\n  share: number\n  draw: Draw\n  clock: Animation | null\n  stopped: boolean\n}\n\ninterface PendingRun {\n  span: number\n  ends: { resolve: () => void; travels: boolean }[]\n  followers: Follower[]\n}\n\n/**\n * The chart's moves: one run of its clock for each commit in which\n * something moves. A part asks in its layout effect, and the run starts once\n * the commit is done, in the same frame as the CSS transitions it started.\n */\ninterface ChartMoves {\n  /**\n   * Moves with this commit, its marks starting one after another over\n   * `span` of their role's duration. Resolves once the longest role has\n   * run, cascade and all, so everything has arrived or gone. A move that\n   * `travels`, such as an entrance, ends at once where motion is reduced,\n   * since travel goes; one with something fading out waits for the fade.\n   */\n  request: (span?: number, travels?: boolean) => Promise<void>\n  /**\n   * Draws with this commit's run, on `role`'s timing over `share` of its\n   * duration: `draw` gets each frame's progress, then 1 and `done`. Where\n   * motion is reduced it gets 1 at once, since travel goes. Stopped, it\n   * draws no more.\n   */\n  follow: (\n    role: MoveRole,\n    draw: Draw,\n    share: number,\n  ) => { run: MoveRun; stop: () => void }\n}\n\nfunction createChartMoves(figure: RefObject<HTMLElement | null>): ChartMoves {\n  let pending: PendingRun | null = null\n  const queue = () => {\n    if (pending) return pending\n    const next: PendingRun = { span: 0, ends: [], followers: [] }\n    pending = next\n    queueMicrotask(() => {\n      pending = null\n      start(next)\n    })\n    return next\n  }\n  return {\n    request: (span = 0, travels = false) => {\n      const run = queue()\n      run.span = Math.max(run.span, span)\n      return new Promise((resolve) => run.ends.push({ resolve, travels }))\n    },\n    follow: (role, draw, share) => {\n      const follower: Follower = {\n        role,\n        share,\n        draw,\n        clock: null,\n        stopped: false,\n      }\n      queue().followers.push(follower)\n      return {\n        run: {\n          progress: () => (follower.clock ? clockProgress(follower.clock) : 0),\n          running: () =>\n            follower.clock !== null && follower.clock.playState !== 'finished',\n        },\n        stop: () => {\n          follower.stopped = true\n        },\n      }\n    },\n  }\n\n  function start({ span, ends, followers }: PendingRun) {\n    const element = figure.current\n    const reduced = element !== null && reducesMotion(element)\n    const end = (all: boolean) => {\n      for (const { resolve, travels } of ends) if (all || travels) resolve()\n    }\n    if (!element) {\n      end(true)\n      for (const follower of followers) if (!follower.stopped) follower.draw(1, true)\n      return\n    }\n    const style = getComputedStyle(element)\n    const longest = Math.max(\n      0,\n      ...MOVE_ROLES.map((role) => roleTiming(style, role)?.duration ?? 0),\n    )\n    const whole = moveTiming(\n      longest > 0 ? { duration: longest, easing: 'linear' } : null,\n      span,\n    )\n    if (reduced) end(false)\n    if (whole) {\n      void playClock(element, {\n        duration: whole.duration,\n        endDelay: whole.endDelay,\n      }).finished.then(\n        () => end(true),\n        () => undefined,\n      )\n    } else end(true)\n    const clocks = new Map<string, Animation | null>()\n    for (const follower of followers) {\n      const key = `${follower.role} ${follower.share}`\n      if (!clocks.has(key)) {\n        const timing = reduced ? null : roleTiming(style, follower.role)\n        clocks.set(\n          key,\n          timing &&\n            playClock(element, {\n              ...timing,\n              duration: timing.duration * follower.share,\n            }),\n        )\n      }\n      follower.clock = clocks.get(key) ?? null\n    }\n    const frame = () => {\n      let moving = false\n      for (const follower of followers) {\n        if (follower.stopped) continue\n        const { clock } = follower\n        const done = clock === null || clock.playState === 'finished'\n        follower.draw(done ? 1 : travelOf(clockProgress(clock), reduced), done)\n        if (done) follower.stopped = true\n        else moving = true\n      }\n      if (moving) requestAnimationFrame(frame)\n    }\n    frame()\n  }\n}\n\n/**\n * What has left `items` and is still leaving: kept, with what it last\n * showed, until the move it left in has ended, however often another change\n * turns it round on the way. Items are told apart by `keyOf`.\n */\nfunction useLeaving<T>(\n  moves: ChartMoves,\n  items: readonly T[],\n  keyOf: (item: T) => string,\n): readonly T[] {\n  const signature = items.map(keyOf).join('\\u0000')\n  const [state, setState] = useState({\n    signature,\n    items,\n    leaving: [] as readonly T[],\n    change: 0,\n  })\n  if (state.signature !== signature) {\n    setState({\n      signature,\n      items,\n      leaving: leavingAfter(state.items, items, state.leaving, keyOf),\n      change: state.change + 1,\n    })\n  }\n  const { change, leaving } = state\n  const waiting = leaving.length > 0\n  useLayoutEffect(() => {\n    if (!waiting) return\n    let live = true\n    void moves.request().then(() => {\n      if (live) setState((was) => (was.change === change ? { ...was, leaving: [] } : was))\n    })\n    return () => {\n      live = false\n    }\n  }, [moves, waiting, change])\n  return state.signature === signature ? leaving : []\n}\n\n/** How a set of points moves: what pairs them up, and where they are part way. */\ninterface PointsMove<Point, Moves> {\n  /** Matches the points drawn now, `from`, with those they move to. */\n  align: (from: readonly Point[], to: readonly Point[]) => Moves\n  /** Where the points are `progress` of the way through `moves`. */\n  at: (moves: Moves, progress: number) => readonly Point[]\n  /** Draws the points; `moving` while a move is under way. */\n  draw: (points: readonly Point[], moving: boolean) => void\n}\n\n/**\n * Moves a set of points, such as a line's or a shape's, to `to` whenever\n * they change, `signature` telling one set from the next: from wherever\n * they are drawn, even halfway through a move, with the chart's moves on\n * `role`. The first set, and any before the chart has painted, are drawn\n * where they are; with none drawn yet, a move starts from `start`. A new\n * `redraw` alone, such as a new size, draws again at once, mid-move too.\n */\nfunction usePointsMove<Point, Moves>(\n  role: MoveRole,\n  to: readonly Point[],\n  signature: string,\n  start: readonly Point[],\n  redraw: string,\n  move: PointsMove<Point, Moves>,\n) {\n  const { moves, root } = useChartRootValue()\n  // The move under way, or the last: its points matched up, where it goes, and its run.\n  const state = useRef<{\n    moves: Moves\n    to: readonly Point[]\n    signature: string\n    /** The points the move left, by their signature, and the share of its role it runs for. */\n    from: string\n    share: number\n    run: MoveRun | null\n  } | null>(null)\n  const mounting = useRef(true)\n  const latest = useRef(move)\n  useLayoutEffect(() => {\n    latest.current = move\n  })\n  useLayoutEffect(() => {\n    const atMount = mounting.current\n    mounting.current = false\n    const was = state.current\n    // Points not drawn, while the chart loads or is empty, start again from `start`.\n    if (to.length === 0) {\n      state.current = null\n      return\n    }\n    // From where they are drawn mid-move; at rest from where they went, so the points that came\n    // in only to grow or fold a part don't stay and pile up from move to move.\n    const shown = !was\n      ? []\n      : was.run?.running()\n        ? latest.current.at(was.moves, was.run.progress())\n        : was.to\n    const matched = latest.current.align(shown.length > 0 ? shown : start, to)\n    // A chart that loads with its data shows its points where they are, with no move, until it\n    // has painted: the value axis may still settle on its ticks as the page hydrates.\n    if (atMount || !root.current?.closest('[data-mounted]')) {\n      state.current = {\n        moves: matched,\n        to,\n        signature,\n        from: signature,\n        share: 1,\n        run: null,\n      }\n      latest.current.draw(to, false)\n      return\n    }\n    // Turned back to where a move set out from, it takes as long as it has come, as a CSS\n    // transition does, so it keeps pace with the marks CSS moves.\n    const share =\n      was?.run?.running() && was.from === signature\n        ? reversedShare(was.run.progress(), was.share)\n        : 1\n    const { run, stop } = moves.follow(\n      role,\n      (progress, done) =>\n        done\n          ? latest.current.draw(to, false)\n          : latest.current.draw(latest.current.at(matched, progress), true),\n      share,\n    )\n    state.current = {\n      moves: matched,\n      to,\n      signature,\n      from: was?.signature ?? signature,\n      share,\n      run,\n    }\n    return stop\n    // The points are compared by their signature, so a new array of the same points moves nothing.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [signature])\n  // A new `redraw` with no new points draws where they are: on their way, mid-move.\n  useLayoutEffect(() => {\n    const under = state.current?.run?.running() ? state.current : null\n    if (under?.run)\n      latest.current.draw(latest.current.at(under.moves, under.run.progress()), true)\n    else latest.current.draw(to, false)\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [redraw])\n}\n\n/**\n * The share of its role's duration a move turned back to where it set out\n * runs for, as CSS shortens a reversed transition: how far the move it turns\n * from had come, on its easing, with that move's own share.\n */\nfunction reversedShare(progress: number, share: number) {\n  return Math.min(1, Math.max(0, Math.abs(progress * share + 1 - share)))\n}\n\n/**\n * `value` as it was before the last change to `key`, so what arrives can\n * start where the old value put it, such as a tick from where the old range\n * had it.\n */\nfunction useBefore<T>(value: T, key: string): T {\n  const [state, setState] = useState({ key, value, before: value })\n  if (state.key !== key) setState({ key, value, before: state.value })\n  return state.key === key ? state.before : state.value\n}\n\n/**\n * Whether what is lit now was lit from rest, for a frame: what marks it then\n * appears in place, since after a rest there is no move to explain, and\n * glides from there on. A rest begins once the last lit mark has finished\n * leaving, at the end of the move it left in, so a pointer that comes back\n * while it still fades glides on from where it is.\n */\nfunction useFromRest(spotlit: unknown) {\n  const moves = useChartMoves()\n  const [fromRest, setFromRest] = useState(false)\n  const previous = useRef(spotlit)\n  const rested = useRef(true)\n  const lit = spotlit !== null\n  useLayoutEffect(() => {\n    const before = previous.current\n    previous.current = spotlit\n    if (spotlit === null) {\n      if (before === null) return\n      rested.current = false\n      let live = true\n      void moves.request().then(() => {\n        if (live) rested.current = true\n      })\n      return () => {\n        live = false\n      }\n    }\n    setFromRest(before === null && rested.current)\n    return undefined\n    // Only lighting and letting go count, not a move from one mark to the next.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [lit, moves])\n  useEffect(() => {\n    if (!fromRest) return\n    const frame = requestAnimationFrame(() => setFromRest(false))\n    return () => cancelAnimationFrame(frame)\n  }, [fromRest])\n  return fromRest\n}\n\n/** The props every chart takes on its root, whatever its shape. */\ninterface ChartRootProps {\n  config: ChartConfig\n  /** What the chart shows, for screen readers: a short title, such as \"Visitors by month\". */\n  label: string\n  /** How values are written in the tooltip, the labels and the table. */\n  format?: ChartFormat\n  /** The locale numbers are written in. Give one, so the server and the browser agree. */\n  locale?: Intl.LocalesArgument\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 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  /** Every word the chart says or reads out, for a chart in another language. */\n  messages?: Partial<ChartMessages>\n}\n\n/** What a root keeps whatever the chart's shape, before its family adds its reader. */\ninterface ChartRootState {\n  id: string\n  label: string\n  config: ChartConfig\n  /** Every series key, in the order written in the config. */\n  series: readonly string[]\n  hidden: readonly string[]\n  setHidden: (keys: string[]) => void\n  /** The series brought forward by the legend, or by what the pointer or the keys are on. */\n  emphasis: string | null\n  setEmphasis: (key: string | null) => void\n  direction: ReadingDirection\n  locale: Intl.LocalesArgument\n  format: ChartFormat | undefined\n  /** A value as the chart's `format` writes it. */\n  valueText: (value: number) => string\n  messages: ChartMessages\n  error: ReactNode\n  onRetry: (() => void) | null\n  patternOf: (key: string) => ChartPattern\n  /** The figure. */\n  root: RefObject<HTMLElement | null>\n  /** The plot's box: the layer that takes the pointer, as large as the plot. */\n  plot: RefObject<HTMLElement | null>\n  /** The plot's size in px, once measured. */\n  plotSize: { width: number; height: number }\n  /** How wide `text` is in px, in the chart's medium-weight text. */\n  textWidth: (text: string) => number\n  /** Whether the chart has come into view, or doesn't wait to. */\n  seen: boolean\n  tooltip: TooltipController<undefined>\n  moves: ChartMoves\n}\n\n/**\n * Everything a chart keeps whatever its shape: its series and what is hidden\n * and brought forward, its words and how it writes values, its figure and\n * plot and their size, its tooltip and its moves. `entrance` waits for the\n * chart to come into view; `heightFromData` counts only a change of width as\n * a resize, for a chart whose height comes from its data.\n */\nfunction useChartRoot(\n  props: ChartRootProps,\n  { entrance, heightFromData }: { entrance: boolean; heightFromData: boolean },\n): ChartRootState {\n  const {\n    config,\n    label,\n    format,\n    locale,\n    patterns = false,\n    hiddenSeries,\n    defaultHiddenSeries = [],\n    onHiddenSeriesChange,\n    error,\n    onRetry,\n    messages,\n  } = props\n  const id = useChartId()\n  // The figure, which the moves read once each run starts, never while rendering.\n  const [root] = useState<RefObject<HTMLElement | null>>(() => ({\n    current: null,\n  }))\n  const direction = useReadingDirection(root)\n  const plot = useRef<HTMLElement | null>(null)\n  const plotSize = useSize(plot)\n  const [tooltip] = useState(() => createTooltipController<undefined>())\n  const [moves] = useState(() => createChartMoves(root))\n  const series = Object.keys(config)\n  const [hidden, setHidden] = useControllable(\n    hiddenSeries,\n    defaultHiddenSeries,\n    onHiddenSeriesChange,\n  )\n  const [emphasis, setEmphasis] = useState<string | null>(null)\n  useResizing(root, heightFromData)\n  const textWidth = useTextWidth(root)\n  const seen = useEntered(root, !entrance)\n  return {\n    id,\n    label,\n    config,\n    series,\n    hidden,\n    setHidden,\n    emphasis,\n    setEmphasis,\n    direction,\n    locale,\n    format,\n    valueText: formatterOf(locale, format),\n    messages: { ...defaultMessages, ...messages },\n    error,\n    onRetry: onRetry ?? null,\n    patternOf: (key) =>\n      config[key]?.pattern ??\n      (patterns\n        ? (patternOrder[series.indexOf(key) % patternOrder.length] ?? 'solid')\n        : 'solid'),\n    root,\n    plot,\n    plotSize,\n    textWidth,\n    seen,\n    tooltip,\n    moves,\n  }\n}\n\n/** Everything the root shows from: what it keeps, and what the chart's family adds. */\ninterface ChartRootValue extends ChartRootState {\n  status: ChartStatus\n  reader: ChartReader\n  /** The shape a series' marks take, such as a scatter's points, which its legend swatch takes; null for a plain swatch. */\n  markerOf: (key: string) => string | null\n  /** Whether a press, Enter or Space picks what it is on. */\n  selectable: boolean\n  picked: ChartTarget | null\n  /** Picks `target`, or lets it go if it was picked. */\n  togglePicked: (target: ChartTarget) => void\n}\n\nconst ChartRootContext = createContext<ChartRootValue | null>(null)\n\nfunction useChartRootValue() {\n  const value = use(ChartRootContext)\n  if (!value) throw new Error('Chart parts go inside a chart, such as a `BarChart`.')\n  return value\n}\n\nfunction useChartMoves() {\n  return useChartRootValue().moves\n}\n\n/**\n * What the pointer, the focus or the keys are on, kept apart from the rest\n * of the chart, so a hover re-renders only the parts that show it.\n */\ninterface ChartFocusValue {\n  focus: ChartTarget | null\n  setFocus: (target: ChartTarget | null) => void\n  /** What stays bright: what the focus is on, or else what is picked. */\n  spotlit: ChartTarget | null\n}\n\nconst ChartFocusContext = createContext<ChartFocusValue | null>(null)\n\nfunction useChartFocus() {\n  const value = use(ChartFocusContext)\n  if (!value) throw new Error('Chart parts go inside a chart, such as a `BarChart`.')\n  return value\n}\n\n/** The focus for a chart you control: yours, and what to tell when it moves. */\ninterface ChartFocusProps {\n  /** Yours, or undefined for the chart's own. */\n  focus: ChartTarget | null | undefined\n  defaultFocus: ChartTarget | null\n  onFocusChange: (target: ChartTarget | null) => void\n}\n\n/**\n * Keeps the focus: yours, or the group's by its key, or the chart's own,\n * held by key so new data keeps it, and let go when its key leaves the\n * chart. What the focus is on brings its series forward.\n */\nfunction ChartFocus({\n  root,\n  focus: yours,\n  defaultFocus,\n  onFocusChange,\n  children,\n}: ChartFocusProps & { root: ChartRootValue; children: ReactNode }) {\n  const { reader, picked, setEmphasis } = root\n  const group = use(ChartGroupContext)\n  const grouped = group !== null && yours === undefined\n  const [own, setOwn] = useState(defaultFocus)\n  // The focus last set, ahead of the render that shows it.\n  const ownSet = useRef(own)\n  const resolved = resolveFocus(own, yours, grouped ? group.active : undefined)\n  const focus = resolved !== null && reader.holds(resolved) ? resolved : null\n  const set = (next: ChartTarget | null) => {\n    setEmphasis(next === null ? null : reader.lights(next))\n    const kept = next !== null && reader.holds(next) ? next : null\n    if (sameTarget(kept, focus)) return\n    if (grouped) group.setActive(kept === null || kept.kind === 'node' ? null : kept.key)\n    ownSet.current = kept\n    setOwn(kept)\n    onFocusChange(kept)\n  }\n  // Yours to keep, when you pass it; the group's is held by key already.\n  const gone = own !== null && !reader.holds(own)\n  useLayoutEffect(() => {\n    // A part's effect may have set a new focus since, as the keys do once a zoom renders: that one stays.\n    if (!gone || yours !== undefined || grouped || ownSet.current !== own) return\n    ownSet.current = null\n    // eslint-disable-next-line react-hooks/set-state-in-effect -- new data took the key away, and the change is told as it lands, so it is let go here, not in render\n    setOwn(null)\n    onFocusChange(null)\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [gone, yours, grouped])\n  // One function for the chart's life, so parts that take it redraw only when what they\n  // show changes, without the React Compiler.\n  const latest = useRef(set)\n  useLayoutEffect(() => {\n    latest.current = set\n  })\n  const setFocus = useCallback((next: ChartTarget | null) => latest.current(next), [])\n  const spotlit = focus ?? (picked !== null && reader.holds(picked) ? picked : null)\n  const focusKey = focus === null ? null : JSON.stringify(focus)\n  const spotlitKey = spotlit === null ? null : JSON.stringify(spotlit)\n  const value = useMemo(\n    () => ({ focus, setFocus, spotlit }),\n    // Compared by what they are on, so a new object for the same target renders nothing.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [focusKey, setFocus, spotlitKey],\n  )\n  return <ChartFocusContext value={value}>{children}</ChartFocusContext>\n}\n\n/** Half the width the keys bring into view around a mark of a chart that scrolls, in px. */\nconst REVEAL_HALF = 8\n\n/** Where the pointer is on the plot: in px from its top left, with its size. */\nfunction plotPointOf(event: {\n  clientX: number\n  clientY: number\n  currentTarget: HTMLElement\n}) {\n  const box = event.currentTarget.getBoundingClientRect()\n  return {\n    x: event.clientX - box.left,\n    y: event.clientY - box.top,\n    width: box.width,\n    height: box.height,\n  }\n}\n\n/**\n * The layer that takes the pointer and the keys. By keyboard the plot is one\n * stop, a slider over what the reader reaches, as the WAI-ARIA slider\n * pattern has it: the reader says where each key goes, and a screen reader\n * hears what each stop holds as the slider's value. With things to pick, a\n * press, Enter or Space picks the one reached. The tooltip's one trigger\n * fills it.\n */\nfunction ChartBrowse({\n  reader,\n  agentRef,\n}: {\n  reader: ChartBrowseReader\n  /** Where the browse stop's moves go for the chart's agent primitive, as the keys run them. */\n  agentRef: RefObject<ChartAgentMoves | null>\n}) {\n  const {\n    reader: { holds, items },\n    status,\n    messages,\n    plot,\n    selectable,\n    picked,\n    togglePicked,\n    tooltip,\n  } = useChartRootValue()\n  const { focus, setFocus } = useChartFocus()\n  // Where the keys start from when focus comes back: the last stop they reached.\n  const [last, setLast] = useState<ChartTarget | null>(null)\n  // Whether the keys opened something, so they start again from its first stop once it shows.\n  const [restart, setRestart] = useState(false)\n  const ready = status === 'ready'\n  const held = (target: ChartTarget | null) =>\n    target !== null && holds(target) ? target : null\n  const resting = held(last) ?? held(picked) ?? reader.start\n  const reached = focus ?? resting\n  useLayoutEffect(() => {\n    if (!restart) return\n    // eslint-disable-next-line react-hooks/set-state-in-effect -- the first stop is the new view's, known once the zoom has rendered\n    setRestart(false)\n    setLast(null)\n    setFocus(reader.start)\n  }, [restart, reader, setFocus])\n\n  // The moves the keys and an agent share.\n  const reach = (next: ChartTarget) => {\n    setLast(next)\n    setFocus(next)\n  }\n  /** Opens `target`, as Enter does, and starts the keys again from the new view's first stop; false when it doesn't open. */\n  const openAt = (target: ChartTarget) => {\n    const zoom = reader.open(target)\n    if (!zoom) return false\n    zoom()\n    setRestart(true)\n    return true\n  }\n  /** Goes back out, as Escape does once nothing is lit; false when there is nowhere to go. */\n  const goBack = () => {\n    if (!reader.back) return false\n    reader.back()\n    setLast(null)\n    return true\n  }\n  // An agent's focus brings its stop into view, as the keys do, though the plot doesn't hold focus.\n  const agentReveal = useRef(false)\n  useLayoutEffect(() => {\n    // A row by its key, and the name an agent knows it by.\n    const rowOf = (key: string) => {\n      const name = reader.table.rows.find((row) => row.key === key)?.name ?? key\n      const target = items.find((each) => targetKey(each) === key && holds(each))\n      if (!target) throw new Error(`No row \"${name}\" in the chart now.`)\n      return { target, name }\n    }\n    agentRef.current = {\n      focus: (key) => {\n        agentReveal.current = true\n        reach(rowOf(key).target)\n      },\n      open: (key) => {\n        const { target, name } = rowOf(key)\n        if (!openAt(target)) throw new Error(`\"${name}\" doesn't open.`)\n      },\n      // As Escape: the tooltip closes first, and only then does what was opened close.\n      back: () => {\n        if (focus !== null) {\n          setFocus(null)\n          return\n        }\n        if (!goBack()) throw new Error('Nothing is focused or opened.')\n      },\n    }\n  })\n  useLayoutEffect(\n    () => () => {\n      agentRef.current = null\n    },\n    [agentRef],\n  )\n  // In a chart that scrolls sideways, the keys bring the mark they reach into view, clear of\n  // the axes that stay at its sides; the pointer only lights what is already in view.\n  const anchor = focus === null ? null : reader.anchor(focus)\n  const anchorX = anchor?.x ?? null\n  const focusKey = focus === null ? null : targetKey(focus)\n  const revealed = useRef<string | null>(null)\n  useEffect(() => {\n    if (focusKey === revealed.current) return\n    revealed.current = focusKey\n    const byAgent = agentReveal.current\n    agentReveal.current = false\n    const element = plot.current\n    const frame = element?.parentElement\n    if (\n      anchorX === null ||\n      !element ||\n      !frame ||\n      !(byAgent || element.matches(':focus-visible'))\n    )\n      return\n    if (frame.scrollWidth <= frame.clientWidth) return\n    const box = element.getBoundingClientRect()\n    const x = box.left + anchorX * box.width\n    frame.scrollTo({\n      // From where it is now, so a glide still running for the last key is replaced.\n      left:\n        frame.scrollLeft +\n        revealBy(inView(frame), {\n          left: x - REVEAL_HALF,\n          right: x + REVEAL_HALF,\n        }),\n      behavior: revealBehavior(frame),\n    })\n  }, [focusKey, anchorX, plot])\n\n  const point = (event: {\n    clientX: number\n    clientY: number\n    currentTarget: HTMLElement\n  }) => {\n    if (!ready) return\n    const target = reader.targetAt(plotPointOf(event))\n    setFocus(target)\n    // The keys come back to where the pointer was, without the series it was over.\n    const rest =\n      target?.kind === 'datum' ? { kind: 'x' as const, key: target.key } : target\n    if (held(rest)) setLast(rest)\n  }\n\n  const className = cn(\n    'focus-visible:ring-ring/50 relative z-30 min-h-0 min-w-0 rounded-(--control-radius-capped) focus-visible:outline-hidden [grid-area:plot] focus-visible:ring-3 group-data-scrolls/chart:focus-visible:ring-inset',\n    reader.orientation === 'horizontal' ? 'touch-pan-y' : 'touch-pan-x',\n  )\n  // The slider only while there is something to step through, so a screen reader doesn't\n  // find a disabled one beside the note that says why.\n  if (!ready) {\n    return (\n      <div\n        ref={plot as Ref<HTMLDivElement>}\n        tabIndex={-1}\n        data-slot='chart-columns'\n        data-chart-plot=''\n        className={className}\n      />\n    )\n  }\n\n  return (\n    <div\n      ref={plot as Ref<HTMLDivElement>}\n      role='slider'\n      tabIndex={0}\n      aria-label={messages.browse}\n      aria-orientation={reader.orientation}\n      aria-valuemin={1}\n      aria-valuemax={Math.max(1, reader.stops)}\n      aria-valuenow={reached === null ? 1 : reader.rank(reached)}\n      aria-valuetext={reached === null ? '' : reader.describe(reached)}\n      data-slot='chart-columns'\n      data-chart-plot=''\n      className={className}\n      onPointerMove={point}\n      onPointerDown={point}\n      onPointerLeave={(event) => {\n        if (event.pointerType === 'mouse') setFocus(null)\n      }}\n      onClick={(event) => {\n        if (!ready) return\n        const target = reader.targetAt(plotPointOf(event))\n        const zoom = target === null ? null : reader.open(target)\n        if (zoom) {\n          zoom()\n          return\n        }\n        if (!selectable) return\n        if (held(target)) togglePicked(target as ChartTarget)\n      }}\n      onFocus={(event) => {\n        if (ready && event.currentTarget.matches(':focus-visible')) setFocus(resting)\n      }}\n      onBlur={() => setFocus(null)}\n      onKeyDown={(event) => {\n        if (!ready || reached === null) return\n        if (event.key === 'Escape' && focus !== null) {\n          // Only the tooltip closes, not a dialog or popover the chart sits in.\n          event.preventDefault()\n          event.stopPropagation()\n          setFocus(null)\n          return\n        }\n        if (event.key === 'Escape' && reader.back) {\n          event.preventDefault()\n          event.stopPropagation()\n          goBack()\n          return\n        }\n        if ((event.key === 'Enter' || event.key === ' ') && openAt(reached)) {\n          event.preventDefault()\n          return\n        }\n        const next = reader.step(reached, event.key)\n        if (next !== null) {\n          event.preventDefault()\n          reach(next)\n          return\n        }\n        if (selectable && (event.key === 'Enter' || event.key === ' ')) {\n          event.preventDefault()\n          togglePicked(reached)\n          setFocus(reached)\n        }\n      }}\n    >\n      <TooltipTriggerPrimitive\n        controller={tooltip}\n        render={\n          <span\n            aria-hidden\n            className='pointer-events-none absolute inset-0 rounded-(--control-radius-capped)'\n          />\n        }\n      />\n    </div>\n  )\n}\n\n/** The data as a table for screen readers, which the chart's picture doesn't reach. */\nfunction ChartDataTable({ table }: { table: ChartTable }) {\n  const { status, messages } = useChartRootValue()\n  if (status !== 'ready') return null\n  // The table sits in a hidden box: a table grows to fit its cells past `sr-only`'s 1px.\n  return (\n    <div className='sr-only'>\n      <table aria-label={messages.table}>\n        <thead>\n          <tr>\n            <th scope='col'>{table.header}</th>\n            {table.columns.map((column, at) => (\n              // oxlint-disable-next-line react/no-array-index-key -- the columns are fixed\n              <th key={at} scope='col'>\n                {column}\n              </th>\n            ))}\n          </tr>\n        </thead>\n        <tbody>\n          {table.rows.map((row) => (\n            <tr key={row.key}>\n              <th scope='row'>{row.name}</th>\n              {row.cells.map((cell, at) => (\n                // oxlint-disable-next-line react/no-array-index-key -- the columns are fixed\n                <td key={at}>{cell}</td>\n              ))}\n            </tr>\n          ))}\n        </tbody>\n        {table.footer.length > 0 && (\n          <tfoot>\n            <tr>\n              <th scope='row'>{messages.total}</th>\n              {table.footer.map((cell, at) => (\n                // oxlint-disable-next-line react/no-array-index-key -- the columns are fixed\n                <td key={at}>{cell}</td>\n              ))}\n            </tr>\n          </tfoot>\n        )}\n      </table>\n    </div>\n  )\n}\n\n/**\n * What shows over the plot while there is nothing to draw, and what a\n * screen reader hears as that changes: a loading note (the chart draws its\n * own placeholder), the error and a way to try again, `empty` when there's\n * no data, or a way back when every series is hidden.\n */\nfunction ChartStatusOverlay({ empty }: { empty?: ReactNode }) {\n  const { status, series, setHidden, label, messages, error, onRetry } =\n    useChartRootValue()\n  const overlay = useRef<HTMLDivElement>(null)\n  const was = useRef(status)\n  useEffect(() => {\n    if (was.current === status) return\n    if (status === 'loading') announce(messages.loading)\n    else if (status === 'error') announce(messages.error)\n    else if (was.current === 'loading' || was.current === 'error')\n      announce(status === 'empty' ? messages.empty : messages.loaded(label))\n    was.current = status\n  })\n  const focusPlot = (run: () => void) => {\n    // The button goes once the chart shows or loads again, so focus moves to the legend, or\n    // to the plot (`data-chart-plot`), which keeps it while the chart loads.\n    const figure = overlay.current?.closest('figure')\n    flushSync(run)\n    figure\n      ?.querySelector<HTMLElement>('[data-slot=chart-legend] button, [data-chart-plot]')\n      ?.focus()\n  }\n  return (\n    <>\n      {(status === 'empty' || status === 'hidden' || status === 'error') && (\n        <div\n          ref={overlay}\n          data-slot='chart-status'\n          className='relative z-40 flex min-h-0 flex-col items-center justify-center gap-2 p-4 text-center [grid-area:plot]'\n        >\n          {status === 'empty' &&\n            (empty ?? <p className='text-muted-foreground text-sm'>{messages.empty}</p>)}\n          {status === 'error' && (\n            <>\n              {typeof error === 'string' || error === true ? (\n                <p className='text-muted-foreground text-sm'>\n                  {error === true ? messages.error : error}\n                </p>\n              ) : (\n                error\n              )}\n              {onRetry && (\n                <Button size='xs' variant='outline' onClick={() => focusPlot(onRetry)}>\n                  {messages.retry}\n                </Button>\n              )}\n            </>\n          )}\n          {status === 'hidden' && (\n            <>\n              <p className='text-muted-foreground text-sm'>{messages.allHidden}</p>\n              <Button\n                size='xs'\n                variant='outline'\n                onClick={() => focusPlot(() => setHidden([]))}\n              >\n                {messages.showAll(series.length)}\n              </Button>\n            </>\n          )}\n        </div>\n      )}\n    </>\n  )\n}\n\n/**\n * The chart's `<figure>`, named by its `label`: the series' colours, the\n * parts written inside it, then, on a chart the pointer and the keys browse\n * (`reader.browse`), the layer that takes them, the status, and the data\n * table. A chart whose marks are read and reached as they are, such as a bar\n * list's rows, each a link or a button of its own, gives `plot` to the\n * element that holds them.\n */\nfunction ChartFrame({\n  root,\n  focus,\n  slot,\n  description,\n  empty,\n  measuring,\n  inset,\n  className,\n  children,\n  ref,\n  style,\n  ...props\n}: Omit<ComponentProps<'figure'>, 'ref'> & {\n  root: ChartRootValue\n  focus: ChartFocusProps\n  slot: string\n  description?: string\n  empty?: ReactNode\n  /**\n   * Whether its scales wait for the plot's size, as labels past the bars\n   * do: until the plot is measured, everything but the legend holds its\n   * place unseen rather than show a range that then shifts.\n   */\n  measuring: boolean\n  /** The px kept clear inside each edge of the plot, as `--chart-inset`, for marks drawn round a point. */\n  inset: number\n  ref?: Ref<HTMLElement>\n}) {\n  const figure = root.root\n  const figureRef = useMemo(() => mergeRefs(figure, ref, markMounted), [figure, ref])\n  const descriptionId = `${root.id}-description`\n  const { browse } = root.reader\n  const agent = useChartAgent(root.status, browse)\n  const text = usePart(\n    agent.handle,\n    'description',\n    {},\n    { id: descriptionId, className: 'sr-only', children: description },\n    'p',\n  )\n  const frame = usePart(\n    agent.handle,\n    'root',\n    {},\n    {\n      render: <figure ref={figureRef} />,\n      // ui-sdk names the figure `data-slot='chart'`; the chart's own name is an attribute of its own.\n      [`data-${slot}`]: '',\n      'data-chart': root.id,\n      'data-measuring': measuring ? '' : undefined,\n      'aria-label': root.label,\n      // Yours, as you pass them, come after the chart's own, as on any element.\n      ...props,\n      // Your description, beside the chart's own.\n      'aria-describedby':\n        [props['aria-describedby'], description ? descriptionId : null]\n          .filter(Boolean)\n          .join(' ') || undefined,\n      className: cn(\n        chartFrameClassName,\n        // Waiting for the plot's size, everything but the legend holds its place unseen.\n        'data-measuring:*:not-data-[slot=chart-legend]:invisible',\n        // The server draws left to right, so a page in right to left shows it only once it has read its direction.\n        'rtl:not-data-mounted:*:invisible',\n        className,\n      ),\n      style: inset\n        ? ({ '--chart-inset': `${inset}px`, ...style } as CSSProperties)\n        : style,\n      children: (\n        <>\n          <ChartStyle id={root.id} config={root.config} series={root.series} />\n          {description && text}\n          {children}\n          {browse && <ChartBrowse reader={browse} agentRef={agent.moves} />}\n          <ChartStatusOverlay empty={empty} />\n          {browse && <ChartDataTable table={browse.table} />}\n        </>\n      ),\n    } as PartProps<'figure'>,\n    'figure',\n  )\n  return (\n    <ChartRootContext value={root}>\n      <ChartFocus root={root} {...focus}>\n        {frame}\n      </ChartFocus>\n    </ChartRootContext>\n  )\n}\n\n/**\n * The chart's agent primitive (`registry/lib/chart-agent.ts`): its status\n * and data table, and, on a chart the keys browse, the browse stop's moves,\n * which `ChartBrowse` hands in as it renders.\n */\nfunction useChartAgent(status: ChartStatus, browse: ChartBrowseReader | null) {\n  const [moves] = useState<RefObject<ChartAgentMoves | null>>(() => ({\n    current: null,\n  }))\n  const [delegate] = useState<ChartAgentMoves>(() => {\n    const current = () => {\n      if (!moves.current) throw new Error('The chart has nothing to browse now.')\n      return moves.current\n    }\n    return {\n      focus: (key) => current().focus(key),\n      open: (key) => current().open(key),\n      back: () => current().back(),\n    }\n  })\n  // Whether a chart browses is fixed for its life, so it keeps one primitive.\n  const handle = usePrimitive(browse ? chartPrimitive : stillChart, {\n    status,\n    table: browse?.table ?? null,\n    moves: browse ? delegate : null,\n  })\n  return { handle, moves }\n}\n\n/**\n * The tooltip's box, for a chart's `Tooltip`, which holds it against\n * `anchor`, where the marks it shows are; inside a `GlideGroupMemory`, it\n * slides as the anchor moves. The Tooltip component draws the same box.\n */\nfunction ChartTooltipBox({\n  className,\n  children,\n  side = 'top',\n  align = 'center',\n  sideOffset = 6,\n  ...props\n}: Omit<ComponentProps<typeof TooltipContentPrimitive>, 'className' | 'children'> & {\n  className?: string\n  children?: ReactNode\n}) {\n  return (\n    <TooltipContentPrimitive\n      side={side}\n      align={align}\n      sideOffset={sideOffset}\n      collisionPadding={POPUP_COLLISION_PADDING}\n      arrowPadding={0}\n      // Never under the pointer: the plot beneath keeps it, so the tooltip never closes itself.\n      className={cn(tooltipBoxClassName, 'pointer-events-none')}\n      {...props}\n    >\n      <TooltipSurface />\n      <GlideContent>\n        <div className={cn(tooltipLabelClassName, className)}>{children}</div>\n      </GlideContent>\n    </TooltipContentPrimitive>\n  )\n}\n\n/**\n * The reading direction around `root`'s element, read once it is on the page\n * and again whenever a `dir` on the page changes, so a chart in a box of its\n * own direction follows that box. It reads the element's parent unless the\n * element has a `dir` of its own: a chart that scrolls sideways sets the\n * opposite direction on its element, and reading that would flip it. A new direction\n * mirrors the chart at once, so a right-to-left page never sees it slide\n * across on load.\n */\nfunction useReadingDirection(root: RefObject<HTMLElement | null>): ReadingDirection {\n  const [direction, setDirection] = useState<ReadingDirection>('ltr')\n  const shown = useRef(direction)\n  useLayoutEffect(() => {\n    const element = root.current\n    if (!element) return\n    const resizing = holdResizing(element)\n    const read = (commit: (apply: () => void) => void) => {\n      const next = isRTL(\n        element.hasAttribute('dir') ? element : (element.parentElement ?? element),\n      )\n        ? 'rtl'\n        : 'ltr'\n      if (next === shown.current) return\n      shown.current = next\n      resizing.hold()\n      commit(() => setDirection(next))\n    }\n    // Here React commits before paint; a `dir` that changes later commits at\n    // once, so the hold is still on when the browser restyles.\n    read((apply) => apply())\n    const observer = new MutationObserver(() => read(flushSync))\n    observer.observe(document.documentElement, {\n      attributes: true,\n      attributeFilter: ['dir'],\n      subtree: true,\n    })\n    return () => {\n      observer.disconnect()\n      resizing.stop()\n    }\n  }, [root])\n  return direction\n}\n\nexport {\n  SeriesKey,\n  ChartTooltipBox,\n  type ChartBrowseReader,\n  type ChartItem,\n  type ChartFocusProps,\n  type ChartFocusValue,\n  ChartFrame,\n  type ChartFormat,\n  ChartGroup,\n  ChartLegendToggles,\n  type ChartMessages,\n  type ChartMoves,\n  type ChartPoint,\n  type ChartReader,\n  type ChartRootProps,\n  type ChartRootState,\n  type ChartRootValue,\n  ChartStyle,\n  ChartSvgPattern,\n  ChangeText,\n  ChartNumber,\n  chartFrameClassName,\n  defaultMessages,\n  drawingFrame,\n  drawingSize,\n  forcedSeriesColor,\n  forcedSeriesColors,\n  forcedSeriesTextColor,\n  isMeasured,\n  formatterOf,\n  labelOnClassName,\n  type MoveRole,\n  type MoveRun,\n  patternImage,\n  percent,\n  plotLayerClassName,\n  type PlotPoint,\n  type PointsMove,\n  seriesColor,\n  signedWriter,\n  stepBackInkClassName,\n  stepBackLayerClassName,\n  stepBackScopeClassName,\n  swatchClassName,\n  swatchStyle,\n  tooltipQuietClassName,\n  reversedShare,\n  useBefore,\n  useChartFocus,\n  useChartGroup,\n  useChartMoves,\n  useChartRoot,\n  useChartRootValue,\n  useEntered,\n  useFromRest,\n  useLeaving,\n  usePointsMove,\n  useSize,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-root.tsx"
    },
    {
      "path": "registry/lib/chart-state.ts",
      "content": "/*\n * The chart root's logic, as pure functions: what it shows, what it points\n * at, what is leaving, what its data table holds and how long a move runs.\n * It knows nothing about categories, bands or axes: each family of charts\n * turns its own shapes into these.\n */\n\n/**\n * What the pointer, the focus or the keys are on, held by key so new data\n * keeps it: every series at one x, one series' point, or one node, such as\n * a tile, an arc, a flow or a cell.\n */\nexport type ChartTarget =\n  | { kind: 'x'; key: string }\n  | { kind: 'datum'; series: string; key: string }\n  | { kind: 'node'; id: string }\n\n/** The key a target is held by among its family's items. */\nexport function targetKey(target: ChartTarget): string {\n  return target.kind === 'node' ? target.id : target.key\n}\n\n/** Whether two targets are on the same thing. */\nexport function sameTarget(a: ChartTarget | null, b: ChartTarget | null): boolean {\n  if (a === null || b === null) return a === b\n  if (a.kind !== b.kind || targetKey(a) !== targetKey(b)) return false\n  return a.kind !== 'datum' || (b.kind === 'datum' && a.series === b.series)\n}\n\n/** The series a target brings forward: a point's own; none for the rest. */\nexport function targetSeries(target: ChartTarget | null): string | null {\n  return target?.kind === 'datum' ? target.series : null\n}\n\n/** What the chart shows in place of its data. */\nexport type ChartStatus = 'loading' | 'error' | 'empty' | 'hidden' | 'ready'\n\n/**\n * What the chart shows: its placeholder while it loads, the error, a note\n * that there is no data, a way back when every series is hidden, or its\n * marks. `rows` counts the data, `shown` the series not hidden and `drawn`\n * the rows still drawn with them hidden.\n */\nexport function chartStatus({\n  placeholder,\n  loading,\n  failed,\n  rows,\n  shown,\n  drawn,\n}: {\n  placeholder: boolean\n  loading: boolean\n  failed: boolean\n  rows: number\n  shown: number\n  drawn: number\n}): ChartStatus {\n  if (placeholder || (loading && rows === 0)) return 'loading'\n  if (failed) return 'error'\n  if (rows === 0) return 'empty'\n  if (shown === 0 || drawn === 0) return 'hidden'\n  return 'ready'\n}\n\n/**\n * What is leaving once `current` replaces `previous`: what was leaving and\n * hasn't come back, and what `previous` had that `current` doesn't, each\n * once, by its key. What comes back stops leaving.\n */\nexport function leavingAfter<T>(\n  previous: readonly T[],\n  current: readonly T[],\n  leaving: readonly T[],\n  keyOf: (item: T) => string,\n): T[] {\n  const now = new Set(current.map(keyOf))\n  const seen = new Set<string>()\n  const out: T[] = []\n  for (const item of [...leaving, ...previous]) {\n    const key = keyOf(item)\n    if (now.has(key) || seen.has(key)) continue\n    seen.add(key)\n    out.push(item)\n  }\n  return out\n}\n\n/** Where `key` is among `keys`, or null when it is gone or there is none. */\nexport function indexOfKey(keys: readonly string[], key: string | null): number | null {\n  if (key === null) return null\n  const at = keys.indexOf(key)\n  return at === -1 ? null : at\n}\n\n/** One row of a chart's data table: what names it, and its cells. */\nexport interface ChartTableRow {\n  key: string\n  name: string\n  cells: readonly string[]\n}\n\n/**\n * A chart's data, for screen readers: the first column's title, the\n * columns after it, a row for each item, and a last row of totals, which is\n * empty for a chart without one.\n */\nexport interface ChartTable {\n  header: string\n  columns: readonly string[]\n  rows: readonly ChartTableRow[]\n  footer: readonly string[]\n}\n\n/** How a move runs: its role's duration, then its cascade's, in ms, on the role's easing. */\nexport interface MoveTiming {\n  duration: number\n  endDelay: number\n  easing: string\n}\n\n/**\n * The timing of a move on a role that runs `role` (its duration in ms and\n * easing, or null when it doesn't run, as when a feel gives it none), whose\n * marks start one after another over `span` of that duration. Null when\n * nothing moves, so the move ends at once.\n */\nexport function moveTiming(\n  role: { duration: number; easing: string } | null,\n  span: number,\n): MoveTiming | null {\n  if (!role || !(role.duration > 0)) return null\n  return {\n    duration: role.duration,\n    endDelay: role.duration * Math.max(0, span),\n    easing: role.easing,\n  }\n}\n\n/**\n * How far along its way a mark that redraws is, `progress` through the\n * move: all the way at once where motion is reduced, since travel goes and\n * only fades stay.\n */\nexport function travelOf(progress: number | null, reduced: boolean): number {\n  if (reduced || progress === null) return 1\n  return progress\n}\n\n/** A CSS time, such as `0.45s` or `450ms`, in ms; null for one that isn't. */\nexport function durationOf(time: string): number | null {\n  const value = Number.parseFloat(time)\n  if (!Number.isFinite(value)) return null\n  const trimmed = time.trim()\n  if (trimmed.endsWith('ms')) return value\n  if (trimmed.endsWith('s')) return value * 1000\n  return null\n}\n\n/**\n * The focus a chart shows: yours when you pass one, keeping the series the\n * chart's own focus had on the same key; else, in a group, its own focus on\n * a node, such as a tile, which no other chart holds, or the group's key,\n * the same way; else its own.\n */\nexport function resolveFocus(\n  own: ChartTarget | null,\n  yours: ChartTarget | null | undefined,\n  group: string | null | undefined,\n): ChartTarget | null {\n  const keep = (key: string) =>\n    own !== null && own.kind !== 'node' && own.key === key ? own : null\n  if (yours !== undefined) {\n    if (yours === null) return null\n    return yours.kind === 'node' ? yours : (keep(yours.key) ?? yours)\n  }\n  if (group !== undefined) {\n    if (own?.kind === 'node') return own\n    return group === null ? null : (keep(group) ?? { kind: 'x', key: group })\n  }\n  return own\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-state.ts"
    },
    {
      "path": "registry/lib/chart-agent.ts",
      "content": "import type { ChartStatus, ChartTable } from '@/registry/lib/chart-state'\nimport { definePrimitive } from '@ui-sdk/core'\n\n/*\n * A chart as an agent reads and drives it: the chart root's figure, which\n * `snapshot()` names by the chart's `label`, with its description as text,\n * its status, and its data table as its value. On a chart the keys browse,\n * `focus` moves the browse stop to the stop a row of the table names and\n * shows its tooltip, `open` does what Enter does on it, such as zooming a\n * Treemap in, and `back` what Escape does: each runs the moves the keys\n * run, which the chart hands in. A chart the keys don't browse, such as the\n * Bar list, is `stillChart`, with no table and no actions: its rows are links\n * and buttons an agent finds as they are.\n */\n\n/** A chart's data table as an agent reads it: its words, without the keys the page holds rows by. */\ninterface ChartAgentTable {\n  header: string\n  columns: readonly string[]\n  rows: readonly { name: string; cells: readonly string[] }[]\n  footer: readonly string[]\n}\n\n/** A row of the table as an item an agent names: its key as the value, its name as the label. */\ninterface ChartAgentRow {\n  value: string\n  label: string\n}\n\n/** What the browse stop does for an agent, as the keys do it. Each throws, with why, when it can't. */\ninterface ChartAgentMoves {\n  /** Moves the browse stop to the stop held by `key` and shows its tooltip. */\n  focus: (key: string) => void\n  /** Opens the stop held by `key`, as Enter does. */\n  open: (key: string) => void\n  /** Lets go of the stop the browse stop is on, and goes back out, as Escape does. */\n  back: () => void\n}\n\ntype ChartAgentOptions = {\n  status?: ChartStatus\n  /** The data table, or null on a chart the keys don't browse. An agent reads it only while the chart is `ready`. */\n  table?: ChartTable | null\n  /** The browse stop's moves, or null on a chart the keys don't browse. Fixed for the chart's life. */\n  moves?: ChartAgentMoves | null\n}\n\n/** The table's words, as `snapshot()` shows them. */\nfunction agentTable(table: ChartTable | null): ChartAgentTable | null {\n  if (table === null) return null\n  return {\n    header: table.header,\n    columns: table.columns,\n    rows: table.rows.map((row) => ({ name: row.name, cells: row.cells })),\n    footer: table.footer,\n  }\n}\n\n/** What the chart holds now: its table only once it shows, as a screen reader's table is. */\nfunction stateOf(options: ChartAgentOptions): {\n  status: ChartStatus\n  value: ChartAgentTable | null\n} {\n  const status = options.status ?? 'loading'\n  return {\n    status,\n    value: status === 'ready' ? agentTable(options.table ?? null) : null,\n  }\n}\n\n/** The table's rows as the items an agent names them by. */\nfunction agentRows(table: ChartTable | null | undefined): ChartAgentRow[] {\n  return (table?.rows ?? []).map((row) => ({\n    value: row.key,\n    label: row.name,\n  }))\n}\n\nconst chart = definePrimitive({\n  name: 'chart',\n  options: { status: 'string', table: 'value', moves: 'value' },\n  controlled: ['status', 'value'],\n  state: (options: ChartAgentOptions) => stateOf(options),\n  sync: (options) => stateOf(options),\n  api: (context) => {\n    const moves = () => {\n      const { moves: own, status } = context.options()\n      if (!own) throw new Error('This chart has nothing to browse.')\n      if (status !== 'ready') throw new Error(`The chart is ${status} now.`)\n      return own\n    }\n    return {\n      rows: () =>\n        context.options().status === 'ready' ? agentRows(context.options().table) : [],\n      /** Moves the browse stop to the row with this key, and shows its tooltip. */\n      focus: (key: string) => moves().focus(key),\n      /** Opens the row with this key, as Enter does: a Treemap or a Sunburst zooms into it. */\n      open: (key: string) => moves().open(key),\n      /** Closes the tooltip and goes back out of what was opened, as Escape does. */\n      back: () => moves().back(),\n    }\n  },\n  slots: (slot) => ({\n    root: slot({}),\n    description: slot({}),\n  }),\n  agent: {\n    actions: ['focus', 'open', 'back'],\n    closed: true,\n    items: (api) => api.rows(),\n  },\n})\n\n/** A chart the keys don't browse: its status only, since ui-sdk reads a primitive's actions once, from its definition. */\nconst stillChart = definePrimitive({\n  name: 'chart',\n  options: { status: 'string', table: 'value', moves: 'value' },\n  controlled: ['status', 'value'],\n  state: (options: ChartAgentOptions) => stateOf({ ...options, table: null }),\n  sync: (options) => stateOf({ ...options, table: null }),\n  api: () => ({}),\n  slots: (slot) => ({\n    root: slot({}),\n    description: slot({}),\n  }),\n  agent: { closed: true },\n})\n\nexport type { ChartAgentMoves, ChartAgentTable }\nexport { chart, stillChart }\n",
      "type": "registry:lib",
      "target": "@lib/chart-agent.ts"
    }
  ],
  "cssVars": {
    "light": {
      "chart-1": "oklch(0.42 0.1 248)",
      "chart-2": "oklch(0.53 0.12 222)",
      "chart-3": "oklch(0.6 0.11 185)",
      "chart-4": "oklch(0.65 0.17 132)",
      "chart-5": "oklch(0.72 0.154 106.7)",
      "chart-accent": "oklch(0.795 0.171 71.2)"
    },
    "dark": {
      "chart-1": "oklch(0.6 0.15 255)",
      "chart-2": "oklch(0.7 0.13 222)",
      "chart-3": "oklch(0.79 0.13 185)",
      "chart-4": "oklch(0.82 0.15 128)",
      "chart-5": "oklch(0.72 0.154 106.7)",
      "chart-accent": "oklch(0.795 0.171 71.2)"
    }
  },
  "type": "registry:lib"
}