{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-bars",
  "title": "Chart bars",
  "description": "What the charts drawn as bars share: a bar as the clip of a layer as large as the plot, its shape that dims, rises and glides, the label on its end, the mark of a missing value and the placeholder’s bars. The Bar chart and the Funnel chart draw with it.",
  "registryDependencies": [
    "https://kinoui.com/r/chart-core.json",
    "https://kinoui.com/r/chart-bar-marks.json",
    "https://kinoui.com/r/chart-frame.json",
    "https://kinoui.com/r/chart-root.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/placeholder.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/chart-bars.tsx",
      "content": "'use client'\n\nimport type { BarMarkKind } from '@/registry/lib/chart-bar-marks'\nimport type { EntrancePhase } from '@/registry/lib/chart-base'\nimport type { CartesianModel } from '@/registry/lib/chart-frame'\nimport {\n  type ChartOrientation,\n  numberOf,\n  physicalStart,\n  plotPoint,\n  rangeOf,\n  type ReadingDirection,\n  type Span,\n} from '@/registry/lib/chart-math'\nimport {\n  type ChartRootState,\n  forcedSeriesColor,\n  plotLayerClassName,\n  stepBackInkClassName,\n} from '@/registry/lib/chart-root'\nimport { type Band, bandAt } from '@/registry/lib/chart-scale'\nimport {\n  placeholderBreatheClassName,\n  placeholderFillClassName,\n} from '@/registry/lib/placeholder'\nimport { createContext, type CSSProperties, memo, type ReactNode, use } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * What the charts drawn as bars share: a bar as the clip of a layer as large\n * as the plot, its shape that dims, rises and glides, the label on its end,\n * the mark of a missing value and the placeholder's bars. The Bar chart and\n * the Funnel chart draw with it, so every bar looks and moves the same.\n */\n\nconst PLACEHOLDER_COUNT = 7\n\n/** What a chart's bars stand in, which every `Bar` reads: the Bar chart's and the Composed chart's. */\ninterface BarFrameValue {\n  /** The frame the bars stand in: each series' spans, a hidden one where it would sit, so it shrinks into place and grows back out of it, and the axis it is read against. */\n  model: CartesianModel\n  /** Its bars' kind of mark, which says what each bar's label reads. */\n  kind: BarMarkKind\n  phase: EntrancePhase\n  /** The chart was loading, so its bars grow out of the placeholder. */\n  fromPlaceholder: boolean\n  entrance: 'rise' | 'cascade' | 'none'\n  /** How far through the cascade each category's bars start, by its place in the data. */\n  cascade: readonly number[]\n  /** The share of `draw` a cascade's bars start over, as CSS: its chart's variable, with its default. */\n  cascadeSpan: string\n  barGap: number\n  /**\n   * What the pointer and the keys light: a stop's bars, the rest stepping\n   * back, or a series' bars across every stop, as a Bar chart's ribbons do.\n   */\n  lights: 'stop' | 'series'\n}\n\nconst BarFrameContext = createContext<BarFrameValue | null>(null)\n\nfunction useBarFrame() {\n  const bar = use(BarFrameContext)\n  if (!bar) throw new Error('`Bar` goes inside a `BarChart` or a `ComposedChart`.')\n  return bar\n}\n\n/** Which way a chart's bars lie and its text reads, which places and rounds them. */\ninterface BarLayout {\n  orientation: ChartOrientation\n  direction: ReadingDirection\n}\n\n/** What a chart's labels are fitted to: its bars' layout, the plot's size and its text, and how many stops share it. */\ntype BarLabelLayout = BarLayout &\n  Pick<ChartRootState, 'plotSize' | 'textWidth'> & {\n    current: readonly unknown[]\n  }\n\n/** Where a bar stands: the band it takes and the span of the value axis it covers, as fractions. */\ninterface BarPlace {\n  band: Band\n  from: number\n  to: number\n}\n\n/** The bar's shape as a clip, rounded at the end its value reaches. */\nfunction barClip(chart: BarLayout, place: BarPlace, outermost: boolean) {\n  const insets = barInsets(\n    place.band,\n    place.from,\n    place.to,\n    chart.orientation,\n    chart.direction,\n  )\n  const positive = place.to >= place.from\n  const corners = outermost\n    ? roundCorners(chart.orientation, chart.direction, positive)\n    : ([false, false, false, false] as const)\n  const far =\n    place.to === place.from\n      ? undefined\n      : farSide(chart.orientation, chart.direction, positive)\n  return barClipPath(insets, corners, chart.orientation, far)\n}\n\n/**\n * The placeholder while the data loads: one bar for each of a few\n * categories, at uneven heights, breathing slowly. It fades in while the\n * bars there were shrink away, and the real bars grow out of it when the\n * data arrives.\n */\nfunction BarPlaceholder({\n  chart,\n  values = placeholderValues(PLACEHOLDER_COUNT),\n}: {\n  chart: BarLayout\n  /** The bars' lengths, as fractions of the plot. */\n  values?: readonly number[]\n}) {\n  return (\n    <div\n      data-slot='bar-chart-placeholder'\n      aria-hidden\n      className={cn(\n        plotLayerClassName,\n        'z-10 transition-opacity duration-(--motion-enter-duration) ease-(--motion-enter-easing) group-data-mounted/chart:starting:opacity-0',\n      )}\n    >\n      <div className={cn('absolute inset-0', placeholderBreatheClassName)}>\n        {values.map((value, at) => (\n          <div\n            // oxlint-disable-next-line react/no-array-index-key -- a fixed row\n            key={at}\n            className={cn('absolute inset-0', placeholderFillClassName)}\n            style={{\n              clipPath: placeholderClip(chart, at, value, values.length),\n            }}\n          />\n        ))}\n      </div>\n    </div>\n  )\n}\n\n/** The placeholder's bar at `at` of `count`, `value` long, as a clip. */\nfunction placeholderClip(\n  chart: BarLayout,\n  at: number,\n  value: number,\n  count = PLACEHOLDER_COUNT,\n) {\n  const band = bandAt(at, count)\n  return barClipPath(\n    barInsets(band, 0, value, chart.orientation, chart.direction),\n    roundCorners(chart.orientation, chart.direction, true),\n    chart.orientation,\n  )\n}\n\n/** Where a value label sits on its bar: past its end, just inside it, or in its middle. */\ntype BarLabelPosition = 'outside' | 'inside' | 'center'\n\n/** The room a label past the bars' ends takes along the value axis, in px: a line of text upright; lying, its width and the gap before it. */\nconst OUTSIDE_ROOM = { vertical: 18, gap: 10 } as const\n\n/** The room past the bars' ends that labels reading `texts` take, in px. */\nfunction outsideRoom(\n  chart: Pick<BarLabelLayout, 'orientation' | 'textWidth'>,\n  texts: readonly string[],\n) {\n  if (chart.orientation === 'vertical') return OUTSIDE_ROOM.vertical\n  return Math.ceil(Math.max(0, ...texts.map(chart.textWidth)) + OUTSIDE_ROOM.gap)\n}\n\n/**\n * One bar: its track, the bar, and the mark of a missing value. Memoised,\n * so a pointer moving between categories redraws only the bars it lights\n * or dims.\n */\nconst BarShape = memo(function BarShape({\n  clip,\n  from,\n  dim,\n  entering,\n  delay,\n  color,\n  images,\n  slot,\n  forced = forcedSeriesColor(slot),\n  track,\n  missing,\n}: {\n  clip: string\n  from: string\n  dim: boolean\n  entering: boolean\n  delay: string | undefined\n  color: string\n  images: string\n  slot: number\n  /** Its colour under forced colours, the series' own by default. */\n  forced?: string\n  track: string | undefined\n  missing: CSSProperties | undefined\n}) {\n  return (\n    <>\n      {track && (\n        <div\n          className='bg-foreground/6 dark:bg-foreground/10 absolute inset-0 duration-(--motion-layout-duration) ease-(--motion-layout-easing) [clip-path:var(--bar-clip)] transition-none group-data-mounted/chart:transition-[clip-path] motion-reduce:group-data-mounted/chart:transition-none forced-colors:bg-[GrayText]!'\n          style={{ '--bar-clip': track } as CSSProperties}\n        />\n      )}\n      <div\n        data-entering={entering ? '' : undefined}\n        data-dim={dim ? '' : undefined}\n        className={cn(\n          'absolute inset-0 bg-(--mark-ink) transition-none group-data-mounted/chart:transition-[background-color,clip-path] duration-(--motion-layout-duration) ease-[var(--motion-layout-fade-easing),var(--motion-layout-easing)] [clip-path:var(--bar-clip)] group-data-mounted/chart:starting:[clip-path:var(--bar-from)] data-entering:duration-(--motion-draw-duration) data-entering:ease-[var(--motion-draw-fade-easing),var(--motion-draw-easing)] motion-reduce:group-data-mounted/chart:transition-[background-color] motion-reduce:ease-(--motion-layout-fade-easing)',\n          stepBackInkClassName,\n          forced,\n        )}\n        style={\n          {\n            '--mark-color': color,\n            '--bar-from': from,\n            // A variable, not `clipPath`, so the class's starting shape isn't overruled by an inline style.\n            '--bar-clip': clip,\n            backgroundImage: images || undefined,\n            transitionDelay: delay,\n          } as CSSProperties\n        }\n      />\n      {missing && (\n        <div className='absolute' style={missing}>\n          <div className='border-muted-foreground/60 mx-auto max-w-(--bar-chart-max-thickness,4rem) border-t-2 border-dashed forced-colors:border-[GrayText]' />\n        </div>\n      )}\n    </>\n  )\n})\n\n/** A bar's whole length, from one end of the value axis to the other, in its band. */\nfunction trackClip(chart: BarLayout, band: Band) {\n  return barClipPath(\n    barInsets(band, 0, 1, chart.orientation, chart.direction),\n    [true, true, true, true],\n    chart.orientation,\n  )\n}\n\n/** Where the mark of a missing value sits: across its band, on `zero`, the fraction of the value axis bars grow from. */\nfunction missingMark(chart: BarLayout, band: Band, zero: number): CSSProperties {\n  const start = physicalStart(\n    band,\n    chart.orientation === 'vertical' ? 'inline' : 'block',\n    chart.direction,\n  )\n  return chart.orientation === 'vertical'\n    ? {\n        left: `${start * 100}%`,\n        width: `${band.size * 100}%`,\n        bottom: `calc(${zero * 100}% - 1px)`,\n      }\n    : {\n        top: `calc(${(band.start + band.size / 2) * 100}% - 1px)`,\n        height: 2,\n        width: 0,\n        [chart.direction === 'rtl' ? 'right' : 'left']: `${zero * 100}%`,\n      }\n}\n\n/** Where a label on the bar at `place` goes: the point it sits on, and which way is out from the bar's end. */\nfunction labelPlace(chart: BarLayout, place: BarPlace, position: BarLabelPosition) {\n  const { orientation, direction } = chart\n  const positive = place.to >= place.from\n  const along = position === 'center' ? (place.from + place.to) / 2 : place.to\n  const point = plotPoint(place.band, along, orientation, direction)\n  const out: 'up' | 'down' | 'left' | 'right' =\n    orientation === 'vertical'\n      ? positive\n        ? 'up'\n        : 'down'\n      : positive === (direction === 'ltr')\n        ? 'right'\n        : 'left'\n  return { x: point.x, y: point.y, out, position }\n}\n\n/**\n * A label on a bar, sliding with it: past its end, inside it, or in its\n * middle. Memoised, as the bars are.\n */\nconst BarLabel = memo(function BarLabel({\n  x,\n  y,\n  out,\n  position,\n  shown,\n  dim,\n  entering = false,\n  delay,\n  children,\n}: {\n  x: number\n  y: number\n  out: 'up' | 'down' | 'left' | 'right'\n  position: BarLabelPosition\n  shown: boolean\n  dim: boolean\n  /** Its bar is rising for the entrance, so it rises with it, on `draw`, after the same `delay`. */\n  entering?: boolean\n  delay?: string\n  children: ReactNode\n}) {\n  const outside = position === 'outside'\n  const placeClass =\n    // A physical `left-0` beside the centring translate, so it centres on the anchor in\n    // either reading direction; right to left would start it from the anchor's right.\n    position === 'center'\n      ? 'left-0 top-0 -translate-x-1/2 -translate-y-1/2'\n      : out === 'up'\n        ? cn('left-0 -translate-x-1/2', outside ? 'bottom-1' : 'top-1')\n        : out === 'down'\n          ? cn('left-0 -translate-x-1/2', outside ? 'top-1' : 'bottom-1')\n          : out === 'right'\n            ? cn('-translate-y-1/2', outside ? 'left-1.5' : 'right-1.5')\n            : cn('-translate-y-1/2', outside ? 'right-1.5' : 'left-1.5')\n  return (\n    <span\n      data-dim={dim ? '' : undefined}\n      data-entering={entering ? '' : undefined}\n      className='absolute top-0 left-0 size-0 [translate:var(--label-at)] duration-(--motion-layout-duration) ease-[var(--motion-layout-fade-easing),var(--motion-layout-fade-easing),var(--motion-layout-easing)] transition-none group-data-mounted/chart:transition-[color,opacity,translate] data-dim:text-muted-foreground data-entering:duration-(--motion-draw-duration) data-entering:ease-[var(--motion-draw-fade-easing),var(--motion-draw-fade-easing),var(--motion-draw-easing)] motion-reduce:group-data-mounted/chart:transition-opacity motion-reduce:ease-(--motion-layout-fade-easing)'\n      style={\n        {\n          '--label-at': `${x * 100}cqw ${y * 100}cqh`,\n          transitionDelay: delay,\n        } as CSSProperties\n      }\n    >\n      {/* A value with a sign or a unit reads in its own order whatever the page's direction. */}\n      <span\n        dir='auto'\n        className={cn(\n          'absolute w-max font-medium whitespace-nowrap tabular-nums transition-none duration-(--motion-enter-duration) ease-(--motion-enter-fade-easing) group-data-mounted/chart:transition-[opacity,color]',\n          // Past the bar, it hides the grid under it in the colour of the surface the chart is on.\n          outside\n            ? 'bg-(--chart-surface,var(--card))/85'\n            : 'bg-background/85 text-foreground rounded-(--control-radius-xs) px-1',\n          !shown && 'opacity-0',\n          placeClass,\n        )}\n        // In a cascade it fades in as its bar starts to rise.\n        style={{ transitionDelay: delay }}\n      >\n        {children}\n      </span>\n    </span>\n  )\n})\n\n/** Whether `text` fits where its label goes on the bar at `place`, at the chart's size. */\nfunction labelFits(\n  chart: BarLabelLayout,\n  place: BarPlace,\n  text: string,\n  position: BarLabelPosition,\n) {\n  const { width, height } = chart.plotSize\n  const vertical = chart.orientation === 'vertical'\n  const thickness = place.band.size * (vertical ? width : height)\n  const length = Math.abs(place.to - place.from) * (vertical ? height : width)\n  const textWidth = chart.textWidth(text)\n  // A line of the chart's 12px text.\n  const textHeight = 16\n  if (position === 'outside') {\n    // Past the end, a label may be wider than its bar, but not than its category's step.\n    const step = (vertical ? width : height) / Math.max(1, chart.current.length)\n    return vertical ? step >= textWidth + 4 : thickness >= textHeight - 2\n  }\n  // Inside, a label and its backdrop fit the bar's thickness and its length, past the inset\n  // from the end; centred, its length.\n  const inset = position === 'inside' ? (vertical ? 4 : 6) : 0\n  return vertical\n    ? thickness >= textWidth + 4 && length >= textHeight + inset + 2\n    : thickness >= textHeight - 2 && length >= textWidth + 8 + inset + 2\n}\n\n/** The edges of a bar, as fractions of the plot from each side. */\ninterface Insets {\n  top: number\n  right: number\n  bottom: number\n  left: number\n}\n\n/**\n * Where a bar is drawn in the plot: across `band` of the category axis, and\n * along the value axis from `from` to `to`, both fractions of the value axis.\n * Upright bars run left to right in reading order and up from the bottom;\n * lying bars run down the page and away from the reading start.\n */\nfunction barInsets(\n  band: Band,\n  from: number,\n  to: number,\n  orientation: ChartOrientation,\n  direction: ReadingDirection,\n): Insets {\n  const low = Math.min(from, to)\n  const high = Math.max(from, to)\n  if (orientation === 'vertical') {\n    const left = physicalStart(band, 'inline', direction)\n    return { top: 1 - high, right: 1 - left - band.size, bottom: low, left }\n  }\n  return {\n    top: band.start,\n    right: direction === 'rtl' ? low : 1 - high,\n    bottom: 1 - band.start - band.size,\n    left: direction === 'rtl' ? 1 - high : low,\n  }\n}\n\n/**\n * Which corners of a bar are round, as top left, top right, bottom right and\n * bottom left: the two at the end its value reaches, away from zero.\n */\nfunction roundCorners(\n  orientation: ChartOrientation,\n  direction: ReadingDirection,\n  positive: boolean,\n): readonly [boolean, boolean, boolean, boolean] {\n  if (orientation === 'vertical') {\n    return positive ? [true, true, false, false] : [false, false, true, true]\n  }\n  const right = positive === (direction === 'ltr') ? true : false\n  return right ? [false, true, true, false] : [true, false, false, true]\n}\n\n/** The side of the plot a bar's far end faces: the end its value reaches, away from zero. */\nfunction farSide(\n  orientation: ChartOrientation,\n  direction: ReadingDirection,\n  positive: boolean,\n): keyof Insets {\n  if (orientation === 'vertical') return positive ? 'top' : 'bottom'\n  return positive === (direction === 'ltr') ? 'right' : 'left'\n}\n\n/**\n * The heights a loading chart's bars stand at, as fractions of the plot: a\n * fixed, uneven row, so it reads as a chart and never flickers between renders.\n */\nfunction placeholderValues(count: number): number[] {\n  const pattern = [0.42, 0.68, 0.55, 0.82, 0.61, 0.74, 0.48, 0.9, 0.58, 0.7, 0.38, 0.64]\n  return Array.from({ length: count }, (_, index) => pattern[index % pattern.length]!)\n}\n\n/**\n * A bar as the `clip-path` of a layer as large as the plot, which must be a\n * size container: its edges from `insets`, its thickness capped at\n * `--bar-chart-max-thickness` and centred in its band, at least\n * `--bar-chart-min-length` long toward its `far` side, so a tiny value\n * still shows, and the `corners` from `roundCorners` rounded by\n * `--bar-chart-radius`, never past `--mark-radius-share` of the bar's thickness. Moving from one\n * bar to the next is then a transition of one property, which turns back\n * from wherever it is.\n */\nfunction barClipPath(\n  insets: Insets,\n  corners: readonly [boolean, boolean, boolean, boolean],\n  orientation: ChartOrientation,\n  far?: keyof Insets,\n): string {\n  const across = orientation === 'vertical' ? 'cqw' : 'cqh'\n  const along = orientation === 'vertical' ? 'cqh' : 'cqw'\n  const [start, end] =\n    orientation === 'vertical' ? [insets.left, insets.right] : [insets.top, insets.bottom]\n  const size = Math.max(0, 1 - start - end)\n  const centre = start + size / 2\n  const half = halfThickness(size, across)\n  const near = `calc(${round(centre * 100)}${across} - ${half})`\n  const farAcross = `calc(${round((1 - centre) * 100)}${across} - ${half})`\n  const opposite = {\n    top: 'bottom',\n    bottom: 'top',\n    left: 'right',\n    right: 'left',\n  } as const\n  const edge = (side: keyof Insets) => {\n    const at = `${round(insets[side] * 100)}${along}`\n    if (side !== far) return at\n    // Pulled in no further than leaves the bar its least length from its other end.\n    return `min(${at}, 100${along} - ${round(insets[opposite[side]] * 100)}${along} - var(--bar-chart-min-length, 0px))`\n  }\n  const edges =\n    orientation === 'vertical'\n      ? [edge('top'), farAcross, edge('bottom'), near]\n      : [near, edge('right'), farAcross, edge('left')]\n  const radius = barRadius(half)\n  // Never all square: Chromium can't run a clip-path transition off the main thread between\n  // an inset with no `round` and one with, and a corner of 0px drops the `round`.\n  const radii = corners.map((rounded) => (rounded ? radius : '0.01px'))\n  return `inset(${edges.join(' ')} round ${radii.join(' ')})`\n}\n\n/**\n * Half a bar's thickness across `size` of the plot, in `unit` (`%` in a\n * shape that resolves against the plot), as CSS: capped at\n * `--bar-chart-max-thickness`.\n */\nfunction halfThickness(size: number, unit: 'cqw' | 'cqh' | '%') {\n  return `min(${round(size * 50)}${unit}, var(--bar-chart-max-thickness, 4rem) / 2)`\n}\n\n/**\n * A bar's rounded corner, as CSS: `--bar-chart-radius`, never past `--mark-radius-share` of its\n * thickness, twice `half`, so a thin bar keeps a thick one's shape rather than turning into a pill.\n */\nfunction barRadius(half: string) {\n  return `min(var(--bar-chart-radius, var(--control-radius-xs)), ${half} * 2 * var(--mark-radius-share))`\n}\n\n/** A fraction written to four decimals, enough for a plot thousands of px long. */\nfunction round(value: number): number {\n  return Math.round(value * 10_000) / 10_000\n}\n\n/*\n * Ribbons: each series of a stack joined from its bar in one column to its\n * bar in the next, so a viewer follows its share across them. A ribbon is a\n * clip of the plot, as a bar is, drawn from the same places, each of its two\n * edges a cubic that leaves one bar and meets the next flat.\n */\n\n/** A ribbon of `series` from its bar in the column at `from` to the one at `to`, by their places in the data. */\ninterface RibbonPair {\n  series: string\n  from: number\n  to: number\n}\n\n/**\n * The ribbons of a stack of `count` columns: one for each series between\n * each two neighbouring columns where it has a value at both. None crosses\n * a missing value or a change of sign, since its bars there stand on\n * opposite sides of zero; a zero joins either side, and its ribbon tapers to\n * a point there.\n */\nfunction ribbonsOf(\n  series: readonly string[],\n  count: number,\n  valueOf: (key: string, index: number) => unknown,\n): RibbonPair[] {\n  return series.flatMap((key) =>\n    Array.from({ length: Math.max(0, count - 1) }, (_, at) => at).flatMap((at) => {\n      const from = valueSign(valueOf(key, at))\n      const to = valueSign(valueOf(key, at + 1))\n      return from === null || to === null || from * to < 0\n        ? []\n        : [{ series: key, from: at, to: at + 1 }]\n    }),\n  )\n}\n\n/** Which side of zero a value or a `[from, to]` range runs to: 1, -1, or 0 for none; null for no value. */\nfunction valueSign(raw: unknown): number | null {\n  const value = numberOf(raw)\n  if (value !== null) return Math.sign(value)\n  const range = rangeOf(raw)\n  return range ? Math.sign(range[1] - range[0]) : null\n}\n\n/** How a chart's ribbons are laid out: its bars', with the bars' greatest thickness as a share of the plot across the categories. */\ninterface RibbonLayout extends BarLayout {\n  cap: number\n}\n\n/**\n * Where a ribbon meets a bar: the bar's edge that faces it, as a fraction of\n * the plot from its physical left (upright) or top (lying), and the bar's\n * span along the value axis, as fractions of it, which it covers whole.\n */\ninterface RibbonEnd {\n  edge: number\n  from: number\n  to: number\n}\n\n/** The middle of a bar across the categories, and half its thickness, as fractions of the plot: capped as `barClipPath` caps it. */\nfunction barAcross(place: BarPlace, layout: RibbonLayout) {\n  const { band } = place\n  const axis = layout.orientation === 'vertical' ? 'inline' : 'block'\n  return {\n    centre: physicalStart(band, axis, layout.direction) + band.size / 2,\n    half: Math.min(band.size, layout.cap) / 2,\n  }\n}\n\n/** The two ends of a ribbon from the bar at `start` to the bar at `end`: the edges that face each other, whichever way the columns run. */\nfunction ribbonEnds(\n  start: BarPlace,\n  end: BarPlace,\n  layout: RibbonLayout,\n): readonly [RibbonEnd, RibbonEnd] {\n  const a = barAcross(start, layout)\n  const b = barAcross(end, layout)\n  const forward = b.centre >= a.centre ? 1 : -1\n  return [\n    { edge: a.centre + forward * a.half, from: start.from, to: start.to },\n    { edge: b.centre - forward * b.half, from: end.from, to: end.to },\n  ]\n}\n\n/**\n * How a ribbon meets the bar at one end: running under it `share` of the way\n * from its edge to its middle, and, at the outermost bar of a stack, at least\n * as far as the bar's rounded corner reaches in, so the ribbon fills the\n * corner and runs on behind it.\n */\ninterface RibbonTuck {\n  share: number\n  corner: boolean\n}\n\n/**\n * How far a ribbon runs under its bars: halfway to their middles. The bars\n * cover it there, so it meets them with no seam whatever their thickness.\n */\nconst RIBBON_TUCK = 0.5\n\n/** A ribbon that stops at its bars' edges. */\nconst NO_TUCK: RibbonTuck = { share: 0, corner: false }\n\n/**\n * A ribbon as the `clip-path` of a layer as large as the plot: a `shape()`\n * from the end of its first bar's span to the end of the next's and back\n * along their starts, each edge a cubic whose handles sit halfway across, so\n * it leaves each bar flat. Its places across are the bars' own, in the same\n * CSS as `barClipPath`, so it meets each bar's edge at any size, and moving\n * it is one transition beside theirs, which lands with them and turns back\n * with them. Its edge along the ends of the spans stands\n * `--bar-chart-ribbon-gap` back, apart from the ribbon stacked past it.\n */\nfunction ribbonClipPath(\n  start: BarPlace,\n  end: BarPlace,\n  layout: BarLayout,\n  [startTuck, endTuck]: readonly [RibbonTuck, RibbonTuck],\n): string {\n  const { orientation, direction } = layout\n  const across = (place: BarPlace) => {\n    const { band } = place\n    const axis = orientation === 'vertical' ? 'inline' : 'block'\n    return {\n      centre: physicalStart(band, axis, direction) + band.size / 2,\n      half: halfThickness(band.size, '%'),\n    }\n  }\n  const a = across(start)\n  const b = across(end)\n  const forward = b.centre >= a.centre ? 1 : -1\n  // A place across `sign` of the way out from a bar's middle, less how far it runs under the bar.\n  const out = (\n    { centre, half }: { centre: number; half: string },\n    sign: number,\n    tuck?: RibbonTuck,\n  ) => {\n    const reach = tuck\n      ? // Never past the bar's middle.\n        `(${half} - min(${half}, max(${half} * ${tuck.share}, ${barRadius(half)} * ${tuck.corner ? 1 : 0})))`\n      : half\n    return `calc(${round(centre * 100)}% ${sign < 0 ? '-' : '+'} ${reach})`\n  }\n  const startEdge = out(a, forward)\n  const endEdge = out(b, -forward)\n  const startUnder = out(a, forward, startTuck)\n  const endUnder = out(b, -forward, endTuck)\n  const middle = `calc((${startEdge} + ${endEdge}) / 2)`\n  // A fraction of the value axis as a place along the plot, from its top (upright) or its left (lying).\n  const place = (along: number) =>\n    round((orientation === 'horizontal' && direction === 'ltr' ? along : 1 - along) * 100)\n  // The end of a span, the gap back toward its start, never past it.\n  const far = ({ from, to }: BarPlace) => {\n    const near = place(from)\n    const at = place(to)\n    const gap = 'var(--bar-chart-ribbon-gap, 1px)'\n    return at <= near\n      ? `min(${near}%, calc(${at}% + ${gap}))`\n      : `max(${near}%, calc(${at}% - ${gap}))`\n  }\n  const point = (acrossAt: string, along: string) =>\n    orientation === 'vertical' ? `${acrossAt} ${along}` : `${along} ${acrossAt}`\n  const startFar = far(start)\n  const endFar = far(end)\n  const startNear = `${place(start.from)}%`\n  const endNear = `${place(end.from)}%`\n  return `shape(${[\n    `from ${point(startUnder, startFar)}`,\n    `line to ${point(startEdge, startFar)}`,\n    `curve to ${point(endEdge, endFar)} with ${point(middle, startFar)} / ${point(middle, endFar)}`,\n    `line to ${point(endUnder, endFar)}`,\n    `line to ${point(endUnder, endNear)}`,\n    `line to ${point(endEdge, endNear)}`,\n    `curve to ${point(startEdge, startNear)} with ${point(middle, endNear)} / ${point(middle, startNear)}`,\n    `line to ${point(startUnder, startNear)}`,\n    'close',\n  ].join(', ')})`\n}\n\n/**\n * The span of the value axis a ribbon covers at `across`, as fractions, or\n * null where it doesn't reach: each edge read off its cubic, whose share of\n * the way across is `1.5t - 1.5t² + t³` and of the way along `3t² - 2t³`.\n */\nfunction ribbonSpanAt(\n  [start, end]: readonly [RibbonEnd, RibbonEnd],\n  across: number,\n): Span | null {\n  const width = end.edge - start.edge\n  if (width === 0) return null\n  const share = (across - start.edge) / width\n  if (share < 0 || share > 1) return null\n  // The curve's share across only grows, so halving finds its `t`.\n  let low = 0\n  let high = 1\n  for (let step = 0; step < 32; step += 1) {\n    const t = (low + high) / 2\n    if (1.5 * t - 1.5 * t * t + t * t * t < share) low = t\n    else high = t\n  }\n  const t = (low + high) / 2\n  const eased = 3 * t * t - 2 * t * t * t\n  return [\n    start.from + (end.from - start.from) * eased,\n    start.to + (end.to - start.to) * eased,\n  ]\n}\n\n/** What the pointer can land on in a stack with ribbons: each series' bars and its ribbons. */\ninterface StackMarks {\n  bars: readonly { series: string; place: BarPlace }[]\n  ribbons: readonly { series: string; ends: readonly [RibbonEnd, RibbonEnd] }[]\n}\n\n/**\n * The series whose bar or ribbon holds a point, `across` the categories as\n * the ribbon ends have it and `along` the value axis, both fractions of the\n * plot; null over neither, such as past a stack's end or where no ribbon\n * crosses a missing value. A mark with no length holds nothing.\n */\nfunction stackSeriesAt(\n  marks: StackMarks,\n  point: { across: number; along: number },\n  layout: RibbonLayout,\n): string | null {\n  const inside = (span: Span) => {\n    const low = Math.min(span[0], span[1])\n    const high = Math.max(span[0], span[1])\n    return high > low && point.along >= low && point.along <= high\n  }\n  const bar = marks.bars.find(({ place }) => {\n    const { centre, half } = barAcross(place, layout)\n    return Math.abs(point.across - centre) <= half && inside([place.from, place.to])\n  })\n  if (bar) return bar.series\n  const ribbon = marks.ribbons.find(({ ends }) => {\n    const span = ribbonSpanAt(ends, point.across)\n    return span !== null && inside(span)\n  })\n  return ribbon?.series ?? null\n}\n\nexport {\n  barAcross,\n  barClip,\n  BarFrameContext,\n  type BarFrameValue,\n  useBarFrame,\n  barClipPath,\n  barInsets,\n  BarLabel,\n  type BarLabelPosition,\n  type BarPlace,\n  BarPlaceholder,\n  BarShape,\n  farSide,\n  labelFits,\n  labelPlace,\n  missingMark,\n  outsideRoom,\n  PLACEHOLDER_COUNT,\n  placeholderClip,\n  placeholderValues,\n  type RibbonEnd,\n  ribbonEnds,\n  type RibbonLayout,\n  type RibbonPair,\n  NO_TUCK,\n  RIBBON_TUCK,\n  type RibbonTuck,\n  ribbonClipPath,\n  ribbonsOf,\n  ribbonSpanAt,\n  roundCorners,\n  type StackMarks,\n  stackSeriesAt,\n  trackClip,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-bars.tsx"
    }
  ],
  "type": "registry:lib"
}