{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "donut-chart",
  "title": "Donut chart",
  "description": "Shares of a whole as a ring or, with no hole, a pie chart, with labels, more rings inside and a slice that grows. The slice under the pointer or the keys stays bright while the rest step back and its value rolls into the centre; new data or a slice hidden from the legend moves every slice by its angles from where it is.",
  "registryDependencies": [
    "https://kinoui.com/r/chart.json",
    "https://kinoui.com/r/chart-centre.json",
    "https://kinoui.com/r/chart-core.json",
    "https://kinoui.com/r/chart-root.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/chart-radial.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/placeholder.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/donut-chart.tsx",
      "content": "'use client'\n\nimport {\n  type CategoryChartProps,\n  chartParts,\n  ChartPartsContext,\n  figureProps,\n  pickedName,\n  shareColor,\n  ShareTooltipContent,\n  shareValue,\n  useChartActive,\n  useDeclared,\n  useRegistry,\n} from '@/registry/lib/chart-base'\nimport { ChartCentreText } from '@/registry/lib/chart-centre'\nimport {\n  ListChartFrame,\n  type ListChartStop,\n  useListChart,\n} from '@/registry/lib/chart-list'\nimport { listReader, type ListStop } from '@/registry/lib/chart-list-reader'\nimport type { ChartPattern } from '@/registry/lib/chart-math'\nimport {\n  foldPoint,\n  insideLabelFits,\n  LEADER,\n  outerPoint,\n  outsideLabelsShown,\n  outsideRoom,\n  RadialLabel,\n  ringBands,\n  type RingBand,\n  ringSlices,\n  round,\n  type Slice,\n  sliceAt,\n  sliceDash,\n} from '@/registry/lib/chart-radial'\nimport {\n  ChartSvgPattern,\n  drawingFrame,\n  drawingSize,\n  forcedSeriesTextColor,\n  labelOnClassName,\n  plotLayerClassName,\n  stepBackInkClassName,\n  useChartRootValue,\n} from '@/registry/lib/chart-root'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport {\n  placeholderBreatheClassName,\n  placeholderFillClassName,\n} from '@/registry/lib/placeholder'\nimport {\n  Children,\n  type ComponentProps,\n  createContext,\n  type CSSProperties,\n  isValidElement,\n  memo,\n  type ReactNode,\n  use,\n  useLayoutEffect,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The Donut chart: shares of a whole as slices of a ring, or of a pie. Each\n * slice is a dash along one circle, so a new value, a slice hidden or new\n * data moves every slice by its angles, in one CSS transition of the dash,\n * which turns back from wherever it is. The slice under the pointer or the\n * keys stays bright while the rest step back, and its value rolls into the\n * centre. `DonutChartRing` adds a ring inside for another value of the same\n * slices, and `DonutChartLabels` writes on or beside each slice.\n */\n\ninterface DonutChartProps extends Omit<\n  CategoryChartProps,\n  'domain' | 'tickCount' | 'tickValues' | 'allowDecimals' | 'ordered'\n> {\n  /** The key of each slice's value in the data. The config's keys are the slices, under `index`. */\n  dataKey: string\n  /** What the values are, such as \"Visitors\": the centre's caption at rest, and the data table's column. */\n  valueLabel?: string\n  /** The hole's radius as a share of the ring's, from 0, a pie, to below 1. */\n  innerRadius?: number\n  /** The room between two slices, in px, as wide at the hole as at the edge; 0 for none. */\n  sliceGap?: number\n  /** The slice under the pointer, the keys or picked grows out of the ring, as well as staying bright. */\n  grow?: boolean\n  /**\n   * How the slices arrive the first time the chart comes into view: drawn\n   * around the ring from the top, or simply there, the default, since a page\n   * that loads doesn't animate into place.\n   */\n  entrance?: 'draw' | 'none'\n}\n\n/** One ring's value of each slice, by its key in the data and its name. */\ninterface DonutRingKey {\n  dataKey: string\n  label: string\n}\n\n/** A ring as the chart draws it: its slices, their values and its band. */\ninterface DonutRing extends DonutRingKey {\n  /** Where each slice sits, by its key, the leaving ones folded to nothing. */\n  slices: ReadonlyMap<string, Slice>\n  /** Each shown slice's place, by its place in the data, for the pointer and labels. */\n  shares: readonly Slice[]\n  /** The values of the slices shown, by their place in the data. */\n  values: readonly number[]\n  total: number\n  band: RingBand\n}\n\ninterface DonutContextValue {\n  /** Every slice to draw, the leaving ones too. */\n  stops: readonly ListChartStop[]\n  /** The slices still in the data, in order. */\n  current: readonly ListStop[]\n  /** A slice's name, as the chart writes it, from its value under the chart's `index`. */\n  nameText: (value: unknown) => string\n  /** The rings, outermost first: the chart's own, then each `DonutChartRing`'s. */\n  rings: readonly DonutRing[]\n  addRing: (ring: DonutRingKey) => () => void\n  innerRadius: number\n  /** The outer ring's radius at rest, in px. */\n  outer: number\n  /** How far the slices reach, in px: the outer ring's radius, grown. */\n  edge: number\n  sliceGap: number\n  grow: boolean\n  valueLabel: string\n  entering: boolean\n}\n\nconst DonutContext = createContext<DonutContextValue | null>(null)\n\nfunction useDonutChart() {\n  const donut = use(DonutContext)\n  if (!donut) throw new Error('Donut chart parts go inside a `DonutChart`.')\n  return donut\n}\n\n/** What the Donut's labels need to fit past the ring. */\ninterface DonutRoomState {\n  /** The slices still in the data. */\n  stops: readonly ListStop[]\n  /** The outer ring's values, by their key in the data, and their total. */\n  ring: { dataKey: string; total: number }\n  plot: { width: number; height: number }\n  textWidth: (text: string) => number\n  valueText: (value: number) => string\n  nameText: (value: unknown) => string\n  locale: Intl.LocalesArgument\n}\n\n/** What a part written inside the Donut tells it as it renders. */\ninterface DonutPartDeclaration {\n  /** The px a part draws past the ring, or null for a part that draws none. */\n  room: ((state: DonutRoomState) => number) | null\n}\n\n/** What tells a part's declaration apart; empty for one that says nothing. */\nfunction donutSignature(declaration: DonutPartDeclaration) {\n  return declaration.room ? 'room' : ''\n}\n\nconst donutChartKeys = [\n  'dataKey',\n  'valueLabel',\n  'innerRadius',\n  'sliceGap',\n  'grow',\n  'entrance',\n]\n\n/** The room between two slices, in px, by default. */\nconst SLICE_GAP = 2\n\n/** The room between two rings, in px. */\nconst RING_GAP = 4\n\n/**\n * The least arc a slice with a value takes along the ring's middle, in px,\n * its gap included, so a tiny share still shows and the pointer can find it.\n */\nconst MIN_ARC = 6\n\n/** How much a growing slice scales, when `--donut-chart-grow` isn't set. */\nconst GROW = 1.08\n\n/**\n * The chart's root: it works out each ring's slices from the data, and lays\n * out the frame its legend, centre, labels and tooltip draw in.\n */\nfunction DonutChart(props: DonutChartProps) {\n  const {\n    dataKey,\n    valueLabel,\n    innerRadius = 0.62,\n    sliceGap = SLICE_GAP,\n    grow = false,\n    entrance = 'none',\n    messages,\n    description,\n    empty,\n    className,\n    children,\n    ref,\n  } = props\n  const hole = Math.min(0.95, Math.max(0, innerRadius))\n  const gap = Math.max(0, sliceGap)\n  const chart = useListChart(\n    {\n      ...props,\n      // A slice is named by its config's label, as its legend entry is.\n      categoryFormat:\n        props.categoryFormat ??\n        ((value) => {\n          const named = props.config[String(value)]?.label\n          return typeof named === 'string' ? named : String(value)\n        }),\n      messages: {\n        series: 'Slices',\n        empty: 'No data yet',\n        allHidden: 'Every slice is hidden',\n        showAll: (count) => `Show all ${count} slices`,\n        ...messages,\n      },\n    },\n    { entrance: entrance !== 'none', rowsAreSeries: true },\n  )\n  const { state, current, stops, stopText } = chart\n  const parts = chartParts(children, donutSignature)\n  const added = useRegistry<DonutRingKey>()\n  const label = valueLabel ?? state.messages.total\n  // The rings among its own children are known from the first render, as on the server's\n  // first paint; any deeper one joins once it mounts.\n  const declared = Children.toArray(children).flatMap((child) =>\n    isValidElement<DonutRingKey>(child) && child.type === DonutChartRing\n      ? [{ dataKey: child.props.dataKey, label: child.props.label }]\n      : [],\n  )\n  const keys: DonutRingKey[] = [{ dataKey, label }]\n  for (const ring of [...declared, ...added.values]) {\n    if (!keys.some((key) => key.dataKey === ring.dataKey)) keys.push(ring)\n  }\n  const measured = state.plotSize.width > 0 && state.plotSize.height > 0\n  // Labels past the ring keep room for themselves, in px, so the ring waits unseen for the\n  // plot's size rather than draw at one size and then shrink.\n  const rooms = parts.declarations.flatMap((part) => (part.room ? [part.room] : []))\n  const total = current.reduce((sum, stop) => sum + shareValue(stop.datum, dataKey), 0)\n  const roomState: DonutRoomState = {\n    stops: current,\n    ring: { dataKey, total },\n    plot: state.plotSize,\n    textWidth: state.textWidth,\n    valueText: state.valueText,\n    nameText: stopText,\n    locale: state.locale,\n  }\n  const room = measured ? Math.max(0, ...rooms.map((roomOf) => roomOf(roomState))) : 0\n  const { width, height } = drawingSize(state.plotSize)\n  const scale = useGrowScale(state.root, grow, width, height)\n  const edge = Math.max(0, Math.min(width, height) / 2 - 0.5 - room)\n  const outer = edge / scale\n  const bands = ringBands(outer, outer * hole, keys.length, RING_GAP)\n  const rings: DonutRing[] = keys.map((key, at) => {\n    const band = bands[at] ?? { inner: 0, outer: 0 }\n    const values = current.map((stop) => shareValue(stop.datum, key.dataKey))\n    const circumference = Math.PI * (band.inner + band.outer)\n    const shares = ringSlices(values, circumference > 0 ? MIN_ARC / circumference : 0)\n    const slices = new Map<string, Slice>()\n    for (const stop of stops) {\n      if (!chart.entered) slices.set(stop.key, { start: 0, size: 0 })\n      else if (stop.leaving) {\n        // Folded to nothing where it would sit among the slices that stay.\n        slices.set(stop.key, { start: foldPoint(shares, stop.index), size: 0 })\n      } else slices.set(stop.key, shares[stop.index] ?? { start: 0, size: 0 })\n    }\n    return {\n      ...key,\n      band,\n      values,\n      shares,\n      slices,\n      total: values.reduce((sum, value) => sum + value, 0),\n    }\n  })\n  const main = rings[0]!\n  const percent = numberFormatter(state.locale, {\n    style: 'percent',\n    maximumFractionDigits: 1,\n  })\n  const nameOf = (stop: ListStop) => stopText(stop.value)\n  const shareOf = (ring: DonutRing, at: number) =>\n    ring.total === 0 ? 0 : (ring.values[at] ?? 0) / ring.total\n  const valueText = (ring: DonutRing, stop: ListStop) =>\n    chart.datumText(stop.datum?.[ring.dataKey])\n  const several = rings.length > 1\n  const reader = listReader({\n    current,\n    walk: { kind: 'round' },\n    series: { kind: 'none' },\n    direction: state.direction,\n    hit: (point) =>\n      sliceAt(\n        point.x - point.width / 2,\n        point.y - point.height / 2,\n        rings.map((ring, at) => ({\n          inner: ring.band.inner,\n          // The outer ring reaches as far as a slice of it grows.\n          outer: at === 0 ? edge : ring.band.outer,\n          slices: ring.shares,\n        })),\n      ),\n    // The tooltip sits on the outer edge of the slice's middle, opening away from the ring.\n    anchor: (stop) => {\n      const slice = main.shares[stop.index]\n      if (!slice || width === 0 || height === 0) return null\n      return outerPoint(slice.start + slice.size / 2, width, height, edge)\n    },\n    words: {\n      describe: (stop) =>\n        `${pickedName(nameOf(stop), chart.picked === stop.key, state.messages)}: ${rings\n          .map(\n            (ring) =>\n              `${ring.label} ${valueText(ring, stop)}, ${percent.format(shareOf(ring, stop.index))}`,\n          )\n          .join('; ')}`,\n      tooltip: (stop) => (\n        <ShareTooltipContent\n          chart={state}\n          category={stop}\n          name={nameOf(stop)}\n          rows={rings.map((ring) => ({\n            label: several ? ring.label : null,\n            value: valueText(ring, stop),\n            share: percent.format(shareOf(ring, stop.index)),\n          }))}\n        />\n      ),\n      table: {\n        header: state.messages.category,\n        columns: several\n          ? rings.map((ring) => ring.label)\n          : [label, state.messages.share],\n        rows: current.map((stop) => ({\n          key: stop.key,\n          name: nameOf(stop),\n          cells: several\n            ? rings.map((ring) => valueText(ring, stop))\n            : [valueText(main, stop), percent.format(shareOf(main, stop.index))],\n        })),\n        footer: several\n          ? rings.map((ring) => state.valueText(ring.total))\n          : [state.valueText(main.total), percent.format(main.total === 0 ? 0 : 1)],\n      },\n    },\n  })\n\n  return (\n    <DonutContext\n      value={{\n        stops,\n        current,\n        nameText: stopText,\n        rings,\n        addRing: added.add,\n        innerRadius: hole,\n        outer,\n        edge,\n        sliceGap: gap,\n        grow,\n        valueLabel: label,\n        entering: chart.entering,\n      }}\n    >\n      <ChartPartsContext value={parts}>\n        <ListChartFrame\n          chart={chart}\n          reader={reader}\n          ref={ref}\n          slot='donut-chart'\n          description={description}\n          empty={empty}\n          measuring={rooms.length > 0 && !measured}\n          className={className}\n          placeholder={\n            chart.placeholder ? (\n              <DonutTrack slot='donut-chart-placeholder' breathe />\n            ) : (\n              chart.status === 'ready' &&\n              main.total === 0 && <DonutTrack slot='donut-chart-track' />\n            )\n          }\n          {...figureProps(props, donutChartKeys)}\n        >\n          <DonutSlices ring={0} />\n          {children}\n        </ListChartFrame>\n      </ChartPartsContext>\n    </DonutContext>\n  )\n}\n\n/**\n * How much a growing slice scales: the `--donut-chart-grow` set on the chart\n * or above it, read again as the chart changes size, so the ring leaves room\n * for it.\n */\nfunction useGrowScale(\n  root: { current: HTMLElement | null },\n  grow: boolean,\n  width: number,\n  height: number,\n) {\n  const [scale, setScale] = useState(GROW)\n  useLayoutEffect(() => {\n    const element = root.current\n    if (!grow || !element) return\n    const read = Number.parseFloat(\n      getComputedStyle(element).getPropertyValue('--donut-chart-grow'),\n    )\n    // eslint-disable-next-line react-hooks/set-state-in-effect -- the scale is the page's CSS, read once the chart is laid out, before it paints\n    setScale(Number.isFinite(read) && read >= 1 ? read : GROW)\n  }, [root, grow, width, height])\n  return grow ? scale : 1\n}\n\n/**\n * One ring: a circle for each slice, each drawn as its dash, in its\n * category's colour. While the chart enters, the slices draw round from the\n * top on `draw`; after that every change moves on `layout`, and a slice that\n * arrives grows out from its own start.\n */\nfunction DonutSlices({ ring: at }: { ring: number }) {\n  const chart = useChartRootValue()\n  const { spotlit } = useChartActive()\n  const donut = useDonutChart()\n  const ring = donut.rings[at]\n  // Before the plot is measured, drawn in a square stand-in that the SVG fits to the plot.\n  const { width, height } = drawingSize(chart.plotSize)\n  if (!ring || chart.status === 'empty') return null\n  const { inner, outer } = ring.band\n  const radius = (inner + outer) / 2\n  const circumference = 2 * Math.PI * radius\n  // A circle starts on its right and runs clockwise; turned back a quarter, it starts at the\n  // top, so a dash's offset is its start. Its length is exactly the circumference the dashes\n  // are measured on, which a path drawn as two arcs isn't.\n  const circle = {\n    cx: round(width / 2),\n    cy: round(height / 2),\n    r: round(radius),\n  }\n  const drawn = [...ring.slices.values()].filter((slice) => slice.size > 0).length\n  // The gaps are cut out of the ring as bands of an even width, so they don't taper towards\n  // the centre as a dash's ends would; the dashes themselves meet end to end. The mask stays\n  // while a ring shows a single slice, or none yet, so its gaps fade and turn rather than\n  // vanish.\n  const gaps = donut.sliceGap > 0\n  const maskId = `${chart.id}-${at}-gaps`\n  return (\n    <div\n      data-slot='donut-chart-slices'\n      aria-hidden\n      className={cn(plotLayerClassName, 'z-10')}\n    >\n      <svg\n        className='absolute inset-0 size-full overflow-visible'\n        viewBox={`0 0 ${round(width)} ${round(height)}`}\n        {...drawingFrame(chart.plotSize, 'xMidYMid meet')}\n      >\n        {gaps && (\n          <defs>\n            <mask\n              id={maskId}\n              maskUnits='userSpaceOnUse'\n              x={-round(width)}\n              y={-round(height)}\n              width={round(width * 3)}\n              height={round(height * 3)}\n            >\n              <rect\n                x={-round(width)}\n                y={-round(height)}\n                width={round(width * 3)}\n                height={round(height * 3)}\n                fill='white'\n              />\n              {donut.stops.map((category) => {\n                const slice = ring.slices.get(category.key) ?? {\n                  start: 0,\n                  size: 0,\n                }\n                return (\n                  <SliceGap\n                    key={category.key}\n                    cx={circle.cx}\n                    cy={circle.cy}\n                    // Past the ring's edge, and past a slice that grows.\n                    reach={round(donut.edge * 1.5)}\n                    width={donut.sliceGap}\n                    turn={slice.start}\n                    shown={drawn > 1 && slice.size > 0 && !category.leaving}\n                    entering={donut.entering}\n                  />\n                )\n              })}\n            </mask>\n          </defs>\n        )}\n        <g mask={gaps ? `url(#${maskId})` : undefined}>\n          {donut.stops.map((category) => {\n            const slice = ring.slices.get(category.key) ?? {\n              start: 0,\n              size: 0,\n            }\n            const { dash, offset, empty } = sliceDash(slice, circumference, drawn === 1)\n            const arriving = sliceDash(\n              { start: slice.start, size: 0 },\n              circumference,\n              drawn === 1,\n            )\n            const slot = chart.series.indexOf(category.key)\n            const lit = spotlit === category.index && !category.leaving\n            const dim =\n              (spotlit !== null && !lit && !category.leaving) ||\n              (chart.emphasis !== null && chart.emphasis !== category.key)\n            return (\n              <SliceShape\n                key={category.key}\n                id={`${chart.id}-${at}-${category.key}`}\n                circle={circle}\n                thickness={round(outer - inner)}\n                dash={dash}\n                offset={offset}\n                fromDash={arriving.dash}\n                fromOffset={arriving.offset}\n                empty={empty || category.leaving}\n                dim={dim}\n                // Only the outer ring grows: an inner one would reach into the ring around it.\n                grown={donut.grow && at === 0 && lit}\n                entering={donut.entering}\n                color={shareColor(chart, category)}\n                slot={slot === -1 ? category.index : slot}\n                pattern={slot === -1 ? 'solid' : chart.patternOf(category.key)}\n              />\n            )\n          })}\n        </g>\n      </svg>\n    </div>\n  )\n}\n\n/**\n * The gap before a slice: a band `width` px wide from the centre out past the\n * ring, cut out of the ring by its mask. It turns round to the slice's start\n * in step with the slice's dash, on the same role, and fades while its slice\n * has nothing to show.\n */\nconst SliceGap = memo(function SliceGap({\n  cx,\n  cy,\n  reach,\n  width,\n  turn,\n  shown,\n  entering,\n}: {\n  cx: number\n  cy: number\n  reach: number\n  width: number\n  turn: number\n  shown: boolean\n  entering: boolean\n}) {\n  return (\n    <line\n      x1={cx}\n      y1={cy}\n      x2={cx}\n      y2={round(cy - reach)}\n      stroke='black'\n      strokeWidth={width}\n      data-entering={entering ? '' : undefined}\n      className={cn(\n        // An SVG element turns with `transform`, which runs off the main thread.\n        '[transform:rotate(var(--gap-turn))] transition-none duration-(--motion-layout-duration) ease-[var(--motion-layout-easing),var(--motion-layout-fade-easing)] group-data-mounted/chart:transition-[transform,opacity] group-data-mounted/chart:starting:opacity-0 data-entering:duration-(--motion-draw-duration) data-entering:ease-[var(--motion-draw-easing),var(--motion-layout-fade-easing)] motion-reduce:group-data-mounted/chart:transition-[opacity]',\n        !shown && 'opacity-0',\n      )}\n      style={\n        {\n          transformOrigin: `${cx}px ${cy}px`,\n          '--gap-turn': `${round(turn * 360)}deg`,\n        } as CSSProperties\n      }\n    />\n  )\n})\n\n/**\n * One slice: its dash along the ring, with its pattern. Memoised, so the\n * pointer moving between slices redraws only the ones it lights or dims.\n */\nconst SliceShape = memo(function SliceShape({\n  id,\n  circle,\n  thickness,\n  dash,\n  offset,\n  fromDash,\n  fromOffset,\n  empty,\n  dim,\n  grown,\n  entering,\n  color,\n  slot,\n  pattern,\n}: {\n  id: string\n  circle: { cx: number; cy: number; r: number }\n  thickness: number\n  dash: string\n  offset: number\n  fromDash: string\n  fromOffset: number\n  empty: boolean\n  dim: boolean\n  grown: boolean\n  entering: boolean\n  color: string\n  slot: number\n  pattern: ChartPattern\n}) {\n  const patternId = `${id}-pattern`\n  return (\n    <g\n      data-dim={dim ? '' : undefined}\n      data-grown={grown ? '' : undefined}\n      className={cn(\n        // An SVG element scales with `transform`, which runs off the main thread.\n        'text-(--mark-ink) [transform:scale(1)] transition-none group-data-mounted/chart:transition-[color,transform] duration-(--motion-layout-duration) ease-[var(--motion-layout-fade-easing),var(--motion-layout-easing)] data-grown:[transform:scale(var(--donut-chart-grow,1.08))] motion-reduce:group-data-mounted/chart:transition-[color]',\n        stepBackInkClassName,\n        forcedSeriesTextColor(slot),\n      )}\n      style={\n        {\n          '--mark-color': color,\n          transformOrigin: `${circle.cx}px ${circle.cy}px`,\n        } as CSSProperties\n      }\n    >\n      {pattern !== 'solid' && (\n        // The circle is turned back a quarter, so the pattern turns forward to match the swatches.\n        <ChartSvgPattern id={patternId} pattern={pattern} turn={90} />\n      )}\n      <circle\n        {...circle}\n        transform={`rotate(-90 ${circle.cx} ${circle.cy})`}\n        data-entering={entering ? '' : undefined}\n        data-empty={empty ? '' : undefined}\n        className='fill-none transition-none [stroke-dasharray:var(--slice-dash)] [stroke-dashoffset:var(--slice-offset)] group-data-mounted/chart:transition-[stroke-dasharray,stroke-dashoffset,opacity] duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-mounted/chart:starting:[stroke-dasharray:var(--slice-from-dash)] group-data-mounted/chart:starting:[stroke-dashoffset:var(--slice-from-offset)] group-data-mounted/chart:starting:opacity-0 data-empty:opacity-0 data-entering:duration-(--motion-draw-duration) data-entering:ease-(--motion-draw-easing) motion-reduce:group-data-mounted/chart:transition-[opacity]'\n        style={\n          {\n            stroke: pattern === 'solid' ? 'currentColor' : `url(#${patternId})`,\n            strokeWidth: thickness,\n            // Variables, not the properties, so the class's starting dash isn't overruled by an inline style.\n            '--slice-dash': dash,\n            '--slice-offset': `${offset}px`,\n            '--slice-from-dash': fromDash,\n            '--slice-from-offset': `${fromOffset}px`,\n          } as CSSProperties\n        }\n      />\n    </g>\n  )\n})\n\n/**\n * Another ring inside the chart's own, for a second value of the same\n * slices, such as last year's beside this year's. Each ring takes an even\n * share of the room between the hole and the edge, outermost first, and the\n * tooltip, the data table and a screen reader give every ring's value.\n */\nfunction DonutChartRing({\n  dataKey,\n  label,\n}: {\n  /** The key of each slice's value in this ring, in the chart's data. */\n  dataKey: string\n  /** What this ring's values are, such as \"2025\", in the tooltip and the data table. */\n  label: string\n}) {\n  const donut = useDonutChart()\n  const { addRing } = donut\n  useLayoutEffect(() => addRing({ dataKey, label }), [addRing, dataKey, label])\n  const at = donut.rings.findIndex((ring) => ring.dataKey === dataKey)\n  return at > 0 ? <DonutSlices ring={at} /> : null\n}\n\n/** What a slice's label is given to write. */\ninterface DonutLabelSlice {\n  key: string\n  /** The slice's name, from its config's label. */\n  name: string\n  value: number\n  /** Its share of the ring's total, from 0 to 1. */\n  share: number\n}\n\n/** Where a label sits: past the ring's edge on a short line, or on its slice. */\ntype DonutLabelPosition = 'outside' | 'inside'\n\n/** What each label writes: the slice's value, its share, its name, or your own words. */\ntype DonutLabelContent = 'value' | 'share' | 'name' | ((slice: DonutLabelSlice) => string)\n\ninterface DonutChartLabelsProps extends Omit<\n  ComponentProps<'div'>,\n  'children' | 'content'\n> {\n  position?: DonutLabelPosition\n  content?: DonutLabelContent\n}\n\n/**\n * What a label is given to write for `stop` of the ring whose values are\n * under `dataKey` and add up to `total`. A leaving slice keeps the share it\n * had while it was part of the whole.\n */\nfunction labelSlice(\n  stop: ListStop & { leaving?: boolean },\n  ring: { dataKey: string; total: number },\n  nameText: (value: unknown) => string,\n): DonutLabelSlice {\n  const value = stop.datum ? shareValue(stop.datum, ring.dataKey) : 0\n  const whole = stop.leaving ? ring.total + value : ring.total\n  return {\n    key: stop.key,\n    name: nameText(stop.value),\n    value,\n    share: whole === 0 ? 0 : value / whole,\n  }\n}\n\n/** What a label with `content` writes for `slice`. */\nfunction labelText(\n  content: DonutLabelContent,\n  slice: DonutLabelSlice,\n  valueText: (value: number) => string,\n  locale: Intl.LocalesArgument,\n) {\n  if (typeof content === 'function') return content(slice)\n  if (content === 'share')\n    return numberFormatter(locale, {\n      style: 'percent',\n      maximumFractionDigits: 0,\n    }).format(slice.share)\n  if (content === 'name') return slice.name\n  return valueText(slice.value)\n}\n\n/** The px labels with `content` take past the ring: a line of text above and below it, and the widest label beside it. */\nfunction labelsRoom(content: DonutLabelContent, state: DonutRoomState) {\n  const widths = state.stops.map((stop) =>\n    state.textWidth(\n      labelText(\n        content,\n        labelSlice(stop, state.ring, state.nameText),\n        state.valueText,\n        state.locale,\n      ),\n    ),\n  )\n  return outsideRoom(state.plot.width, state.plot.height, Math.max(0, ...widths))\n}\n\n/**\n * Writes each slice's value, share or name, past the outer ring's edge on a\n * short line, or on the slice. A label with no room, or one that would\n * overlap a bigger slice's, is skipped, and every label travels round with\n * its slice. Past the ring, it goes straight inside the chart, or in a\n * fragment there, so the chart keeps room for it as it renders.\n */\nfunction DonutChartLabels(props: DonutChartLabelsProps) {\n  const { position = 'outside', content = 'value', className, ...rest } = props\n  useDeclared('DonutChartLabels', DonutChartLabels.declare(props), donutSignature)\n  const chart = useChartRootValue()\n  const { spotlit } = useChartActive()\n  const donut = useDonutChart()\n  const ring = donut.rings[0]!\n  // Every slice's, a leaving one's too, so its label fades out with its words.\n  const textOf = (stop: ListChartStop | ListStop) =>\n    labelText(\n      content,\n      labelSlice(stop, ring, donut.nameText),\n      chart.valueText,\n      chart.locale,\n    )\n  const widths = donut.current.map((stop) => chart.textWidth(textOf(stop)))\n  const outside = position === 'outside'\n  // Before the plot is measured, labels on their slices sit in the slices' square stand-in;\n  // those past the ring wait, since the room they take is in pixels, not a share of the plot.\n  const measured = chart.plotSize.width > 0 && chart.plotSize.height > 0\n  if (chart.status !== 'ready' || (outside && !measured)) return null\n  const drawn = drawingSize(chart.plotSize)\n  const stretch = measured ? null : 1 / Math.min(drawn.width, drawn.height)\n  const { inner, outer } = ring.band\n  // On a pie, a little past halfway out, where a slice is wider; on a ring, its middle.\n  const radius = outside\n    ? donut.edge + LEADER.gap + LEADER.length + LEADER.text\n    : inner === 0\n      ? outer * 0.62\n      : (inner + outer) / 2\n  const shown = outside\n    ? outsideLabelsShown(ring.shares, widths, radius)\n    : ring.shares.map((slice, at) =>\n        insideLabelFits(slice, widths[at] ?? 0, radius, outer - inner, donut.sliceGap),\n      )\n  return (\n    <div\n      data-slot='donut-chart-labels'\n      aria-hidden\n      className={cn(plotLayerClassName, 'z-20', className)}\n      {...rest}\n    >\n      {donut.stops.map((stop) => {\n        const slice = ring.slices.get(stop.key) ?? { start: 0, size: 0 }\n        const at = stop.leaving ? -1 : stop.index\n        return (\n          <DonutLabel\n            key={stop.key}\n            turn={slice.start + slice.size / 2}\n            radius={radius}\n            stretch={stretch}\n            edge={outside ? donut.edge : null}\n            color={shareColor(chart, stop)}\n            shown={at !== -1 && slice.size > 0 && !donut.entering && (shown[at] ?? false)}\n            dim={spotlit !== null && spotlit !== stop.index}\n          >\n            {textOf(stop)}\n          </DonutLabel>\n        )\n      })}\n    </div>\n  )\n}\n\nDonutChartLabels.declare = ({\n  position = 'outside',\n  content = 'value',\n}: DonutChartLabelsProps): DonutPartDeclaration => ({\n  room: position === 'outside' ? (state) => labelsRoom(content, state) : null,\n})\n\n/**\n * One slice's label, on its slice or past the ring on a short line from its\n * `edge`, in the words' colours there. Memoised, as the slices are.\n */\nconst DonutLabel = memo(function DonutLabel({\n  turn,\n  radius,\n  stretch,\n  edge,\n  color,\n  shown,\n  dim,\n  children,\n}: {\n  turn: number\n  radius: number\n  stretch: number | null\n  /** The ring's edge, in px, for a label outside; null for one on its slice. */\n  edge: number | null\n  /** The slice's colour, which a label on it is written against. */\n  color: string\n  shown: boolean\n  dim: boolean\n  children: string\n}) {\n  return (\n    <RadialLabel\n      turn={turn}\n      radius={radius}\n      stretch={stretch}\n      edge={edge}\n      centred={edge === null}\n      shown={shown}\n      className={cn(\n        'font-medium whitespace-nowrap tabular-nums',\n        edge === null\n          ? // On its slice: near white or near black, whichever reads on the slice's colour.\n            labelOnClassName\n          : dim\n            ? 'text-muted-foreground'\n            : 'text-foreground',\n      )}\n      style={{ '--label-on': color } as CSSProperties}\n    >\n      {children}\n    </RadialLabel>\n  )\n})\n\n/**\n * The whole ring in the placeholder's tint: what shows while the data loads,\n * breathing slowly, and behind slices that add up to nothing, so the chart\n * keeps its shape.\n */\nfunction DonutTrack({ slot, breathe = false }: { slot: string; breathe?: boolean }) {\n  const donut = useDonutChart()\n  const inner = donut.rings.at(-1)?.band.inner ?? 0\n  return (\n    <div\n      data-slot={slot}\n      aria-hidden\n      className={cn(\n        plotLayerClassName,\n        'z-10 flex items-center justify-center transition-opacity duration-(--motion-enter-duration) ease-(--motion-enter-easing) group-data-mounted/chart:starting:opacity-0',\n      )}\n    >\n      <div className={cn(breathe && placeholderBreatheClassName)}>\n        <div\n          // As large as the ring.\n          className={cn(\n            'size-(--donut-size) rounded-full [mask-image:radial-gradient(closest-side,transparent_var(--donut-hole),black_calc(var(--donut-hole)+0.5px))]',\n            placeholderFillClassName,\n          )}\n          style={\n            {\n              '--donut-size': `${round(donut.outer * 2)}px`,\n              '--donut-hole': `${donut.outer === 0 ? 0 : round((inner / donut.outer) * 100)}%`,\n            } as CSSProperties\n          }\n        />\n      </div>\n    </div>\n  )\n}\n\n/**\n * What sits in the hole: the total of the slices shown, under `label`, and\n * the value and name of the slice under the pointer, the keys, or picked,\n * rolling in as it changes. A pie has no hole, so it draws nothing there.\n */\nfunction DonutChartCentre({\n  label,\n  className,\n  style,\n  ...props\n}: Omit<ComponentProps<'div'>, 'children'> & {\n  /** The caption under the total; the chart's `valueLabel` by default. */\n  label?: ReactNode\n}) {\n  const chart = useChartRootValue()\n  const { spotlit } = useChartActive()\n  const donut = useDonutChart()\n  const ring = donut.rings[0]\n  if (!ring || chart.status !== 'ready' || donut.innerRadius < 0.4) return null\n  const stop = spotlit === null ? undefined : donut.current[spotlit]\n  const value = stop ? (ring.values[stop.index] ?? 0) : ring.total\n  const caption = stop\n    ? (chart.config[stop.key]?.label ?? donut.nameText(stop.value))\n    : (label ?? donut.valueLabel)\n  const hole = donut.outer * 2 * donut.innerRadius\n  const drawn = drawingSize(chart.plotSize)\n  return (\n    <div\n      data-slot='donut-chart-centre'\n      aria-hidden\n      className={cn(\n        plotLayerClassName,\n        'z-20 flex items-center justify-center',\n        className,\n      )}\n      style={\n        {\n          // Before the plot is measured, the stand-in's hole as a share of the plot's shorter side.\n          '--centre-hole':\n            chart.plotSize.width > 0 && chart.plotSize.height > 0\n              ? `${round(hole)}px`\n              : `calc(min(100cqw, 100cqh) * ${hole / Math.min(drawn.width, drawn.height)})`,\n          ...style,\n        } as CSSProperties\n      }\n      {...props}\n    >\n      <ChartCentreText\n        value={value}\n        caption={caption}\n        format={chart.format}\n        locale={chart.locale}\n      />\n    </div>\n  )\n}\n\nexport {\n  DonutChart,\n  DonutChartCentre,\n  DonutChartLabels,\n  type DonutChartLabelsProps,\n  type DonutChartProps,\n  DonutChartRing,\n  type DonutLabelContent,\n  type DonutLabelPosition,\n  type DonutLabelSlice,\n  type DonutPartDeclaration,\n  type DonutRoomState,\n  labelsRoom,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/donut-chart.tsx"
    }
  ],
  "type": "registry:component"
}