{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart",
  "title": "Chart",
  "description": "The parts every chart is built from: the grid, the axes with a pill that glides to the category under the pointer, a tooltip that slides between categories, a legend that shows and hides series, reference lines and bands, and Kino’s chart colours.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/chart-frame.json",
    "https://kinoui.com/r/chart-core.json",
    "https://kinoui.com/r/chart-live.json",
    "https://kinoui.com/r/chart-root.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/dates.json",
    "https://kinoui.com/r/theme.json",
    "https://kinoui.com/r/glide.json",
    "https://kinoui.com/r/highlight.json",
    "https://kinoui.com/r/swap.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/chart.tsx",
      "content": "'use client'\n\nimport {\n  type AxisNames,\n  axisLayerClassName,\n  axisSlide,\n  type ChartAxesValue,\n  type ChartAxis,\n  type ChartFrame,\n  ChartTooltipContent,\n  ChartTooltipTotal,\n  numberAxis,\n  plotOffset,\n  slideLine,\n  stickTo,\n  TICK_SPACING,\n  tickMove,\n  timeAxis,\n  useChartAxes,\n  useDeclared,\n  useTicks,\n} from '@/registry/lib/chart-base'\nimport {\n  cartesianSignature,\n  type ChartPartDeclaration,\n} from '@/registry/lib/chart-cartesian'\nimport { VALUE_AXIS } from '@/registry/lib/chart-frame'\nimport { ChartLiveLayer } from '@/registry/lib/chart-live-clock'\nimport {\n  axisNames,\n  namePitch,\n  labelBox,\n  labelsMeet,\n  type ChartSummary,\n  physicalStart,\n  summaryOf,\n} from '@/registry/lib/chart-math'\nimport {\n  ChartTooltipBox,\n  type ChartFormat,\n  ChartGroup,\n  ChartLegendToggles,\n  formatterOf,\n  type ChartItem,\n  type ChartPoint,\n  plotLayerClassName,\n  useChartFocus,\n  SeriesKey,\n  useChartRootValue,\n} from '@/registry/lib/chart-root'\nimport { bandCentre, tickLadder, timeLadder } from '@/registry/lib/chart-scale'\nimport { type ChartTarget, sameTarget } from '@/registry/lib/chart-state'\nimport { timeTickLabel } from '@/registry/lib/dates'\nimport { GlideGroupMemory } from '@/registry/lib/glide'\nimport {\n  createHighlight,\n  type Highlight,\n  highlightClassName,\n} from '@/registry/lib/highlight'\nimport { Swap } from '@/registry/lib/swap'\nimport { Tooltip as TooltipPrimitive } from '@ui-sdk/react/tooltip'\nimport {\n  type ComponentProps,\n  type CSSProperties,\n  type ReactNode,\n  type RefObject,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The parts you write inside a chart: the grid, the axes, the legend, the\n * tooltip, and the lines and areas that mark a value. Each draws from the\n * chart it sits in, so it works the same in every kind of chart.\n */\n\n/**\n * The lines across the plot at the value axis's ticks, all alike, except\n * the one on the category axis's edge, which the names stand in for. On a\n * chart whose x is a value too, such as a scatter, lines along the plot at\n * the x axis's ticks as well. They slide to their new place when the range\n * changes, and new ones fade in from where they would have been.\n */\nfunction ChartGrid({ className, ...props }: Omit<ComponentProps<'div'>, 'children'>) {\n  const axes = useChartAxes()\n  const frame = framed(axes, 'ChartGrid')\n  const valueLayer = useRef<HTMLDivElement>(null)\n  const xLayer = useRef<HTMLDivElement>(null)\n  return (\n    <div\n      data-slot='chart-grid'\n      aria-hidden\n      className={cn(plotLayerClassName, 'z-0 overflow-visible', className)}\n      {...props}\n    >\n      <GridLines\n        layer={valueLayer}\n        axis={VALUE_AXIS}\n        line={axes.orientation === 'vertical' ? 'y' : 'x'}\n      />\n      {frame.x.scale.kind === 'linear' && <GridLines layer={xLayer} axis='x' line='x' />}\n    </div>\n  )\n}\n\n/** The grid's lines at one axis's ticks: across the plot (`y`), or along it (`x`). */\nfunction GridLines({\n  layer,\n  axis,\n  line,\n}: {\n  layer: RefObject<HTMLDivElement | null>\n  axis: ChartAxis\n  line: 'x' | 'y'\n}) {\n  const { status, direction } = useChartRootValue()\n  const axes = useChartAxes()\n  const frame = numberAxis({ frame: framed(axes, 'ChartGrid') }, axis)\n  const ladder = frame && tickLadder(frame.scale, tickSpacing[line])\n  const ticks = useTicks(frame?.scale ?? null, ladder?.ticks)\n  const id = useId()\n  if (!frame || !ladder) return null\n  const { scale, previous } = frame\n  return (\n    <div ref={layer} data-ticks={id} className='absolute inset-0 [container-type:size]'>\n      {status === 'ready' && (\n        <TickSteps\n          id={id}\n          ladder={ladder}\n          before={tickLadder(previous, tickSpacing[line])}\n          line={line}\n        />\n      )}\n      {status === 'ready' &&\n        ticks.map(({ value: tick, leaving }) => (\n          <div\n            key={tick}\n            data-leaving={leaving ? '' : undefined}\n            data-tick={tick}\n            // The line at the axis's start sits on the plot's edge, unless the chart keeps an inset.\n            data-edge={tick === scale.domain[0] && !axes.inset ? '' : undefined}\n            className={cn(\n              'border-border border-dashed data-edge:opacity-0 forced-colors:border-[GrayText]',\n              tickMove,\n              slideLine[line],\n              line === 'y' ? 'border-t' : 'border-l',\n            )}\n            style={axisSlide(line, scale.place(tick), previous.place(tick), direction)}\n          />\n        ))}\n    </div>\n  )\n}\n\n/** The chart's scales, for a part that reads them, which throws on a chart that has none, such as the Heatmap. */\nfunction framed(axes: ChartAxesValue, part: string): ChartFrame {\n  if (!axes.frame) throw new Error(`\\`${part}\\` needs a chart with a value axis.`)\n  return axes.frame\n}\n\n/** How far apart ticks stand at least, by the way they stack: values one over another, or side by side. */\nconst tickSpacing = {\n  y: TICK_SPACING.upright,\n  x: TICK_SPACING.across,\n} as const\n\n/**\n * The ticks that show at each length of a short axis, `line` the way its\n * ticks stack, by container queries, so they are right from the first\n * paint. The range stays the one the chart's tick count rounds to. A tick\n * leaving keeps what `before`, the ladder it left, showed, so one never\n * shown never shows as it goes; one the ladder hides fades as it slides.\n */\nfunction TickSteps({\n  id,\n  ladder,\n  before,\n  line,\n}: {\n  id: string\n  ladder: ReturnType<typeof tickLadder>\n  before: ReturnType<typeof tickLadder>\n  line: 'x' | 'y'\n}) {\n  const size = line === 'y' ? 'height' : 'width'\n  const gone = before.ticks.filter((tick) => !ladder.ticks.includes(tick))\n  const rules = [\n    ...ladder.steps.map((step) => [step, ladder.ticks] as const),\n    ...before.steps.map((step) => [step, gone] as const),\n  ].flatMap(([{ from, to, shown }, ticks]) => {\n    const hidden = ticks\n      .filter((tick) => !shown.includes(tick))\n      .map((tick) => `[data-ticks='${id}'] [data-tick='${tick}']`)\n    if (hidden.length === 0) return []\n    const query = [\n      from > 0 && `(${size} >= ${from}px)`,\n      to !== null && `(${size} < ${to}px)`,\n    ]\n      .filter(Boolean)\n      .join(' and ')\n    return [`@container ${query} { ${hidden.join(',')} { opacity: 0 } }`]\n  })\n  if (rules.length === 0) return null\n  // oxlint-disable-next-line react/no-danger -- the rules are worked out from the chart's own ticks\n  return <style dangerouslySetInnerHTML={{ __html: rules.join(' ') }} />\n}\n\ninterface AxisProps extends Omit<ComponentProps<'div'>, 'children'> {\n  /** How the values on a value axis are written; the chart's `format`, shortened, by default. */\n  format?: ChartFormat\n  /** How the categories on a category axis are written; the chart's `categoryFormat` by default. */\n  categoryFormat?: (value: unknown) => string\n  /** The axis's title, such as its unit; what it measures, where the chart says, by default. */\n  label?: ReactNode\n}\n\ntype AxisSide = 'start' | 'end' | 'top' | 'bottom'\n\n/**\n * The axis beside the plot: the values of upright bars, or the categories of\n * lying ones. At the reading start, or with `side='end'` at the end.\n */\nfunction ChartYAxis({\n  side = 'start',\n  axis = VALUE_AXIS,\n  format,\n  categoryFormat,\n  ...props\n}: AxisProps & {\n  side?: 'start' | 'end'\n  /** The value axis it shows, by the id series name in the config; the chart's own by default. */\n  axis?: string\n}) {\n  const { names } = useChartAxes()\n  if (names.y === null)\n    return <ValueAxis side={side} format={format} axis={axis} {...props} />\n  categoriesOnly('ChartYAxis', axis)\n  // A grid of cells names its rows down the side, and lying bars their categories.\n  return (\n    <CategoryAxis\n      side={side}\n      names={names.y}\n      categoryFormat={categoryFormat}\n      {...props}\n    />\n  )\n}\n\n/** Throws for a value axis named on an axis that shows something else, which would show none of it. */\nfunction categoriesOnly(part: string, axis: ChartAxis) {\n  if (axis === VALUE_AXIS) return\n  throw new Error(\n    `\\`${part}\\` shows no value axis here, so it can't show \\`${axis}\\`. Name it on the axis the values run along.`,\n  )\n}\n\n/**\n * The axis under the plot: the categories of upright bars, the values of\n * lying ones, or on a chart whose x is a value too, such as a scatter, its\n * x values. With `side='top'`, above it.\n */\nfunction ChartXAxis({\n  side = 'bottom',\n  axis = VALUE_AXIS,\n  format,\n  categoryFormat,\n  ...props\n}: AxisProps & {\n  side?: 'top' | 'bottom'\n  /** On lying bars, the value axis it shows, by the id series name in the config; the chart's own by default. */\n  axis?: string\n}) {\n  const { names, frame } = useChartAxes()\n  const along = frame?.x.scale.kind\n  if (along === 'time' || along === 'linear' || names.x !== null) {\n    categoriesOnly('ChartXAxis', axis)\n  }\n  if (along === 'time') {\n    if (names.x === null) throw new Error('`TimeAxis` names the times along x.')\n    return (\n      <TimeAxis\n        side={side}\n        names={names.x}\n        format={format}\n        categoryFormat={categoryFormat}\n        {...props}\n      />\n    )\n  }\n  if (along === 'linear')\n    return <ValueAxis side={side} format={format} axis='x' {...props} />\n  if (names.x === null)\n    return <ValueAxis side={side} format={format} axis={axis} {...props} />\n  // A grid of cells names its columns along it, and upright bars their categories.\n  return (\n    <CategoryAxis\n      side={side}\n      names={names.x}\n      categoryFormat={categoryFormat}\n      {...props}\n    />\n  )\n}\n\nconst axisArea = {\n  start: '[grid-area:start-axis]',\n  end: '[grid-area:end-axis]',\n  top: '[grid-area:top-axis]',\n  bottom: '[grid-area:bottom-axis]',\n} as const\n\n/** An axis's frame: its area, and its title before or after the ticks. */\nfunction AxisFrame({\n  side,\n  label,\n  slot,\n  className,\n  children,\n  ...props\n}: ComponentProps<'div'> & {\n  side: AxisSide\n  label?: ReactNode\n  slot: string\n}) {\n  const { direction } = useChartRootValue()\n  const across = side === 'start' || side === 'end'\n  const title = label && (\n    <span\n      className={cn(\n        'text-muted-foreground shrink-0 truncate font-medium',\n        // Reads upwards with no rotation where the browser can, so it renders as sharply as the\n        // ticks; a turned title is drawn softer, on Windows above all.\n        across\n          ? 'self-center [writing-mode:vertical-rl] rotate-180 supports-[writing-mode:sideways-lr]:[writing-mode:sideways-lr] supports-[writing-mode:sideways-lr]:rotate-none'\n          : 'self-center',\n      )}\n    >\n      {label}\n    </span>\n  )\n  return (\n    <div\n      data-slot={slot}\n      data-side={side}\n      className={cn(\n        'flex min-h-0 min-w-0 select-none',\n        across ? 'flex-row gap-1' : 'flex-col gap-0.5',\n        // While the chart scrolls sideways, an axis down a side stays in view over the marks\n        // passing under it, on the colour behind the chart, at the width of its names (each\n        // capped), which the plot's least width would otherwise squeeze out.\n        across &&\n          'group-data-scrolls/chart:sticky group-data-scrolls/chart:z-40 group-data-scroller/chart:min-w-max group-data-scrolls/chart:bg-(--chart-surface,var(--card))',\n        across && stickTo(side, direction),\n        axisArea[side],\n        className,\n      )}\n      {...props}\n    >\n      {(side === 'start' || side === 'top') && title}\n      {children}\n      {(side === 'end' || side === 'bottom') && title}\n    </div>\n  )\n}\n\nfunction ValueAxis({\n  side,\n  format,\n  axis = VALUE_AXIS,\n  label,\n  className,\n  ...props\n}: AxisProps & { side: AxisSide; axis?: ChartAxis }) {\n  const chart = useChartRootValue()\n  const axes = useChartAxes()\n  const { markerOf, locale, status, direction } = chart\n  const id = useId()\n  const chartFrame = framed(axes, 'ValueAxis')\n  const frame = numberAxis({ frame: chartFrame }, axis)\n  const across = side === 'start' || side === 'end'\n  const ladder = frame && tickLadder(frame.scale, tickSpacing[across ? 'y' : 'x'])\n  // The axis's own format, shortened, or the chart's.\n  const own = frame?.format ?? chart.format\n  const write = formatterOf(\n    locale,\n    format ??\n      (axes.percent && axis === VALUE_AXIS\n        ? { style: 'percent' }\n        : typeof own === 'function'\n          ? own\n          : // Shortened to 1.5K, never rounded to 2K: a whole-number format's ticks still differ.\n            {\n              ...own,\n              minimumFractionDigits: 0,\n              maximumFractionDigits: Math.max(1, own?.maximumFractionDigits ?? 1),\n              notation: 'compact',\n            }),\n  )\n  const all = useTicks(frame?.scale ?? null, ladder?.ticks, write)\n  if (!frame || !ladder) {\n    throw new Error(\n      `The chart has no value axis \\`${axis}\\`: no series in its config names it.`,\n    )\n  }\n  const { scale, previous } = frame\n  const layer = useRef<HTMLSpanElement>(null)\n  // Beside another value axis, one that holds a single series is titled with it and its key, so\n  // which axis reads which series never rests on colour.\n  const onAxis = chart.series.filter((key) => chartFrame.axisOf(key) === axis)\n  // An axis whose series are all hidden reads nothing, so its ticks fade until one shows again.\n  const reads = axis === 'x' || onAxis.some((key) => !chart.hidden.includes(key))\n  const ticks = status === 'ready' && reads ? all : []\n  const keyed =\n    axis !== 'x' && Object.keys(chartFrame.y).length > 1 && onAxis.length === 1\n      ? onAxis[0]\n      : undefined\n  const title = label ?? frame.label ?? (keyed && (chart.config[keyed]?.label ?? keyed))\n  const texts = ticks.flatMap((tick) => (tick.leaving ? [] : [tick.text]))\n  return (\n    <AxisFrame\n      side={side}\n      label={\n        keyed && title ? (\n          <span className='inline-flex items-center gap-1.5'>\n            <SeriesKey\n              series={keyed}\n              slot={chart.series.indexOf(keyed)}\n              pattern={chart.patternOf(keyed)}\n              marker={markerOf(keyed) ?? undefined}\n            />\n            {title}\n          </span>\n        ) : (\n          title\n        )\n      }\n      slot='chart-value-axis'\n      aria-hidden\n      className={className}\n      {...props}\n    >\n      <div\n        className={cn(\n          'text-muted-foreground relative grid flex-1 tabular-nums',\n          side === 'start' && 'pe-2',\n          side === 'end' && 'ps-2',\n          side === 'bottom' && 'pt-1.5',\n          side === 'top' && 'pb-1.5',\n        )}\n      >\n        {/* The widest value holds the axis open; the ticks themselves are placed. */}\n        <span className='invisible col-start-1 row-start-1 grid'>\n          {texts.map((text, at) => (\n            // oxlint-disable-next-line react/no-array-index-key -- ticks repeat no text\n            <span key={at} className='col-start-1 row-start-1 whitespace-nowrap'>\n              {text}\n            </span>\n          ))}\n        </span>\n        <span ref={layer} data-ticks={id} className={axisLayerClassName}>\n          {status === 'ready' && (\n            <TickSteps\n              id={id}\n              ladder={ladder}\n              before={tickLadder(previous, tickSpacing[across ? 'y' : 'x'])}\n              line={across ? 'y' : 'x'}\n            />\n          )}\n          {ticks.map(({ value: tick, text, leaving }) => (\n            <span\n              key={tick}\n              data-leaving={leaving ? '' : undefined}\n              data-tick={tick}\n              className={cn(tickMove, slideLine[across ? 'y' : 'x'])}\n              style={axisSlide(\n                across ? 'y' : 'x',\n                scale.place(tick),\n                previous.place(tick),\n                direction,\n              )}\n            >\n              <span\n                className={cn(\n                  'absolute whitespace-nowrap',\n                  side === 'start' && 'end-2 top-0 -translate-y-1/2',\n                  side === 'end' && 'start-2 top-0 -translate-y-1/2',\n                  // Under or over the plot, centred on the slide's physical left edge, but the\n                  // last value goes no further than the plot's edge, so it stays inside the chart:\n                  // it centres too when a chart's inset leaves it the room.\n                  side === 'bottom' && 'top-0 left-0',\n                  side === 'top' && 'bottom-0 left-0',\n                  !across &&\n                    (tick !== scale.domain[1]\n                      ? '-translate-x-1/2'\n                      : direction === 'rtl'\n                        ? 'translate-x-[max(-50%,calc(-1*var(--chart-inset,0px)))]'\n                        : 'translate-x-[min(-50%,calc(var(--chart-inset,0px)-100%))]'),\n                )}\n              >\n                {text}\n              </span>\n            </span>\n          ))}\n        </span>\n      </div>\n    </AxisFrame>\n  )\n}\n\n/** The least room between two tick labels on an axis of times, in px. */\nconst TIME_TICK_GAP = 16\n\n/**\n * The axis under a plot whose x is times: ticks on the calendar's\n * boundaries, as many as fit its width, each saying only what changed at it\n * (14:00, 17 Nov, Dec, 2027), which slide when the range changes. The\n * category axis's pill glides along it to the time under the pointer, the\n * focus or picked, naming it whole, while the ticks it would cover step\n * aside.\n */\nfunction TimeAxis({\n  side,\n  names,\n  format,\n  categoryFormat,\n  label,\n  className,\n  ...props\n}: AxisProps & { side: 'top' | 'bottom'; names: AxisNames }) {\n  const { locale, status, direction, textWidth } = useChartRootValue()\n  const axes = useChartAxes()\n  const chartFrame = framed(axes, 'TimeAxis')\n  const frame = timeAxis({ frame: chartFrame })\n  const own = format ?? frame?.format\n  const zone = frame?.scale.timeZone ?? 'UTC'\n  const write =\n    typeof own === 'function' ? own : (time: number) => timeTickLabel(time, locale, zone)\n  const tickWidth = (tick: number) => textWidth(write(tick))\n  const ladder = frame && timeLadder(frame.scale, tickWidth, TIME_TICK_GAP)\n  const all = useTicks(frame?.scale ?? null, ladder?.ticks, write)\n  const { current, spotlit, format: categoryText } = useAxisNames(names)\n  const ref = useRef<HTMLDivElement>(null)\n  const pill = useRef<HTMLSpanElement>(null)\n  const target = useRef<HTMLSpanElement>(null)\n  const [length, setLength] = useState(0)\n  useLayoutEffect(() => {\n    const element = ref.current\n    if (!element) return\n    const observer = new ResizeObserver(([entry]) => {\n      if (entry) setLength(entry.contentRect.width)\n    })\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [])\n  const highlight = useRef<Highlight | null>(null)\n  useEffect(() => {\n    const element = pill.current\n    if (!element) return\n    const created = createHighlight(element)\n    highlight.current = created\n    return () => {\n      created.stop()\n      highlight.current = null\n    }\n  }, [])\n  const litKey = spotlit === null ? null : (current[spotlit]?.key ?? null)\n  // The time the pill names: the one lit, kept once nothing is lit so the pill fades over it.\n  // Only one, since two times close together would overlap inside the pill.\n  const [named, setNamed] = useState<string | null>(null)\n  if (litKey !== null && named !== litKey) setNamed(litKey)\n  const placedIn = useRef(direction)\n  useEffect(() => {\n    const item = litKey === null ? null : target.current\n    // The page's direction read after the first paint moves every name: the pill goes with it at once.\n    if (placedIn.current !== direction && item) highlight.current?.jump(item)\n    else highlight.current?.move(item)\n    placedIn.current = direction\n  }, [litKey, length, direction])\n  const axisId = useId()\n  if (!frame || !ladder) throw new Error('`TimeAxis` goes on a chart whose x is times.')\n  const { scale } = frame\n  // A window of time scrolls by its layer: a tick stays where its time is, with nothing to\n  // slide, and goes past the axis's ends rather than being kept inside them.\n  const live = chartFrame.live\n  const previous = live ? scale : frame.previous\n  // How far the layer has moved, which a held plot shows still, as the lit name is shown.\n  const along = live ? live.offset() : 0\n  const writeName = categoryFormat ?? categoryText\n  const physical = (place: number) => (direction === 'rtl' ? 1 - place : place)\n  // A place on the axis as it shows now, where the layer has moved to.\n  const onAxis = (place: number) =>\n    physical(place) - (direction === 'rtl' ? -along : along)\n  const ticks = status === 'ready' ? all : []\n  const nameOf = (key: string) => current.find((category) => category.key === key)\n  const lit = litKey === null ? undefined : nameOf(litKey)\n  // The ticks the pill would cover, kept inside the axis as its names are.\n  const litBox =\n    lit && length > 0\n      ? labelBox(\n          onAxis(bandCentre(lit.band)),\n          textWidth(writeName(lit.value)) + 12,\n          length,\n        )\n      : null\n  const tickBox = (tick: number): readonly [number, number] => {\n    if (!live) return labelBox(physical(scale.place(tick)), tickWidth(tick), length)\n    const centre = onAxis(scale.place(tick)) * length\n    return [centre - tickWidth(tick) / 2, centre + tickWidth(tick) / 2]\n  }\n  const covered = (tick: number) =>\n    litBox !== null && labelsMeet(tickBox(tick), litBox, LABEL_GAP)\n  const shown = named === null ? undefined : nameOf(named)\n  // Where the axis as it shows now starts in its layer, physically from the left.\n  const physicalShift = direction === 'rtl' ? -along : along\n  const pillName = (copy: boolean) => {\n    // Where the name's box starts: the layer's start, or the pill's, which sits where the axis\n    // shows now.\n    const origin = copy ? physicalShift : 0\n    const from = physicalShift - origin\n    return (\n      shown && (\n        <span className={axisLayerClassName}>\n          <span\n            key={shown.key}\n            ref={copy ? undefined : target}\n            dir='auto'\n            className={cn(\n              'absolute top-0 left-0 mt-1 rounded-(--control-radius-xs) px-1.5 py-0.5 whitespace-nowrap',\n              // On the axis, the name is the pill's place; only the pill's copy shows it.\n              !copy && 'opacity-0',\n            )}\n            // Kept inside the axis as it shows now: on a live plot, the stretch the layer has moved to.\n            style={{\n              translate: `clamp(${from * 100}cqw, ${(physical(bandCentre(shown.band)) - origin) * 100}cqw - 50%, ${(1 + from) * 100}cqw - 100%) 0`,\n            }}\n          >\n            {writeName(shown.value)}\n          </span>\n        </span>\n      )\n    )\n  }\n  return (\n    <AxisFrame\n      side={side}\n      label={label ?? frame.label}\n      slot='chart-time-axis'\n      aria-hidden\n      className={className}\n      {...props}\n    >\n      <div\n        ref={ref}\n        data-axis={axisId}\n        className={cn(\n          'text-muted-foreground relative min-h-0 min-w-0 flex-1 tabular-nums [container-type:inline-size]',\n          side === 'bottom' && 'pt-1',\n          side === 'top' && 'pb-1',\n        )}\n      >\n        {/* One name's height under the plot, before any tick is placed. */}\n        <span className='invisible mt-1 block py-0.5'>&nbsp;</span>\n        <ChartLiveLayer live={live} direction={direction} fade='ends'>\n          <span data-ticks={axisId} className={axisLayerClassName}>\n            {status === 'ready' && (\n              <TickSteps\n                id={axisId}\n                ladder={ladder}\n                before={timeLadder(previous, tickWidth, TIME_TICK_GAP)}\n                line='x'\n              />\n            )}\n            {ticks.map(({ value: tick, text, leaving }) => {\n              // A tick that leaves stays kept inside the axis as it was, rather than jumping to\n              // where its place past the end would keep it.\n              const place = physical((leaving ? previous : scale).place(tick))\n              return (\n                <span\n                  key={tick}\n                  data-leaving={leaving ? '' : undefined}\n                  data-tick={tick}\n                  data-covered={!leaving && covered(tick) ? '' : undefined}\n                  className={cn(\n                    tickMove,\n                    slideLine.x,\n                    'data-covered:opacity-0',\n                    live &&\n                      'group-data-mounted/chart:transition-opacity duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing)',\n                  )}\n                  style={axisSlide(\n                    'x',\n                    scale.place(tick),\n                    previous.place(tick),\n                    direction,\n                  )}\n                >\n                  <span\n                    className='absolute top-0 left-0 mt-1 py-0.5 whitespace-nowrap transition-none group-data-mounted/chart:transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:group-data-mounted/chart:transition-none'\n                    // Centred on its time, but kept inside the axis, so a tick near either end stays in\n                    // view. Reaching an end or leaving it, it eases there as it slides. Scrolling past,\n                    // it stays centred.\n                    style={{\n                      translate: live\n                        ? '-50% 0'\n                        : `clamp(${-place * 100}cqw, -50%, ${(1 - place) * 100}cqw - 100%) 0`,\n                    }}\n                  >\n                    {text}\n                  </span>\n                </span>\n              )\n            })}\n          </span>\n        </ChartLiveLayer>\n        <ChartLiveLayer live={live} direction={direction}>\n          {pillName(false)}\n          <span\n            ref={pill}\n            data-slot='chart-category-pill'\n            className={cn(\n              highlightClassName,\n              'bg-foreground text-background z-10 forced-colors:bg-[Highlight] forced-colors:text-[HighlightText] forced-colors:forced-color-adjust-none',\n            )}\n            // On a live plot, over the stretch of its layer the axis shows now, as its name is, so\n            // the name is never cut at the layer's own end.\n            style={live ? { translate: `${physicalShift * 100}cqw 0` } : undefined}\n          >\n            {pillName(true)}\n          </span>\n        </ChartLiveLayer>\n      </div>\n    </AxisFrame>\n  )\n}\n\n/** A label is never squeezed narrower than this, in px: below it, labels are skipped instead. */\nconst MIN_LABEL = 44\n\n/** Past this many categories, labels are skipped rather than cut short. */\nconst MANY_CATEGORIES = 12\n\n/** The room between two names on the axis, in px. */\nconst LABEL_GAP = 6\n\n/**\n * The category axis. Each category's name sits under it; in a long run,\n * such as days, every few. A pill glides along the axis to the name of the\n * category under the pointer, or the one picked, which shows whole while\n * the names it would land on step aside.\n */\nfunction CategoryAxis({\n  side,\n  names: axisNamesOf,\n  categoryFormat,\n  label,\n  className,\n  ...props\n}: AxisProps & { side: AxisSide; names: AxisNames }) {\n  const { direction, status, textWidth } = useChartRootValue()\n  const across = side === 'start' || side === 'end'\n  const { all, current, spotlit, active, format, keepInside } = useAxisNames(axisNamesOf)\n  const ref = useRef<HTMLDivElement>(null)\n  const pill = useRef<HTMLSpanElement>(null)\n  const names = useRef(new Map<string, HTMLElement>())\n  const [length, setLength] = useState(0)\n  // The names move only once they have been drawn where the measured axis puts them, so\n  // nothing fades or slides in on load.\n  const [settled, setSettled] = useState(false)\n  useEffect(() => {\n    if (settled || length === 0) return\n    const frame = requestAnimationFrame(() => setSettled(true))\n    return () => cancelAnimationFrame(frame)\n  }, [settled, length])\n  useLayoutEffect(() => {\n    const element = ref.current\n    if (!element) return\n    const observer = new ResizeObserver(([entry]) => {\n      if (entry) setLength(across ? entry.contentRect.height : entry.contentRect.width)\n    })\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [across])\n  const highlight = useRef<Highlight | null>(null)\n  useEffect(() => {\n    const element = pill.current\n    if (!element) return\n    const created = createHighlight(element)\n    highlight.current = created\n    return () => {\n      created.stop()\n      highlight.current = null\n    }\n  }, [])\n  const placedIn = useRef(direction)\n  useEffect(() => {\n    const key = spotlit === null ? undefined : current[spotlit]?.key\n    const item = key === undefined ? null : (names.current.get(key) ?? null)\n    if (placedIn.current !== direction && item) highlight.current?.jump(item)\n    else highlight.current?.move(item)\n    placedIn.current = direction\n  }, [spotlit, current, length, direction])\n  const write = categoryFormat ?? format\n  // How wide a name is with its padding, measured in the chart's font.\n  const nameLength = (name: AxisNames['all'][number]) => textWidth(write(name.value)) + 12\n  // A few categories each keep a name, cut short if they must; a long run, such as days,\n  // shows every few in full instead.\n  const longest =\n    current.length > MANY_CATEGORIES\n      ? Math.max(MIN_LABEL, ...current.map(nameLength))\n      : MIN_LABEL\n  const shown = status === 'loading' ? [] : all\n  const centreOf = (name: AxisNames['all'][number]) =>\n    across\n      ? name.band.start + name.band.size / 2\n      : physicalStart(name.band, 'inline', direction) + name.band.size / 2\n  const axisNamed = current.map((category) => ({\n    centre: centreOf(category),\n    width: nameLength(category),\n  }))\n  const spacing = { minLength: longest + LABEL_GAP, gap: LABEL_GAP }\n  // Only a name under the pointer or the focus shows whole, and the names it would land on\n  // step aside; a picked one keeps its room, so its neighbours keep theirs while it stays picked.\n  const { room, skipped } =\n    across || length === 0\n      ? { room: 0, skipped: new Set<number>() }\n      : axisNames(axisNamed, length, { ...spacing, lit: active })\n  const axisId = useId()\n  // Down the side, the name the pill marks shows whole, a picked one at rest included.\n  const marked = spotlit === null ? null : (current[spotlit]?.index ?? null)\n  const acrossLit = active ?? marked\n\n  // The names, drawn twice: once on the axis, and once in the pill's colours inside the pill,\n  // which shows only the part under it, so the name it slides onto reads in its colours.\n  const layer = (copy: boolean) => (\n    <span className={axisLayerClassName}>\n      {shown.map((category) => {\n        const centre = centreOf(category)\n        const isLit =\n          (across ? acrossLit : active) === category.index && !category.leaving\n        const isSkipped =\n          !across && !isLit && !category.leaving && skipped.has(category.index)\n        return (\n          <span\n            key={category.key}\n            ref={\n              copy\n                ? undefined\n                : (element) => {\n                    if (element && !category.leaving) {\n                      names.current.set(category.key, element)\n                      return () => {\n                        if (names.current.get(category.key) === element)\n                          names.current.delete(category.key)\n                      }\n                    }\n                    return undefined\n                  }\n            }\n            data-leaving={category.leaving ? '' : undefined}\n            data-name={category.index}\n            data-active={isLit ? '' : undefined}\n            // A date or a name with digits reads in its own order whatever the page's direction.\n            dir='auto'\n            className={cn(\n              // One element both slides and is the name, so the pill finds where it is going. It\n              // moves only once the chart has painted and the axis is measured, so nothing fades in\n              // on load.\n              'absolute top-0 left-0 truncate rounded-(--control-radius-xs) px-1.5 py-0.5 transition-none duration-(--motion-layout-duration) ease-(--motion-layout-easing) data-leaving:opacity-0',\n              settled &&\n                'transition-[translate,opacity] duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-mounted/chart:starting:opacity-0 motion-reduce:transition-opacity',\n              across ? 'max-w-[calc(100%-0.125rem)]' : 'text-center',\n              side === 'bottom' && 'mt-1',\n              isSkipped && 'opacity-0',\n            )}\n            style={\n              {\n                // Its place, which `UnmeasuredAxisNames` picks names by.\n                '--axis-name': category.index,\n                // Centred on its category, but kept inside the axis, so a whole name at either\n                // end stays in view and inside the pill. Beside the plot, it sits against it. A\n                // grid's rows are each a name's height or more, so each centres on its row, and\n                // names that `AcrossAxisNames` spaces never meet at the ends.\n                translate: across\n                  ? `${(side === 'start') === (direction === 'ltr') ? 'calc(100cqw - 100% - 0.125rem)' : '0.125rem'} ${keepInside ? `clamp(0px, ${centre * 100}cqh - 50%, 100cqh - 100%)` : `calc(${centre * 100}cqh - 50%)`}`\n                  : `clamp(0px, ${centre * 100}cqw - 50%, 100cqw - 100%) 0`,\n                // Before the axis is measured, `UnmeasuredAxisNames` gives the room.\n                maxWidth: across || isLit || length === 0 ? undefined : `${room}px`,\n              } as CSSProperties\n            }\n          >\n            {write(category.value)}\n          </span>\n        )\n      })}\n    </span>\n  )\n\n  return (\n    <AxisFrame\n      side={side}\n      label={label}\n      slot='chart-category-axis'\n      aria-hidden\n      className={className}\n      {...props}\n    >\n      <div\n        ref={ref}\n        data-axis={axisId}\n        // The name the pill marks, which `AcrossAxisNames` keeps whole.\n        style={\n          across ? ({ '--axis-lit': acrossLit ?? -1e3 } as CSSProperties) : undefined\n        }\n        className={cn(\n          'text-muted-foreground relative min-h-0 min-w-0 flex-1',\n          across ? 'grid max-w-[40cqw]' : '[container-type:inline-size]',\n          side === 'start' && 'pe-1.5',\n          side === 'end' && 'ps-1.5',\n          side === 'bottom' && 'pt-1',\n          side === 'top' && 'pb-1',\n        )}\n      >\n        {across && (\n          // The longest name holds the axis open, up to its cap; the names themselves are placed.\n          <span className='invisible col-start-1 row-start-1 grid'>\n            {shown.map((category) => (\n              <span\n                key={category.key}\n                className='col-start-1 row-start-1 truncate px-1.5'\n              >\n                {write(category.value)}\n              </span>\n            ))}\n          </span>\n        )}\n        {across && <AcrossAxisNames id={axisId} count={current.length} />}\n        {!across && length === 0 && (\n          <UnmeasuredAxisNames\n            id={axisId}\n            names={axisNamed}\n            {...spacing}\n            cut={current.length <= MANY_CATEGORIES}\n          />\n        )}\n        {/* One name's height under the plot, before any name is placed. */}\n        {!across && <span className='invisible block py-0.5'>&nbsp;</span>}\n        {layer(false)}\n        <span\n          ref={pill}\n          data-slot='chart-category-pill'\n          className={cn(\n            highlightClassName,\n            'bg-foreground text-background z-10 forced-colors:bg-[Highlight] forced-colors:text-[HighlightText] forced-colors:forced-color-adjust-none',\n          )}\n        >\n          {layer(true)}\n        </span>\n      </div>\n    </AxisFrame>\n  )\n}\n\n/**\n * The names on an axis that names things, and which is under the pointer or\n * the focus (`active`) and which stays lit (`spotlit`), by place among the\n * names still in the data.\n */\nfunction useAxisNames(names: AxisNames) {\n  const { focus, spotlit } = useChartFocus()\n  return {\n    ...names,\n    spotlit: spotlit === null ? null : names.nameOf(spotlit),\n    active: focus === null ? null : names.nameOf(focus),\n  }\n}\n\n/** How tall a name on an axis down the side is, with the room it keeps from the next, in px. */\nconst ACROSS_NAME = 18\n\n/**\n * Every few names on an axis down the side, when its bands are shorter than\n * a name, such as a calendar's days: worked out by container queries on the\n * axis's height, so they are right from the first paint. The name the pill\n * marks shows whole, and those it would touch step aside.\n */\nfunction AcrossAxisNames({ id, count }: { id: string; count: number }) {\n  const scope = `[data-axis='${id}'] [data-name]:not([data-leaving])`\n  const rules: string[] = []\n  for (let every = 2; every <= count; every += 1) {\n    // Below this height, each name's band times `every - 1` is shorter than a name.\n    const below = (ACROSS_NAME * count) / (every - 1)\n    const away =\n      'max(var(--axis-name) - var(--axis-lit), var(--axis-lit) - var(--axis-name))'\n    rules.push(\n      `@container (height < ${below}px) { ${scope} { opacity: max(1 - min(1, ${away}), (1 - min(1, mod(var(--axis-name), ${every}))) * min(1, max(0, ${away} - ${every - 1}))) } }`,\n    )\n  }\n  // oxlint-disable-next-line react/no-danger -- the rules are worked out from the chart's own names\n  return <style dangerouslySetInnerHTML={{ __html: rules.join(' ') }} />\n}\n\n/**\n * The names a category axis shows before it is measured, as on the page's\n * first paint from the server: the same ones, with the same room, that\n * `axisNames` gives it once measured, worked out at widths `NAMES_SAMPLE` px\n * apart and picked by container queries on the axis's own width.\n */\nfunction UnmeasuredAxisNames({\n  id,\n  names,\n  minLength,\n  gap,\n  cut,\n}: {\n  id: string\n  names: readonly { centre: number; width: number }[]\n  minLength: number\n  gap: number\n  /** Whether a name is cut short to its room, as a few are, rather than shown whole. */\n  cut: boolean\n}) {\n  const scope = `[data-axis='${id}'] [data-name]`\n  const rules: string[] = []\n  let run: { from: number; every: number; held: string } | null = null\n  const close = (to: number | null) => {\n    if (!run) return\n    const query = [\n      run.from > NAMES_SAMPLE_FROM ? `(width >= ${run.from}px)` : '',\n      to === null ? '' : `(width < ${to}px)`,\n    ]\n      .filter(Boolean)\n      .join(' and ')\n    // Every few show, by their place in `--axis-name`, but those held back. A long run's\n    // names show whole, as once measured; a few are cut short if they must.\n    const room = cut\n      ? `; max-width: calc(100cqw * ${run.every * namePitch(names)} - ${gap}px)`\n      : ''\n    const body = `${scope} { opacity: calc(1 - min(1, mod(var(--axis-name), ${run.every})))${room} }${run.held ? ` ${scope}:is(${run.held}) { opacity: 0 }` : ''}`\n    rules.push(query ? `@container ${query} { ${body} }` : body)\n  }\n  for (\n    let width = NAMES_SAMPLE_FROM;\n    width <= NAMES_SAMPLE_UP_TO;\n    width += NAMES_SAMPLE\n  ) {\n    // Each run of widths is laid out at its middle.\n    const { every, skipped } = axisNames(names, width + NAMES_SAMPLE / 2, {\n      minLength,\n      gap,\n    })\n    // The names on the step that step aside for a neighbour.\n    const held = [...skipped]\n      .filter((index) => index % every === 0)\n      .map((index) => `[data-name='${index}']`)\n      .join(',')\n    if (run && run.every === every && run.held === held) continue\n    close(width)\n    run = { from: width, every, held }\n  }\n  close(null)\n  // oxlint-disable-next-line react/no-danger -- the rules are worked out from the chart's own names\n  return <style dangerouslySetInnerHTML={{ __html: rules.join(' ') }} />\n}\n\n/** How far apart the widths `UnmeasuredAxisNames` works its names out at are, in px, and from and to where. */\nconst NAMES_SAMPLE = 4\nconst NAMES_SAMPLE_FROM = 120\nconst NAMES_SAMPLE_UP_TO = 2560\n\n/** The value a reference line marks: worked out from the data, or the number given. */\nfunction referenceValue(\n  axes: ChartAxesValue,\n  value: number | ChartSummary | undefined,\n  axis: ChartAxis,\n) {\n  if (value === undefined || typeof value === 'number') return value ?? null\n  return summaryOf(axes.summaryValues(axis), value)\n}\n\n/** The axis a reference's values are on: the chart's own value axis unless it names another. */\nfunction referenceOn(axis: ChartAxis | undefined): ChartAxis {\n  return axis ?? VALUE_AXIS\n}\n\n/**\n * The frame's axis a reference marks: `'x'` on a chart whose x is a\n * number, or the value axis named, which an x of categories means too.\n */\nfunction referenceAxis(axes: ChartAxesValue, part: string, given: ChartAxis | undefined) {\n  const chartFrame = framed(axes, part)\n  const axis = referenceOn(given)\n  const onX = axis === 'x' && chartFrame.x.scale.kind === 'linear'\n  const id = onX ? 'x' : axis === 'x' ? VALUE_AXIS : axis\n  const frame = numberAxis({ frame: chartFrame }, id)\n  if (!frame) {\n    throw new Error(\n      `The chart has no value axis \\`${axis}\\` for its reference: no series in its config names it.`,\n    )\n  }\n  return { id, onX, live: chartFrame.live, ...frame }\n}\n\n/** A reference's name, which crossfades as it changes while the line slides. */\n/**\n * A label on a line across the page: centred on it, but held inside the\n * plot, so a line near either edge keeps its whole label in view. It slides\n * as the line does.\n */\nconst lineLabelAcross =\n  'left-0 [translate:max(calc(-1*var(--line-x)),min(-50%,calc(100cqw-var(--line-x)-100%)))_0] transition-none group-data-mounted/chart:transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:group-data-mounted/chart:transition-none'\n\n// A label at the end of a line across the categories sits above the plot, in the\n// room `LabelRoom` keeps there, where it never covers the first category's bar.\nconst labelAbove = 'bottom-full mb-1'\n\nfunction LabelRoom() {\n  return <div aria-hidden className='h-5 [grid-area:top-axis]' />\n}\n\nfunction ReferenceLabel({\n  children,\n  className,\n}: {\n  children: ReactNode\n  className?: string\n}) {\n  return (\n    <span\n      className={cn(\n        'bg-background text-foreground absolute rounded-(--control-radius-xs) px-1 font-medium whitespace-nowrap ring-1 ring-foreground/15 tabular-nums',\n        className,\n      )}\n    >\n      <Swap>{children}</Swap>\n    </span>\n  )\n}\n\n/**\n * A line across the plot that marks `value`, such as a target, or one worked\n * out from the shown data (`'average'`, `'median'`, `'min'`, `'max'`), named\n * by `label` at the axis's end or start. The value axis reaches far enough to\n * show it, and it slides when the range changes. With `category` in place of\n * `value`, it marks that category instead, such as the day of a launch. With\n * `axis='x'`, on a chart whose x is a value too, such as a scatter, it marks\n * a value on the x axis.\n */\ntype ChartReferenceLineProps = Omit<ComponentProps<'div'>, 'children'> & {\n  value?: number | ChartSummary\n  /** The key of the category to mark, in place of a value. */\n  category?: string\n  /**\n   * The axis `value` is on: the chart's value axis, another value axis by\n   * the id its series name in the config, or `'x'` on a chart whose x is a\n   * number too.\n   */\n  axis?: ChartAxis\n  label?: ReactNode | ((value: number) => ReactNode)\n  labelPosition?: 'start' | 'end'\n}\n\nfunction ChartReferenceLine(props: ChartReferenceLineProps) {\n  const {\n    value,\n    category,\n    axis,\n    label,\n    labelPosition = 'end',\n    className,\n    ...rest\n  } = props\n  useDeclared('ChartReferenceLine', ChartReferenceLine.declare(props), cartesianSignature)\n  const { direction, status } = useChartRootValue()\n  const axes = useChartAxes()\n  const { orientation } = axes\n  const {\n    id,\n    onX,\n    scale,\n    previous,\n    live: frameLive,\n  } = referenceAxis(axes, 'ChartReferenceLine', axis)\n  const marked = referenceValue(axes, value, id)\n  // Which way the line runs: a value on an x axis, or a category along one, makes a line\n  // down the plot, whose label sits above it.\n  const along =\n    category !== undefined\n      ? orientation === 'vertical'\n        ? 'x'\n        : 'y'\n      : onX || orientation === 'horizontal'\n        ? 'x'\n        : 'y'\n  // The room stays while the chart loads or fails, so the plot keeps its size.\n  const room =\n    label !== undefined && labelPosition === 'end' && along === 'x' ? <LabelRoom /> : null\n  if (status !== 'ready') return room\n  const named = typeof label === 'function' ? marked !== null && label(marked) : label\n  // A line down a live plot scrolls with its rows, so its label centres on it rather than being\n  // kept inside an axis that moves under it.\n  const live = along === 'x' ? frameLive : null\n  const scrollWith = (node: ReactNode) => (\n    <ChartLiveLayer live={live} direction={direction} reach='label' fade='ends'>\n      {node}\n    </ChartLiveLayer>\n  )\n  const moves = live\n    ? 'group-data-mounted/chart:transition-opacity duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing)'\n    : undefined\n  const labelAcross = live ? 'left-0 [translate:-50%_0]' : lineLabelAcross\n\n  if (category !== undefined) {\n    const at = axes.names[orientation === 'vertical' ? 'x' : 'y']?.current.find(\n      (name) => name.key === category,\n    )\n    if (!at) return room\n    // Across the value axis, at the category's centre.\n    const line = along\n    const centre =\n      physicalStart(at.band, orientation === 'vertical' ? 'inline' : 'block', direction) +\n      at.band.size / 2\n    const place = line === 'x' ? (direction === 'rtl' ? 1 - centre : centre) : 1 - centre\n    return (\n      <>\n        {room}\n        <div\n          data-slot='chart-reference-line'\n          className={cn(plotLayerClassName, 'z-15', className)}\n          {...rest}\n        >\n          {scrollWith(\n            <div\n              className={cn(tickMove, slideLine[line], moves)}\n              style={\n                {\n                  ...axisSlide(line, place, place, direction),\n                  '--line-x': plotOffset(place, 'cqw'),\n                } as CSSProperties\n              }\n            >\n              <div\n                className={cn(\n                  'border-foreground/60 absolute border-dashed forced-colors:border-[CanvasText]',\n                  line === 'y' ? 'inset-x-0 top-0 border-t' : 'inset-y-0 left-0 border-l',\n                )}\n              />\n              {named && (\n                <ReferenceLabel\n                  className={\n                    line === 'x'\n                      ? cn(labelAcross, labelPosition === 'end' ? labelAbove : 'bottom-0')\n                      : cn(\n                          'top-0 -translate-y-1/2',\n                          labelPosition === 'end' ? 'end-0' : 'start-0',\n                        )\n                  }\n                >\n                  {named}\n                </ReferenceLabel>\n              )}\n            </div>,\n          )}\n        </div>\n      </>\n    )\n  }\n\n  if (marked === null) return room\n  const line = along\n  return (\n    <>\n      {room}\n      <div\n        data-slot='chart-reference-line'\n        className={cn(plotLayerClassName, 'z-15', className)}\n        {...rest}\n      >\n        {scrollWith(\n          <div\n            className={cn(tickMove, slideLine[line], moves)}\n            style={\n              {\n                ...axisSlide(\n                  line,\n                  scale.place(marked),\n                  previous.place(marked),\n                  direction,\n                ),\n                '--line-x': plotOffset(\n                  direction === 'rtl' ? 1 - scale.place(marked) : scale.place(marked),\n                  'cqw',\n                ),\n              } as CSSProperties\n            }\n          >\n            <div\n              className={cn(\n                'border-foreground/60 absolute border-dashed forced-colors:border-[CanvasText]',\n                line === 'y' ? 'inset-x-0 top-0 border-t' : 'inset-y-0 left-0 border-l',\n              )}\n            />\n            {named && (\n              <ReferenceLabel\n                className={\n                  line === 'y'\n                    ? cn(\n                        'top-0 -translate-y-1/2',\n                        labelPosition === 'end' ? 'end-0' : 'start-0',\n                      )\n                    : cn(labelAcross, labelPosition === 'end' ? labelAbove : 'bottom-0')\n                }\n              >\n                {named}\n              </ReferenceLabel>\n            )}\n          </div>,\n        )}\n      </div>\n    </>\n  )\n}\n\n/**\n * A band across the plot from `from` to `to` on the value axis, such as a\n * goal range or what is normal, named by `label`. The value axis reaches far\n * enough to show it, and it moves with the range. With `axis='x'`, on a\n * chart whose x is a value too, such as a scatter, a band down the plot\n * between two x values.\n */\ntype ChartReferenceAreaProps = Omit<ComponentProps<'div'>, 'children'> & {\n  from: number\n  to: number\n  /**\n   * The axis `from` and `to` are on: the chart's value axis, another value\n   * axis by the id its series name in the config, or `'x'` on a chart whose\n   * x is a number too.\n   */\n  axis?: ChartAxis\n  label?: ReactNode\n}\n\nfunction ChartReferenceArea(props: ChartReferenceAreaProps) {\n  const { from, to, axis, label, className, ...rest } = props\n  useDeclared('ChartReferenceArea', ChartReferenceArea.declare(props), cartesianSignature)\n  const { direction, status } = useChartRootValue()\n  const axes = useChartAxes()\n  const { onX, scale } = referenceAxis(axes, 'ChartReferenceArea', axis)\n  // A band on an x axis runs down the plot, as a lying bar chart's values do.\n  const orientation = onX ? 'horizontal' : axes.orientation\n  if (status !== 'ready') return null\n  const low = scale.place(Math.min(from, to))\n  const high = scale.place(Math.max(from, to))\n  // Its edges as the plot's own places from the top, the left and the right.\n  const top = plotOffset(1 - high, 'cqh')\n  const bottom = `calc(100cqh - ${plotOffset(1 - low, 'cqh')})`\n  const left = plotOffset(direction === 'rtl' ? 1 - high : low, 'cqw')\n  const right = `calc(100cqw - ${plotOffset(direction === 'rtl' ? 1 - low : high, 'cqw')})`\n  const clip =\n    orientation === 'vertical'\n      ? `inset(${top} 0 ${bottom} 0)`\n      : `inset(0 ${right} 0 ${left})`\n  return (\n    <div\n      data-slot='chart-reference-area'\n      // Over the grid, which shows through its tint, so no grid line strikes through its label.\n      className={cn(plotLayerClassName, 'z-1', className)}\n      {...rest}\n    >\n      <div\n        className='bg-foreground/5 dark:bg-foreground/8 absolute inset-0 duration-(--motion-layout-duration) ease-(--motion-layout-easing) [clip-path:var(--area-clip)] transition-none group-data-mounted/chart:transition-[clip-path] motion-reduce:group-data-mounted/chart:transition-none forced-colors:bg-[GrayText]!'\n        style={{ '--area-clip': clip } as CSSProperties}\n      />\n      {label && (\n        <span\n          className='text-muted-foreground absolute end-1 top-1 font-medium whitespace-nowrap [translate:var(--area-label)] duration-(--motion-layout-duration) ease-(--motion-layout-easing) transition-none group-data-mounted/chart:transition-[translate] motion-reduce:group-data-mounted/chart:transition-none'\n          style={\n            {\n              // At the band's far end: its top, or the end of a band down the plot.\n              '--area-label':\n                orientation === 'vertical'\n                  ? `0 ${top}`\n                  : direction === 'rtl'\n                    ? `${left} 0`\n                    : `calc(-1 * ${right}) 0`,\n            } as CSSProperties\n          }\n        >\n          {label}\n        </span>\n      )}\n    </div>\n  )\n}\n\n// The values a reference marks join its axis's range as the chart renders; one worked out\n// from the data is in it already.\nChartReferenceLine.declare = ({\n  value,\n  category,\n  axis,\n}: ChartReferenceLineProps): ChartPartDeclaration => ({\n  references:\n    typeof value === 'number' && category === undefined\n      ? [{ axis: referenceOn(axis), value }]\n      : [],\n})\n\nChartReferenceArea.declare = ({\n  from,\n  to,\n  axis,\n}: ChartReferenceAreaProps): ChartPartDeclaration => ({\n  references: [\n    { axis: referenceOn(axis), value: from },\n    { axis: referenceOn(axis), value: to },\n  ],\n})\n\n/**\n * One toggle for each series, which shows and hides it: its colour fills the\n * swatch while it shows, and only its outline is left once hidden. Pointing\n * at one, or focusing it, brings its series forward. Above the plot, or with\n * `position='bottom'` under it.\n */\nfunction ChartLegend({\n  position = 'top',\n  className,\n  ...props\n}: Omit<ComponentProps<'div'>, 'children'> & { position?: 'top' | 'bottom' }) {\n  const {\n    series,\n    config,\n    hidden,\n    setHidden,\n    setEmphasis,\n    patternOf,\n    messages,\n    markerOf,\n  } = useChartRootValue()\n  return (\n    <div\n      data-slot='chart-legend'\n      role='group'\n      aria-label={messages.series}\n      className={cn(\n        'flex flex-wrap items-center gap-x-1 gap-y-0.5',\n        position === 'top' ? 'pb-3 [grid-area:top]' : 'pt-3 [grid-area:bottom]',\n        className,\n      )}\n      {...props}\n    >\n      <ChartLegendToggles\n        series={series}\n        labelOf={(key) => config[key]?.label ?? key}\n        patternOf={patternOf}\n        markerOf={(key) => markerOf(key) ?? undefined}\n        hidden={hidden}\n        onHiddenChange={setHidden}\n        onEmphasisChange={setEmphasis}\n      />\n    </div>\n  )\n}\n\n/** What a tooltip of your own gets for what it shows. */\ninterface ChartTooltipItem {\n  /** Its place in the data. */\n  index: number\n  /** What it shows: its key, its value under the chart's `index`, and its row, which is null for what isn't a row of the data. */\n  category: ChartItem\n}\n\ntype ChartTooltipProps = Omit<\n  ComponentProps<typeof ChartTooltipBox>,\n  'children' | 'anchor'\n> & {\n  /** Adds a row with the total of the shown values; on by default when the series stack. */\n  total?: boolean\n  /** What the tooltip shows for a category; `ChartTooltipContent` by default, which yours can wrap. */\n  children?: (item: ChartTooltipItem) => ReactNode\n}\n\n/**\n * The tooltip of the category under the pointer, the focus or the keys: its\n * name and each shown series' value, by default above the category's\n * marks. It opens at once, since it follows the pointer like a crosshair\n * rather than opening on a rest, slides from category to category, and goes\n * to where the marks are going when they move.\n */\nfunction ChartTooltip({\n  side,\n  align = 'center',\n  total,\n  className,\n  children,\n  ...props\n}: ChartTooltipProps) {\n  const { reader, tooltip, status, plot } = useChartRootValue()\n  const { focus, setFocus } = useChartFocus()\n  const { browse } = reader\n  const open = browse !== null && focus !== null && status === 'ready'\n  // What it last showed, which it keeps showing while it closes.\n  const [shown, setShown] = useState<ChartTarget | null>(null)\n  if (focus !== null && !sameTarget(focus, shown)) setShown(focus)\n  if (!browse) return null\n  const target = focus ?? shown\n  const item = target === null ? null : reader.item(target)\n  const content =\n    target === null\n      ? null\n      : children && item\n        ? children({ index: item.index, category: item })\n        : browse.tooltip(target)\n  const point = target === null ? null : browse.anchor(target)\n  return (\n    <GlideGroupMemory>\n      <TooltipPrimitive\n        controller={tooltip}\n        open={open}\n        onOpenChange={(next, details) => {\n          if (next) return\n          // The plot clears it when the pointer leaves or focus goes, so only Escape and a press\n          // away from the chart close it here. A press on the chart, or on another chart in its\n          // group, leaves the values showing.\n          if (details.reason === 'escape-key') {\n            setFocus(null)\n            return\n          }\n          if (details.reason !== 'outside-press') return\n          const pressed = details.event?.target\n          const figure = plot.current?.closest('figure')\n          if (\n            pressed instanceof Element &&\n            (figure?.contains(pressed) || pressed.closest(\"[data-slot='chart-columns']\"))\n          )\n            return\n          setFocus(null)\n        }}\n      >\n        {target !== null && (item !== null || content != null) && (\n          <ChartTooltipPopup\n            // A new side starts the popup afresh there, rather than sliding it across the marks.\n            key={point?.side}\n            point={point}\n            side={\n              side ??\n              (point?.side === 'inline-start'\n                ? 'start'\n                : point?.side === 'inline-end'\n                  ? 'end'\n                  : point?.side)\n            }\n            align={align}\n            className={className}\n            {...props}\n          >\n            <ChartTooltipTotal value={total}>{content}</ChartTooltipTotal>\n          </ChartTooltipPopup>\n        )}\n      </TooltipPrimitive>\n    </GlideGroupMemory>\n  )\n}\n\n/**\n * The tooltip's popup, on `point`, where the marks it shows are going, so it\n * never waits behind them. The point is a new anchor only when it moves, as\n * the popup sets its positioning up again for each new anchor.\n */\nfunction ChartTooltipPopup({\n  point,\n  className,\n  ...props\n}: ComponentProps<typeof ChartTooltipBox> & { point: ChartPoint | null }) {\n  const { plot } = useChartRootValue()\n  const x = point?.x ?? 0\n  const y = point?.y ?? 0\n  const anchor = useMemo(\n    () => ({\n      getBoundingClientRect: () => {\n        const box = plot.current?.getBoundingClientRect()\n        if (!box) return new DOMRect()\n        return new DOMRect(box.left + x * box.width, box.top + y * box.height, 0, 0)\n      },\n    }),\n    [plot, x, y],\n  )\n  return (\n    <ChartTooltipBox\n      sideOffset={8}\n      anchor={anchor}\n      className={cn('max-w-72 px-2.5 py-2', className)}\n      {...props}\n    />\n  )\n}\n\nexport {\n  ChartGrid,\n  ChartGroup,\n  ChartLegend,\n  ChartReferenceArea,\n  ChartReferenceLine,\n  ChartTooltip,\n  ChartTooltipContent,\n  type ChartTooltipItem,\n  ChartXAxis,\n  ChartYAxis,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/chart.tsx"
    }
  ],
  "type": "registry:component"
}