{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bar-chart",
  "title": "Bar chart",
  "description": "Values across categories, side by side, stacked, as shares or overlapped, such as this week just in front of last, upright or lying, or as a bridge from a start to an end through rises and falls. The category under the pointer stays bright while the rest step back, and every change of data, range or sort glides from where the bars are.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/chart-bar-marks.json",
    "https://kinoui.com/r/chart-frame.json",
    "https://kinoui.com/r/chart.json",
    "https://kinoui.com/r/chart-bars.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/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/bar-chart.tsx",
      "content": "'use client'\n\nimport {\n  barBand,\n  barKind,\n  barMarks,\n  type BarReading,\n  bridgeMarks,\n  bridgeSpans,\n  checkBarGap,\n  farEnd,\n  runningTotals,\n} from '@/registry/lib/chart-bar-marks'\nimport {\n  barAcross,\n  barClip,\n  BarFrameContext,\n  type BarFrameValue,\n  BarLabel,\n  type BarLabelPosition,\n  type BarPlace,\n  BarPlaceholder,\n  BarShape,\n  labelFits,\n  labelPlace,\n  missingMark,\n  NO_TUCK,\n  outsideRoom,\n  PLACEHOLDER_COUNT,\n  placeholderClip,\n  placeholderValues,\n  RIBBON_TUCK,\n  ribbonEnds,\n  type RibbonLayout,\n  ribbonClipPath,\n  ribbonsOf,\n  type RibbonTuck,\n  type StackMarks,\n  stackSeriesAt,\n  trackClip,\n  useBarFrame,\n} from '@/registry/lib/chart-bars'\nimport {\n  type ChartWords,\n  figureProps,\n  pickedName,\n  seriesWords,\n  useChartActive,\n  useDeclared,\n  useLeavingItems,\n} from '@/registry/lib/chart-base'\nimport {\n  CartesianChartFrame,\n  type CartesianChartProps,\n  type CartesianChartValue,\n  cartesianChartKeys,\n  cartesianSignature,\n  type CartesianStop,\n  cartesianTable,\n  cartesianWords,\n  type ChartPartDeclaration,\n  type ChartRoomState,\n  useCartesian,\n  useCartesianChart,\n} from '@/registry/lib/chart-cartesian'\nimport { type CartesianModel, markLayer, VALUE_AXIS } from '@/registry/lib/chart-frame'\nimport {\n  type ChartLive,\n  ChartLiveLayer,\n  LIVE_SPAN,\n} from '@/registry/lib/chart-live-clock'\nimport {\n  addsUp,\n  cascadeAt,\n  type ChartDatum,\n  type ChartOrientation,\n  type ChartStack,\n  numberOf,\n  plotPoint,\n  rangeOf,\n  type ReadingDirection,\n  type Span,\n  stacksOf,\n  stepThrough,\n} from '@/registry/lib/chart-math'\nimport {\n  type ChartFormat,\n  type ChartItem,\n  type ChartMoves,\n  type ChartPoint,\n  type ChartRootState,\n  forcedSeriesColor,\n  formatterOf,\n  patternImage,\n  plotLayerClassName,\n  seriesColor,\n  signedWriter,\n  stepBackInkClassName,\n  swatchClassName,\n  tooltipQuietClassName,\n  useBefore,\n  useChartMoves,\n  useSize,\n} from '@/registry/lib/chart-root'\nimport type { BandGaps } from '@/registry/lib/chart-scale'\nimport {\n  type ComponentProps,\n  createContext,\n  type CSSProperties,\n  use,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The Bar chart: values across categories, side by side, stacked, or as\n * shares, upright or lying. Each bar is the clip of a layer as large as the\n * plot, so a new value, a new range, a series hidden or the categories\n * sorted is one CSS transition of each bar, which turns back from wherever\n * it is. The category under the pointer stays bright while the rest step\n * back, and the tooltip sits on the end of its bars. As a bridge, one\n * series' changes float from the running total before each to the total\n * after it, joined by thin lines, with totals standing on the axis.\n */\n\ninterface BarChartProps extends CartesianChartProps {\n  /**\n   * Bars that stand on the axis, or a bridge: how a start becomes an end,\n   * such as revenue to profit. A bridge's one series holds signed changes,\n   * each floating from the running total before it, and the categories in\n   * `totals` stand on the axis. Rows keep the data's order.\n   */\n  layout?: 'bars' | 'bridge'\n  /**\n   * The categories of a bridge that stand on the axis as totals: at their\n   * value, which the run carries on from, such as an opening balance, or with\n   * none, at the running total, worked out.\n   */\n  totals?: readonly string[]\n  /** Upright bars over the categories, or bars lying along them. */\n  orientation?: ChartOrientation\n  /**\n   * How each category's series combine: side by side; stacked; stacked as\n   * shares of their total; or overlapped, where the series of one `stack`\n   * stand in front of one another from the axis, the first written at the\n   * back, such as hours booked in front of the hours there are, and the\n   * stacks sit side by side.\n   */\n  stack?: ChartStack\n  /**\n   * Joins each series' bar in one stack to its bar in the next with a soft\n   * ribbon, so its share reads across them, such as a country's cars from\n   * one year to the next. For one stack, `stacked` or `expand`; the stops\n   * then run in order, so the tooltip gives each change since the one before.\n   */\n  ribbons?: boolean\n  /**\n   * How the bars arrive the first time the chart comes into view: all\n   * rising together, rising one after another, or simply there, the\n   * default, since a page that loads doesn't animate into place.\n   */\n  entrance?: 'rise' | 'cascade' | 'none'\n  /** Where a cascade starts: the reading start, the end, the centre, or the largest value. */\n  cascadeFrom?: 'start' | 'end' | 'centre' | 'value'\n  /** The space between two categories, as a share of one category's step. */\n  categoryGap?: number\n  /**\n   * The space between bars side by side, as a share of one bar's slot, more\n   * than -1 and less than 1. Below 0 each overlaps the one before by that\n   * share, the later in front, such as this period just in front of the last.\n   */\n  barGap?: number\n  /**\n   * What each category holds, for a screen reader and the data table, in\n   * place of each series' value: a day's state in a strip of days, whose\n   * series are only its colours. `name` heads the data table's column.\n   */\n  describe?: { name: string; text: (datum: ChartDatum) => string }\n}\n\nconst barChartKeys = [\n  ...cartesianChartKeys,\n  'layout',\n  'totals',\n  'orientation',\n  'stack',\n  'ribbons',\n  'entrance',\n  'cascadeFrom',\n  'categoryGap',\n  'barGap',\n  'describe',\n]\n\n/** Every series at a stop, read along x. */\nconst X_BROWSE = { kind: 'x' } as const\n\n/** The legend's keys are plain swatches. */\nfunction noMarker() {\n  return null\n}\n\n/**\n * The chart's root: it works out each series' bars from the data, and\n * lays out the frame its parts draw in.\n */\nfunction BarChart(props: BarChartProps) {\n  const {\n    layout = 'bars',\n    totals,\n    orientation = 'vertical',\n    stack = 'none',\n    ribbons = false,\n    entrance = 'none',\n    cascadeFrom = 'start',\n    categoryGap,\n    barGap = 0.12,\n    describe,\n    description,\n    empty,\n    className,\n    children,\n    ref,\n  } = props\n  const gaps: BandGaps = categoryGap === undefined ? {} : { gap: categoryGap }\n  const isTotal = layout === 'bridge' ? bridgeTotals(props, stack, totals ?? []) : null\n  if (totals !== undefined && !isTotal) {\n    throw new Error('`totals` names the totals of a bridge: give `layout=\"bridge\"` too.')\n  }\n  if (isTotal && props.cascadeFrom !== undefined && props.cascadeFrom !== 'start') {\n    throw new Error(\n      'A bridge builds from its first step, as it reads: leave out `cascadeFrom`.',\n    )\n  }\n  if (ribbons) ribbonsAllowed(stack, props)\n  checkBarGap(barGap)\n  const kind = isTotal ? bridgeMarks(isTotal) : barMarks\n  // A bridge's bars start one after another, each as the one before has nearly landed, so none\n  // hangs in the air before the bar it starts from.\n  const cascadeFallback = isTotal\n    ? Math.min(BRIDGE_STEP_WAIT * Math.max(0, props.data.length - 1), BRIDGE_CASCADE_MOST)\n    : 0.8\n  // Ribbons join stops in order, so each one's change since the one before means something.\n  const cartesian = useCartesianChart(\n    { ...props, ordered: props.ordered ?? ribbons },\n    {\n      kinds: [kind],\n      orientation,\n      stack,\n      entrance: entrance !== 'none',\n      cascade:\n        entrance === 'cascade'\n          ? { variable: '--bar-chart-cascade', fallback: cascadeFallback }\n          : undefined,\n      gaps,\n    },\n  )\n  const { chart, model, placeholder, fromPlaceholder, phase } = cartesian\n  const stops = chart.current\n  const bridge = useBridge(chart, isTotal, totals ?? [])\n  // The bars' greatest thickness, `--bar-chart-max-thickness`, measured where the chart is.\n  const capProbe = useRef<HTMLDivElement>(null)\n  const capSize = useSize(capProbe)\n  if (ribbons) oneStack(chart, model)\n  // The cascade's order reads the bars against the chart's own value axis.\n  const shown = totalled(chart).filter(model.totals)\n  const reaches = stops.map((_, at) => farEnd(model.spans, shown, at))\n  const order = reaches\n    .map((reach, at) => ({ at, size: Math.abs(reach) }))\n    .toSorted((a, b) => b.size - a.size)\n  const cascade = stops.map((_, at) =>\n    cascadeFrom === 'value'\n      ? cascadeAt(\n          at,\n          stops.length,\n          'start',\n          order.findIndex((o) => o.at === at),\n        )\n      : cascadeAt(at, stops.length, cascadeFrom),\n  )\n  // What each stop holds, read out and in the data table, in place of each series' value.\n  const own = describe\n    ? {\n        name: describe.name,\n        text: (stop: ChartItem) => (stop.datum ? describe.text(stop.datum) : ''),\n      }\n    : null\n  const bar: BarFrameValue = {\n    model,\n    kind,\n    phase,\n    fromPlaceholder,\n    entrance,\n    cascade,\n    cascadeSpan: `var(--bar-chart-cascade, ${cascadeFallback})`,\n    barGap,\n    lights: ribbons ? 'series' : 'stop',\n  }\n  const across: RibbonLayout = {\n    orientation,\n    direction: chart.direction,\n    cap: capOf(capSize.width, chart.plotSize, orientation),\n  }\n  const words = bridge\n    ? bridgeWords(chart, bridge)\n    : seriesWords(chart, {\n        ...cartesianWords(chart, own),\n        // With ribbons, the series the keys bring forward is read out alone, so Up and Down are heard.\n        alone: ribbons ? chart.emphasis : null,\n      })\n  return (\n    <BarFrameContext value={bar}>\n      <CartesianChartFrame\n        chart={cartesian}\n        ref={ref}\n        slot='bar-chart'\n        description={description}\n        empty={empty}\n        className={className}\n        placeholder={placeholder && <BarPlaceholder chart={chart} />}\n        markerOf={noMarker}\n        // The tooltip sits on the far end of the stop's bars: the tallest, or the stack's top.\n        anchor={(stop, series) => {\n          const lit =\n            series === null ? null : segmentAnchor(chart, bar, stop, series, across)\n          if (lit) return lit\n          const along = chart.entered ? model.reach(stop.index) : null\n          return plotPoint(\n            stop.band,\n            along ?? model.baselines.value,\n            orientation,\n            chart.direction,\n          )\n        }}\n        words={words}\n        browse={\n          ribbons\n            ? {\n                kind: 'x-series',\n                seriesAt: (point) =>\n                  stackSeriesAt(\n                    stackMarks(chart, bar, across),\n                    pointAcross(point, orientation, chart.direction),\n                    across,\n                  ),\n                step: (at, from, step) =>\n                  stepThrough(segmentsOutward(chart, bar, at), from, step),\n              }\n            : X_BROWSE\n        }\n        {...figureProps(props, barChartKeys)}\n      >\n        {/* The bars' greatest thickness, measured, for where the pointer lands on a stack with\n        ribbons and where its tooltip sits. Always there, so ribbons turned on later find it measured. */}\n        <div\n          ref={capProbe}\n          aria-hidden\n          className='invisible absolute h-0 w-(--bar-chart-max-thickness,4rem)'\n        />\n        {ribbons && <BarRibbons layout={across} />}\n        <BridgeContext value={bridge}>{children}</BridgeContext>\n      </CartesianChartFrame>\n    </BarFrameContext>\n  )\n}\n\n/* Ribbons. */\n\n/** Throws on a chart ribbons can't join: one whose bars stand side by side. */\nfunction ribbonsAllowed(stack: ChartStack, props: object) {\n  if (!addsUp(stack)) {\n    throw new Error(\n      \"Ribbons join each series from one stack to the next, which they add up to: give `stack='stacked'` or `stack='expand'` too.\",\n    )\n  }\n  // A bar chart's type has no window of time, but a chart written in JavaScript can pass one.\n  const { window, live } = props as { window?: number; live?: boolean }\n  if (window !== undefined || live) {\n    throw new Error(\n      'Ribbons join stacks that stand still: leave out `window` and `live`.',\n    )\n  }\n}\n\n/** Throws when the bars stand in more than one stack, whose ribbons would cross each other. */\nfunction oneStack(chart: CartesianChartValue, model: CartesianModel) {\n  const bars = chart.series.filter((key) => model.markOf(key) === 'bar')\n  if (stacksOf(bars, model.stackOf).length > 1) {\n    throw new Error(\n      'Ribbons join one stack across the categories: give every `Bar` the same `stack` and axis in the config, and no rows of its own.',\n    )\n  }\n}\n\n/** The bars' greatest thickness, `px`, as a share of the plot across the categories; no cap before either is measured. */\nfunction capOf(\n  px: number,\n  plot: { width: number; height: number },\n  orientation: ChartOrientation,\n) {\n  const across = orientation === 'vertical' ? plot.width : plot.height\n  return px > 0 && across > 0 ? px / across : Number.POSITIVE_INFINITY\n}\n\n/**\n * A point the pointer is on, from the reading start and the top as the\n * reader hands it, as the ribbons read it: across the categories from the\n * physical left (upright) or the top (lying), and along the value axis.\n */\nfunction pointAcross(\n  point: { x: number; y: number },\n  orientation: ChartOrientation,\n  direction: ReadingDirection,\n) {\n  return orientation === 'vertical'\n    ? {\n        across: direction === 'rtl' ? 1 - point.x : point.x,\n        along: 1 - point.y,\n      }\n    : { across: point.y, along: point.x }\n}\n\n/** The part of a category's band the bar of `key` at `stop` takes, beside the chart's other stacks. */\nfunction bandOf(\n  chart: CartesianChartValue,\n  bar: BarFrameValue,\n  stop: CartesianStop,\n  key: string,\n) {\n  return barBand(\n    stop.band,\n    key,\n    chart.series.filter((k) => bar.model.markOf(k) === 'bar'),\n    chart.hidden,\n    chart.stack,\n    bar.model.stackOf,\n    bar.barGap,\n    (k) => chart.rowOf(k, stop) !== null,\n  )\n}\n\n/**\n * Where the bar of `key` at `stop` stands once risen: a hidden series' where\n * it would stack, so its ribbons collapse with it; null with no value.\n */\nfunction standingPlace(\n  chart: CartesianChartValue,\n  bar: BarFrameValue,\n  stop: CartesianStop,\n  key: string,\n): BarPlace | null {\n  const span = bar.model.spans[key]?.[stop.index]\n  if (!span) return null\n  const { scale } = bar.model.valueAxisOf(key)\n  return {\n    band: bandOf(chart, bar, stop, key),\n    from: scale.place(span[0]),\n    to: scale.place(span[1]),\n  }\n}\n\n/** One series' ribbon from the stack at `from` to the next, by their keys, and where its two bars stand. */\ninterface Ribbon {\n  key: string\n  series: string\n  from: string\n  to: string\n  start: BarPlace\n  end: BarPlace\n  /** Whether its bar at each end is the outermost of its stack, whose far corners are rounded. */\n  outer: readonly [boolean, boolean]\n}\n\n/** The chart's ribbons between its stops, each where its bars stand, a hidden series' collapsed. */\nfunction ribbonsAt(chart: CartesianChartValue, bar: BarFrameValue): Ribbon[] {\n  const stops = chart.current\n  const bars = chart.series.filter((key) => bar.model.markOf(key) === 'bar')\n  return ribbonsOf(bars, stops.length, (key, at) => {\n    const stop = stops[at]\n    return stop ? chart.valueOf(key, stop) : null\n  }).flatMap((pair) => {\n    const from = stops[pair.from]\n    const to = stops[pair.to]\n    const start = from && standingPlace(chart, bar, from, pair.series)\n    const end = to && standingPlace(chart, bar, to, pair.series)\n    if (!from || !to || !start || !end) return []\n    return [\n      {\n        key: `${pair.series}\\u0000${from.key}\\u0000${to.key}`,\n        series: pair.series,\n        from: from.key,\n        to: to.key,\n        start,\n        end,\n        outer: [\n          isOutermost(chart, bar, from, pair.series),\n          isOutermost(chart, bar, to, pair.series),\n        ] as const,\n      },\n    ]\n  })\n}\n\n/** The bars and ribbons the pointer can land on: the shown series' only, once the bars have risen. */\nfunction stackMarks(\n  chart: CartesianChartValue,\n  bar: BarFrameValue,\n  layout: RibbonLayout,\n): StackMarks {\n  if (!chart.entered) return { bars: [], ribbons: [] }\n  const shown = (key: string) => !chart.hidden.includes(key)\n  return {\n    bars: chart.current.flatMap((stop) =>\n      chart.series.filter(shown).flatMap((series) => {\n        const place = standingPlace(chart, bar, stop, series)\n        return place ? [{ series, place }] : []\n      }),\n    ),\n    ribbons: ribbonsAt(chart, bar)\n      .filter((ribbon) => shown(ribbon.series))\n      .map((ribbon) => ({\n        series: ribbon.series,\n        ends: ribbonEnds(ribbon.start, ribbon.end, layout),\n      })),\n  }\n}\n\n/** The shown series with a bar at the stop at `index`, the one furthest along the value axis first, as they stand. */\nfunction segmentsOutward(chart: CartesianChartValue, bar: BarFrameValue, index: number) {\n  const stop = chart.current[index]\n  if (!stop) return []\n  return chart.series\n    .filter((key) => !chart.hidden.includes(key))\n    .flatMap((key) => {\n      const place = standingPlace(chart, bar, stop, key)\n      return place ? [{ key, middle: (place.from + place.to) / 2 }] : []\n    })\n    .toSorted((a, b) => b.middle - a.middle)\n    .map(({ key }) => key)\n}\n\n/**\n * Where the tooltip of a lit series sits on its bar at `stop`: beside it at\n * its middle, upright, or above it, lying, so it covers none of the stack;\n * null where the series has no bar.\n */\nfunction segmentAnchor(\n  chart: CartesianChartValue,\n  bar: BarFrameValue,\n  stop: CartesianStop,\n  series: string,\n  layout: RibbonLayout,\n): ChartPoint | null {\n  const place = chart.entered ? standingPlace(chart, bar, stop, series) : null\n  if (!place) return null\n  const { centre, half } = barAcross(place, layout)\n  const middle = (place.from + place.to) / 2\n  if (layout.orientation === 'vertical') {\n    return {\n      x: centre + (layout.direction === 'rtl' ? -half : half),\n      y: 1 - middle,\n      side: 'inline-end',\n    }\n  }\n  return {\n    x: layout.direction === 'rtl' ? 1 - middle : middle,\n    y: centre - half,\n    side: 'top',\n  }\n}\n\n/** Where a ribbon's draw along its length starts: at the stack it leaves, or at the one it meets. */\nfunction wipeFrom(\n  origin: 'from' | 'to',\n  orientation: ChartOrientation,\n  direction: ReadingDirection,\n) {\n  // The clip that hides all but the side it grows from, as `inset()` sides: top, right, bottom, left.\n  const start =\n    orientation === 'vertical' ? (direction === 'rtl' ? 'right' : 'left') : 'top'\n  const side = origin === 'from' ? start : OPPOSITE[start]\n  const sides = { top: '0', right: '0', bottom: '0', left: '0' }\n  sides[OPPOSITE[side]] = '100%'\n  return `inset(${sides.top} ${sides.right} ${sides.bottom} ${sides.left})`\n}\n\nconst OPPOSITE = {\n  top: 'bottom',\n  bottom: 'top',\n  left: 'right',\n  right: 'left',\n} as const\n\n/**\n * The columns that stand still: those there before the last change to `keys`\n * while it moves, and all of them once its move has ended, so a ribbon to a\n * column that arrived runs on under its bars from then.\n */\nfunction useStood(moves: ChartMoves, keys: readonly string[]) {\n  const joined = keys.join('\\u0000')\n  const before = useBefore(keys, joined)\n  const [settled, setSettled] = useState(joined)\n  useLayoutEffect(() => {\n    if (settled === joined) return\n    let live = true\n    void moves.request().then(() => {\n      if (live) setSettled(joined)\n    })\n    return () => {\n      live = false\n    }\n  }, [moves, joined, settled])\n  return settled === joined ? keys : before\n}\n/**\n * The ribbons: a layer under the bars, each series' ribbons in its colour,\n * faint, brighter while its series is lit and stepping back with its bars.\n * Each is a clip of the plot that moves on the same transition as the bars'\n * clips, so it lands with them and turns back with them; a new one draws\n * along its length from the stack that stood before, and one that leaves\n * fades where it was.\n */\nfunction BarRibbons({ layout }: { layout: RibbonLayout }) {\n  const chart = useCartesian()\n  const bar = useBarFrame()\n  const moves = useChartMoves()\n  const ready = chart.status === 'ready'\n  // Each time the data comes back, such as after a reload, its ribbons are new elements, so one\n  // still fading out draws in again with its stacks rather than coming back where it stood.\n  const [arrival, setArrival] = useState({ ready, count: 0 })\n  if (arrival.ready !== ready) {\n    setArrival({ ready, count: arrival.count + (ready ? 1 : 0) })\n  }\n  const ribbons = ready\n    ? ribbonsAt(chart, bar).map((ribbon) => ({\n        ...ribbon,\n        arrival: arrival.count,\n      }))\n    : NO_RIBBONS\n  // In key order, current and leaving alike, so no ribbon's element moves in the page, which\n  // would restart its wipe and drop its fade.\n  const drawn = useLeavingItems(moves, ribbons, ribbonKey)\n  const keys = chart.current.map((stop) => stop.key)\n  const stood = useStood(moves, keys)\n  const at = new Map(chart.current.map((stop) => [stop.key, stop.index]))\n  const { orientation, direction } = layout\n  const entrance = bar.phase !== 'settled' && bar.entrance !== 'none'\n  // A ribbon runs on under its bars, and behind an outermost bar's rounded corner, which it\n  // fills; one that leaves stops at their edges, since its bars go without it.\n  const tuck = (outer: boolean, leaving: boolean): RibbonTuck =>\n    leaving ? NO_TUCK : { share: RIBBON_TUCK, corner: outer }\n  return (\n    <div\n      data-slot='bar-chart-ribbons'\n      aria-hidden\n      // Under the bars, which cover the ends of their ribbons. Only where a browser can draw a\n      // ribbon's shape: elsewhere its unclipped layer would cover the plot.\n      className={cn(\n        plotLayerClassName,\n        'z-7 hidden supports-[clip-path:shape(from_0_0,line_to_1px_1px)]:block',\n      )}\n    >\n      {chart.series.map((series) => {\n        const own = drawn.filter((ribbon) => ribbon.series === series)\n        if (own.length === 0) return null\n        const lit = chart.emphasis === series\n        return (\n          <div\n            key={series}\n            data-series={series}\n            data-lit={lit ? '' : undefined}\n            data-dim={chart.emphasis !== null && !lit ? '' : undefined}\n            className={cn(\n              'absolute inset-0 opacity-(--bar-chart-ribbon,0.24) transition-none duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing) group-data-mounted/chart:transition-opacity data-lit:opacity-[calc(var(--bar-chart-ribbon,0.24)*2)]',\n              stepBackInkClassName,\n            )}\n            style={{ '--mark-color': seriesColor(series) } as CSSProperties}\n          >\n            {own.map((ribbon) => {\n              const fresh = !stood.includes(ribbon.from) || !stood.includes(ribbon.to)\n              const later = at.get(ribbon.to) ?? 0\n              // On the entrance, a ribbon waits for its later stack to rise; a new one, for a\n              // new stack to grow.\n              const wait = entrance\n                ? `calc(var(--motion-draw-duration) * ${bar.entrance === 'cascade' ? `(${bar.cascadeSpan} * ${bar.cascade[later] ?? 0} + 1)` : 1})`\n                : fresh\n                  ? 'var(--motion-layout-duration)'\n                  : '0s'\n              const leaving = Boolean(ribbon.leaving)\n              return (\n                <div\n                  key={`${ribbon.key}\\u0000${ribbon.arrival}`}\n                  data-waiting={bar.phase === 'waiting' ? '' : undefined}\n                  data-leaving={leaving ? '' : undefined}\n                  className='absolute inset-0 [clip-path:inset(0)] transition-none group-data-mounted/chart:[transition:clip-path_var(--motion-draw-duration)_var(--motion-draw-easing)_var(--ribbon-wait),opacity_var(--motion-exit-duration)_var(--motion-exit-fade-easing)] group-data-mounted/chart:starting:[clip-path:var(--ribbon-hidden)] data-leaving:opacity-0 data-waiting:[clip-path:var(--ribbon-hidden)] motion-reduce:group-data-mounted/chart:[transition:opacity_var(--motion-exit-duration)_var(--motion-exit-fade-easing)]'\n                  style={\n                    {\n                      '--ribbon-hidden': wipeFrom(\n                        stood.includes(ribbon.from) || !stood.includes(ribbon.to)\n                          ? 'from'\n                          : 'to',\n                        orientation,\n                        direction,\n                      ),\n                      '--ribbon-wait': wait,\n                    } as CSSProperties\n                  }\n                >\n                  <div\n                    data-entering={bar.phase === 'entering' ? '' : undefined}\n                    className='absolute inset-0 bg-(--mark-ink) transition-none duration-(--motion-layout-duration) ease-[var(--motion-layout-fade-easing),var(--motion-layout-easing)] [clip-path:var(--ribbon-clip)] group-data-mounted/chart:transition-[background-color,clip-path] data-entering:duration-(--motion-draw-duration) data-entering:ease-[var(--motion-draw-fade-easing),var(--motion-draw-easing)] motion-reduce:ease-(--motion-layout-fade-easing) motion-reduce:group-data-mounted/chart:transition-[background-color] forced-colors:bg-[GrayText]'\n                    style={\n                      {\n                        // A variable, as the bars' clip is, so the two read alike.\n                        '--ribbon-clip': ribbonClipPath(\n                          ribbon.start,\n                          ribbon.end,\n                          layout,\n                          [\n                            tuck(ribbon.outer[0], leaving),\n                            tuck(ribbon.outer[1], leaving),\n                          ],\n                        ),\n                      } as CSSProperties\n                    }\n                  />\n                </div>\n              )\n            })}\n          </div>\n        )\n      })}\n    </div>\n  )\n}\n\n/** No ribbons, each as drawn: with the count of the data's arrival it came with. */\nconst NO_RIBBONS: readonly (Ribbon & { arrival: number })[] = []\n\nfunction ribbonKey(ribbon: Ribbon) {\n  return ribbon.key\n}\n\n/* The bridge. */\n\n/** What a bridge's bars and words read. */\ninterface BridgeValue {\n  /** Its one series. */\n  key: string\n  /** Whether a step, still in the data or just taken out, is a total. */\n  isTotal: (stop: ChartItem) => boolean\n  /** Each step's change, by its place in the data: null for a total or a missing change. */\n  changes: readonly (number | null)[]\n  /** The running total after each step, by its place. */\n  runs: readonly number[]\n  /** Where a step just taken out stood, by its key, so it folds into its start. */\n  left: (key: string) => Span | null\n}\n\nconst BridgeContext = createContext<BridgeValue | null>(null)\n\n/** The share of `draw` a bridge's bar waits after the one before starts: by then that one has nearly landed. */\nconst BRIDGE_STEP_WAIT = 0.4\n\n/** The most of `draw` a bridge's cascade spreads over, so a long one builds faster rather than slower. */\nconst BRIDGE_CASCADE_MOST = 1.6\n\n/** A bridge's colours, each a variable a buyer sets on the chart or above it. */\nconst BRIDGE_TONES = {\n  rise: 'var(--bar-chart-rise, var(--chart-1))',\n  fall: 'var(--bar-chart-fall, var(--destructive))',\n  total: 'var(--bar-chart-total, var(--chart-4))',\n} as const\n\n/** The colour of a bridge's step: a total's, or a change's as it rises or falls. */\nfunction bridgeTone(bridge: BridgeValue, stop: ChartItem, value: number | null) {\n  if (bridge.isTotal(stop)) return BRIDGE_TONES.total\n  return value !== null && value < 0 ? BRIDGE_TONES.fall : BRIDGE_TONES.rise\n}\n\n/**\n * What a bridge works out from its rows as it renders: each step's change,\n * the running total after it and whether it joins the next, and where each\n * step just taken out stood. Null for bars that stand on the axis.\n */\nfunction useBridge(\n  chart: CartesianChartValue,\n  isTotal: readonly boolean[] | null,\n  totals: readonly string[],\n): BridgeValue | null {\n  const key = chart.series[0] ?? ''\n  if (isTotal && chart.series.length > 1) {\n    throw new Error(\n      'A bridge draws one series: its changes from a start to an end. Give it one `Bar`, or use `layout=\"bars\"`.',\n    )\n  }\n  const values = chart.current.map((stop) => numberOf(chart.valueOf(key, stop)))\n  const steps = bridgeSpans(values, isTotal ?? [])\n  // Bars that stand on the axis keep nothing.\n  const kept = useLeft(\n    isTotal ? chart.current.map((stop) => stop.key) : [],\n    steps,\n    leavingKeys(chart),\n    (span) => span?.join(',') ?? '',\n  )\n  if (!isTotal) return null\n  return {\n    key,\n    isTotal: (stop) => totals.includes(String(stop.value)),\n    changes: values.map((value, at) => (isTotal[at] ? null : value)),\n    runs: runningTotals(steps),\n    // With no steps left, as while it loads, every step folds onto the axis, as bars do.\n    left: (key) => (chart.current.length > 0 ? (kept(key) ?? null) : null),\n  }\n}\n\n/** The keys of the stops just taken out, while they leave. */\nfunction leavingKeys(chart: CartesianChartValue) {\n  return chart.stops.filter((stop) => stop.leaving).map((stop) => stop.key)\n}\n\n/**\n * What each key last had, for the keys just taken out: kept from the render\n * before, while they leave, and let go once they have left. `signature`\n * writes a value, so a render that changes none keeps what it has.\n */\nfunction useLeft<T>(\n  keys: readonly string[],\n  values: readonly T[],\n  leaving: readonly string[],\n  signature: (value: T | undefined) => string,\n) {\n  const said = keys.map((key, at) => `${key}=${signature(values[at])}`).join('\\u0000')\n  const now = new Map(keys.map((key, at) => [key, values[at]]))\n  const [state, setState] = useState({\n    said,\n    now,\n    gone: new Map<string, T | undefined>(),\n  })\n  let gone = state.gone\n  if (state.said !== said) {\n    gone = new Map([...state.gone, ...state.now])\n    for (const key of keys) gone.delete(key)\n    setState({ said, now, gone })\n  } else if ([...gone.keys()].some((key) => !leaving.includes(key))) {\n    // The data changes a render before its keys are marked leaving, so only a render after it lets them go.\n    gone = new Map([...gone].filter(([key]) => leaving.includes(key)))\n    setState({ ...state, gone })\n  }\n  return (key: string) => gone.get(key)\n}\n\n/**\n * A bridge's words: each step's change in words, so its sign never rests on\n * colour, and the running total after it, or a total's value; the tooltip's\n * change and running total; and a data table of both.\n */\nfunction bridgeWords(chart: CartesianChartValue, bridge: BridgeValue): ChartWords {\n  const { messages, valueText } = chart\n  const signed = signedWriter(chart.locale, chart.format)\n  const run = (stop: ChartItem) => valueText(bridge.runs[stop.index] ?? 0)\n  const change = (stop: ChartItem) => bridge.changes[stop.index] ?? null\n  return {\n    describe: (stop) => {\n      const name = pickedName(chart.stopText(stop), chart.selected === stop.key, messages)\n      if (bridge.isTotal(stop)) return `${name}, ${messages.bridgeTotal(run(stop))}`\n      const value = change(stop)\n      const said =\n        value === null\n          ? messages.noValue\n          : messages.change(value, valueText(Math.abs(value)))\n      return `${name}, ${messages.bridgeStep(said, run(stop))}`\n    },\n    tooltip: (stop) => (\n      <BridgeTooltipContent\n        chart={chart}\n        name={chart.stopText(stop)}\n        tone={bridgeTone(bridge, stop, change(stop))}\n        rows={\n          bridge.isTotal(stop)\n            ? [[messages.total, run(stop)]]\n            : [\n                [\n                  messages.stepChange,\n                  change(stop) === null ? messages.noValue : signed(change(stop) ?? 0),\n                ],\n                [messages.runningTotal, run(stop)],\n              ]\n        }\n      />\n    ),\n    table: {\n      ...cartesianTable(chart, [messages.stepChange, messages.runningTotal], (stop) => {\n        const value = change(stop)\n        return [\n          bridge.isTotal(stop)\n            ? messages.total\n            : value === null\n              ? messages.noValue\n              : signed(value),\n          run(stop),\n        ]\n      }),\n      header: messages.step,\n    },\n  }\n}\n\n/** A bridge step's tooltip: its name keyed by its colour, then its change and the running total after it, or a total's value. */\nfunction BridgeTooltipContent({\n  chart,\n  name,\n  tone,\n  rows,\n}: {\n  chart: CartesianChartValue\n  name: string\n  /** The step's colour, which keys it to its bar. */\n  tone: string\n  rows: readonly (readonly [string, string])[]\n}) {\n  return (\n    // The tooltip sits outside the chart, so it carries the chart's id, as every chart's does.\n    <div data-chart={chart.id} className='grid min-w-36 gap-1'>\n      <div className='flex items-center gap-2'>\n        <span\n          aria-hidden\n          className={cn(swatchClassName, forcedSeriesColor(0))}\n          style={{ '--swatch': tone } as CSSProperties}\n        />\n        <span className='font-medium'>{name}</span>\n      </div>\n      {rows.map(([term, value]) => (\n        <div key={term} className='flex items-center gap-4'>\n          <span className={cn(tooltipQuietClassName, 'flex-1')}>{term}</span>\n          {/* A value with a unit reads in its own order whatever the page's direction. */}\n          <span dir='auto' className='font-medium tabular-nums'>\n            {value}\n          </span>\n        </div>\n      ))}\n    </div>\n  )\n}\n\n/**\n * Where the bar of `key` at `stop` stands: in its slot of the band\n * side by side, or across the band stacked, beside the chart's other stacks.\n * A hidden series, a missing value, a bar that hasn't risen yet and a\n * category that leaves all stand at zero.\n */\nfunction barPlace(\n  chart: CartesianChartValue,\n  bar: BarFrameValue,\n  stop: CartesianStop,\n  key: string,\n  bridge: BridgeValue | null,\n): BarPlace {\n  const { model } = bar\n  const band = bandOf(chart, bar, stop, key)\n  const { scale, baseline: zero } = model.valueAxisOf(key)\n  if (bridge) {\n    // A step folds into where it starts: the running total before it.\n    const span = stop.leaving ? bridge.left(stop.key) : model.spans[key]?.[stop.index]\n    const start = span\n      ? scale.place(span[0])\n      : stop.leaving\n        ? zero\n        : scale.place(bridge.runs[stop.index] ?? 0)\n    if (!span || stop.leaving || !chart.entered) return { band, from: start, to: start }\n    return { band, from: start, to: scale.place(span[1]) }\n  }\n  const span = stop.leaving ? null : model.spans[key]?.[stop.index]\n  if (!span || !chart.entered) return { band, from: zero, to: zero }\n  return { band, from: scale.place(span[0]), to: scale.place(span[1]) }\n}\n\n/** Whether the bar of `key` is the last of its stack on its side of zero, which takes the round end. */\nfunction isOutermost(\n  chart: CartesianChartValue,\n  bar: BarFrameValue,\n  stop: CartesianStop,\n  key: string,\n) {\n  if (!addsUp(chart.stack)) return true\n  const { spans, stackOf } = bar.model\n  const own = spans[key]?.[stop.index]\n  if (!own || rangeOf(chart.valueOf(key, stop))) return true\n  const positive = own[1] >= own[0]\n  const shown = chart.series.filter(\n    (k) => !chart.hidden.includes(k) && stackOf(k) === stackOf(key),\n  )\n  const after = shown.slice(shown.indexOf(key) + 1)\n  return !after.some((k) => {\n    const span = spans[k]?.[stop.index]\n    return (\n      span &&\n      !rangeOf(chart.valueOf(k, stop)) &&\n      span[1] !== span[0] &&\n      span[1] >= span[0] === positive\n    )\n  })\n}\n\n/** What a bar's label says it reads: its value, its range, or a change with its sign; nothing for none. */\nfunction readingText(\n  reading: BarReading | undefined,\n  write: (value: number) => string,\n  signed: (value: number) => string,\n) {\n  if (!reading) return ''\n  const { value } = reading\n  if (typeof value !== 'number') return `${write(value[0])} – ${write(value[1])}`\n  return reading.signed ? signed(value) : write(value)\n}\n\ntype BarProps = Omit<ComponentProps<'div'>, 'children' | 'color'> & {\n  /** The key of this series' values in the data, and of its entry in the config. */\n  dataKey: string\n  /**\n   * The series' own rows, on an x of times, in place of the chart's: each\n   * with the chart's `index` and the series' `dataKey`, in time order. Its\n   * bars stand at their own times and stack with nothing.\n   */\n  data?: readonly ChartDatum[]\n  /**\n   * A colour for one bar, such as one that stands out, from the row it is\n   * drawn from and its stop's place; the series' colour when it returns\n   * nothing.\n   */\n  color?: (datum: ChartDatum, index: number) => string | undefined\n  /** The colour of a bar below zero. */\n  negativeColor?: string\n  /** Writes each bar's value on it: `true` puts it past the bar's end. */\n  label?: boolean | BarLabelPosition\n  /** How the labels write values; the chart's `format` by default. */\n  labelFormat?: ChartFormat\n  /** Draws each bar's whole length behind it, for values out of a whole. */\n  track?: boolean\n  /** Fills the bars with the series' colour, or with it fading toward zero. */\n  fill?: 'solid' | 'gradient'\n}\n\n/**\n * One series' bars: a layer of the plot holding a bar for each category,\n * in the series' colour. While the chart enters, the bars rise on `draw`,\n * one after another with `entrance='cascade'`; after that every change\n * moves on `layout`. A missing value shows a short dashed mark at zero, so\n * it reads apart from a zero.\n */\nfunction Bar(props: BarProps) {\n  const {\n    dataKey,\n    data,\n    color,\n    negativeColor,\n    label = false,\n    labelFormat,\n    track = false,\n    fill = 'solid',\n    className,\n    style,\n    ...rest\n  } = props\n  useDeclared('Bar', Bar.declare(props), cartesianSignature)\n  const chart = useCartesian()\n  const { spotlit } = useChartActive()\n  const bar = useBarFrame()\n  const bridge = use(BridgeContext)\n  if (bridge && negativeColor !== undefined) {\n    throw new Error(\n      'A bridge colours its falls with `--bar-chart-fall`, not `negativeColor`: set the variable on the chart.',\n    )\n  }\n  if (chart.stack === 'overlap' && (label !== false || track)) {\n    throw new Error(\n      'Overlapped bars stand in one place, so their labels and tracks would cover each other: leave out `label` and `track`, or set them side by side with a `barGap` below zero.',\n    )\n  }\n  const position = labelPosition(label)\n  const { orientation } = chart\n  const write = formatterOf(chart.locale, labelFormat ?? chart.format)\n  if (chart.status === 'empty') return null\n  const slot = chart.series.indexOf(dataKey)\n  const zero = bar.model.valueAxisOf(dataKey).baseline\n  const pattern = patternImage(chart.patternOf(dataKey))\n  const gradient =\n    fill === 'gradient'\n      ? `linear-gradient(${orientation === 'vertical' ? 'to top' : chart.direction === 'rtl' ? 'to left' : 'to right'}, color-mix(in oklab, var(--mark-ink) 35%, transparent), var(--mark-ink))`\n      : undefined\n  const images = [pattern, gradient].filter(Boolean).join(', ')\n  const live = chart.frame.live\n  // A stop lit steps the others back, unless the pointer lights a series across every stop.\n  const dimmed = (stop: CartesianStop) =>\n    (bar.lights === 'stop' && spotlit !== null && spotlit !== stop.index) ||\n    (chart.emphasis !== null && chart.emphasis !== dataKey)\n  return (\n    <>\n      <div\n        data-slot='bar-chart-series'\n        data-series={dataKey}\n        data-own={data ? '' : undefined}\n        aria-hidden\n        className={cn(plotLayerClassName, markLayer.bar, className)}\n        style={style}\n        {...rest}\n      >\n        <ChartLiveLayer live={live} direction={chart.direction} reach='plot'>\n          <div\n            className={\n              live\n                ? 'absolute inset-y-0 start-0 w-[300%] [container-type:size]'\n                : 'contents'\n            }\n          >\n            {/* A live plot's rows that leave have scrolled out already, so only the rows still in it draw.\n              A bar stands only where its series has a row. */}\n            {rowStops(chart, live ? chart.current : chart.stops, dataKey).map((stop) => {\n              const place = liveBand(barPlace(chart, bar, stop, dataKey, bridge), live)\n              const row = chart.rowOf(dataKey, stop)\n              const raw = row?.[dataKey]\n              const value = numberOf(raw)\n              const range = rangeOf(raw)\n              const below = range ? range[1] < range[0] : value !== null && value < 0\n              const own =\n                (row && color?.(row, stop.index)) ??\n                (bridge\n                  ? bridgeTone(bridge, stop, value)\n                  : below && negativeColor\n                    ? negativeColor\n                    : undefined)\n              const clip = barClip(chart, place, isOutermost(chart, bar, stop, dataKey))\n              const at = Math.min(stop.index, PLACEHOLDER_COUNT - 1)\n              // A bar that arrives grows out of the placeholder in its place, or up from zero; a\n              // bridge's, up from where it starts.\n              const start = bridge ? place.from : zero\n              const from = bar.fromPlaceholder\n                ? placeholderClip(chart, at, placeholderValues(PLACEHOLDER_COUNT)[at]!)\n                : barClip(chart, { band: place.band, from: start, to: start }, true)\n              const missing =\n                // A row without the key has none of the series here, so nothing marks it.\n                row !== null &&\n                Object.hasOwn(row, dataKey) &&\n                !stop.leaving &&\n                chart.entered &&\n                !chart.hidden.includes(dataKey) &&\n                value === null &&\n                range === null &&\n                // A bridge's total with no value stands at the running total.\n                !bridge?.isTotal(stop)\n              const delay = cascadeDelay(bar, stop.index)\n              return (\n                <BarShape\n                  key={stop.key}\n                  clip={clip}\n                  from={from}\n                  dim={dimmed(stop)}\n                  entering={bar.phase === 'entering'}\n                  delay={delay}\n                  color={own ?? seriesColor(dataKey)}\n                  images={images}\n                  slot={slot}\n                  track={track ? trackClip(chart, place.band) : undefined}\n                  // A bridge's missing change sits at the running total, which carries on past it.\n                  missing={missing ? missingMark(chart, place.band, start) : undefined}\n                />\n              )\n            })}\n          </div>\n        </ChartLiveLayer>\n      </div>\n      {/* A live chart's bars scroll past too fast to read a label on each. */}\n      {position && chart.status === 'ready' && !live && (\n        // Above the reference lines, so a line across a value never runs through it.\n        <div aria-hidden className={cn(plotLayerClassName, 'z-20')}>\n          <BarLabels\n            dataKey={dataKey}\n            position={position}\n            write={write}\n            signed={signedWriter(chart.locale, labelFormat ?? chart.format)}\n            dimmed={dimmed}\n          />\n        </div>\n      )}\n    </>\n  )\n}\n\n/**\n * A bar's place in its layer: on a live chart, a box `LIVE_SPAN` plots wide\n * from the plot's reading start, so a bar past the plot's end, which the\n * clock will bring into view, isn't clipped away.\n */\nfunction liveBand(place: BarPlace, live: ChartLive | null): BarPlace {\n  if (!live) return place\n  const { start, size } = place.band\n  return {\n    ...place,\n    band: { start: start / LIVE_SPAN, size: size / LIVE_SPAN },\n  }\n}\n\n/** The stops among `stops` where `key` has a row, which its bars stand at. */\nfunction rowStops(\n  chart: Pick<CartesianChartValue, 'rowOf'>,\n  stops: readonly CartesianStop[],\n  key: string,\n) {\n  return stops.filter((stop) => chart.rowOf(key, stop) !== null)\n}\n\n/** Where a bar's label sits, or null for none: `true` puts it past the bar's end. */\nfunction labelPosition(label: BarProps['label']): BarLabelPosition | null {\n  return label === true ? 'outside' : label || null\n}\n\n// A bar is its series; labels past the bars' ends keep room for themselves past the value\n// axis's far end, worked out from what they will read.\nBar.declare = ({\n  dataKey,\n  data,\n  label = false,\n  labelFormat,\n}: BarProps): ChartPartDeclaration => ({\n  series: { key: dataKey, mark: 'bar' },\n  ...(data === undefined ? {} : { rows: data }),\n  ...(labelPosition(label) === 'outside'\n    ? {\n        room: (chart: ChartRoomState) => {\n          const format = labelFormat ?? chart.format\n          const write = formatterOf(chart.locale, format)\n          const signed = signedWriter(chart.locale, format)\n          const readings = barKind(chart.kinds).reads(\n            chart.rows.map((row) => row[dataKey]),\n          )\n          return outsideRoom(\n            chart,\n            readings.map((reading) => readingText(reading, write, signed)),\n          )\n        },\n      }\n    : {}),\n})\n\n/** How long the bars of the stop at `index` wait in a cascade's entrance; none otherwise. */\nfunction cascadeDelay(bar: BarFrameValue, index: number) {\n  return bar.entrance === 'cascade' && bar.phase === 'entering'\n    ? `calc(var(--motion-draw-duration) * ${bar.cascadeSpan} * ${bar.cascade[index] ?? 0})`\n    : undefined\n}\n\n/**\n * Each bar's value, written past its end, just inside it, or in its middle.\n * A label that doesn't fit its bar is skipped, and every label slides with\n * its bar.\n */\nfunction BarLabels({\n  dataKey,\n  position,\n  write,\n  signed,\n  dimmed,\n}: {\n  dataKey: string\n  position: BarLabelPosition\n  write: (value: number) => string\n  /** How a bridge's change is written, with its sign. */\n  signed: (value: number) => string\n  dimmed: (stop: CartesianStop) => boolean\n}) {\n  const chart = useCartesian()\n  const bar = useBarFrame()\n  const bridge = use(BridgeContext)\n  const readings = bar.kind.reads(\n    chart.current.map((stop) => chart.valueOf(dataKey, stop)),\n  )\n  const texts = readings.map((reading) => readingText(reading, write, signed))\n  // A label taken out keeps what it read as it fades, since its place in the data has gone.\n  const kept = useLeft(\n    chart.current.map((stop) => stop.key),\n    texts,\n    leavingKeys(chart),\n    (text) => text ?? '',\n  )\n  if (chart.hidden.includes(dataKey)) return null\n  return (\n    <>\n      {rowStops(chart, chart.stops, dataKey).map((stop) => {\n        const place = barPlace(chart, bar, stop, dataKey, bridge)\n        const span = bar.model.spans[dataKey]?.[stop.index]\n        const text = (stop.leaving ? kept(stop.key) : texts[stop.index]) ?? ''\n        const outermost = isOutermost(chart, bar, stop, dataKey)\n        // Until the chart has entered, its bars haven't risen, so their labels wait unseen.\n        const shown =\n          chart.entered &&\n          !stop.leaving &&\n          span !== null &&\n          span !== undefined &&\n          text !== '' &&\n          (position !== 'outside' || outermost) &&\n          labelFits(chart, place, text, position)\n        return (\n          <BarLabel\n            key={stop.key}\n            {...labelPlace(chart, place, position)}\n            shown={shown}\n            dim={dimmed(stop)}\n            entering={bar.phase === 'entering'}\n            delay={cascadeDelay(bar, stop.index)}\n          >\n            {text}\n          </BarLabel>\n        )\n      })}\n    </>\n  )\n}\n\n/**\n * The total of each category's stack, written past its end, for stacked\n * bars, whose length the tooltip alone would otherwise tell.\n */\ntype BarTotalsProps = Omit<ComponentProps<'div'>, 'children'> & {\n  format?: ChartFormat\n}\n\n/**\n * The series a stack's total adds: the shown bars read against the chart's\n * own value axis, never a line or a point beside them, or a bar on an axis\n * of its own.\n */\nfunction totalled(chart: Pick<ChartRootState, 'series' | 'hidden' | 'config'>) {\n  return chart.series.filter(\n    (key) =>\n      !chart.hidden.includes(key) &&\n      (chart.config[key]?.mark ?? 'bar') === 'bar' &&\n      (chart.config[key]?.axis ?? VALUE_AXIS) === VALUE_AXIS,\n  )\n}\n\n/** The total of a stop's shown series, each read with `valueOf`. */\nfunction totalOf(valueOf: (key: string) => unknown, shown: readonly string[]) {\n  return shown.reduce((sum, key) => sum + (numberOf(valueOf(key)) ?? 0), 0)\n}\n\nfunction BarTotals(props: BarTotalsProps) {\n  const { format, className, ...rest } = props\n  useDeclared('BarTotals', BarTotals.declare(props), cartesianSignature)\n  const chart = useCartesian()\n  if (chart.stack === 'overlap') {\n    throw new Error(\n      'Overlapped bars stand in front of one another and add up to nothing: leave out `BarTotals`, or stack them.',\n    )\n  }\n  const { spotlit } = useChartActive()\n  const bar = useBarFrame()\n  const write = formatterOf(chart.locale, format ?? chart.format)\n  // A series with rows of its own stacks with nothing, so it adds to no total.\n  const shown = totalled(chart).filter(bar.model.totals)\n  const scale = bar.model.y.value\n  const zero = bar.model.baselines.value\n  if (chart.status !== 'ready') return null\n  return (\n    <div\n      data-slot='bar-chart-totals'\n      aria-hidden\n      className={cn(plotLayerClassName, 'z-20', className)}\n      {...rest}\n    >\n      {/* A stop where only a series' own rows are has no stack. */}\n      {chart.stops.flatMap((stop) => {\n        if (stop.datum === null) return []\n        const total = totalOf((key) => chart.valueOf(key, stop), shown)\n        const place = {\n          band: stop.band,\n          from: zero,\n          to:\n            stop.leaving || !chart.entered\n              ? zero\n              : scale.place(farEnd(bar.model.spans, shown, stop.index)),\n        }\n        return [\n          <BarLabel\n            key={stop.key}\n            {...labelPlace(chart, place, 'outside')}\n            shown={\n              chart.entered &&\n              !stop.leaving &&\n              labelFits(chart, place, write(total), 'outside')\n            }\n            dim={bar.lights === 'stop' && spotlit !== null && spotlit !== stop.index}\n          >\n            {chart.stack === 'expand' ? '' : write(total)}\n          </BarLabel>,\n        ]\n      })}\n    </div>\n  )\n}\n\n// The totals keep room for themselves past the value axis's far end.\nBarTotals.declare = ({ format }: BarTotalsProps): ChartPartDeclaration => ({\n  room: (chart) => {\n    const write = formatterOf(chart.locale, format ?? chart.format)\n    const shown = totalled(chart)\n    return outsideRoom(\n      chart,\n      chart.stack === 'expand'\n        ? []\n        : chart.rows.map((row) => write(totalOf((key) => row[key], shown))),\n    )\n  },\n})\n\n/**\n * Whether each row of a bridge is a total: its category is in `totals`.\n * Throws on what a bridge can't be: on times, stacked, or with a total no\n * row has.\n */\nfunction bridgeTotals(\n  props: Pick<BarChartProps, 'data' | 'index' | 'indexType'>,\n  stack: ChartStack,\n  totals: readonly string[],\n): boolean[] {\n  if (props.indexType === 'time') {\n    throw new Error(\n      'A bridge steps through named changes, not times: leave out `indexType=\"time\"`.',\n    )\n  }\n  if (stack !== 'none') {\n    throw new Error(\n      'A bridge doesn’t stack: its one series runs from each step to the next.',\n    )\n  }\n  const names = props.data.map((row) => String(row[props.index]))\n  const unknown =\n    props.data.length > 0 ? totals.find((name) => !names.includes(name)) : undefined\n  if (unknown !== undefined) {\n    throw new Error(\n      `\\`totals\\` names \"${unknown}\", which no row's \\`${props.index}\\` has. Name a total by its category.`,\n    )\n  }\n  return names.map((name) => totals.includes(name))\n}\n\nexport {\n  Bar,\n  BarChart,\n  type BarChartProps,\n  type BarLabelPosition,\n  type BarProps,\n  BarTotals,\n  bridgeTotals,\n  ribbonsAllowed,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/bar-chart.tsx"
    }
  ],
  "type": "registry:component"
}