{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "circle-packing-chart",
  "title": "Circle packing chart",
  "description": "A whole as circles packed inside each other, each as large as its value, or rows with no children as one cloud of bubbles: coloured by group, or by a value of their own on a ramp from zero, with a key of sizes. A press on a group zooms into it as one move until it fills the chart, and a path above it, or Escape, zooms back out. The circle under the pointer or the keys stays bright while the rest step back, and new data moves every circle from where it is.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/chart.json",
    "https://kinoui.com/r/chart-cells.json",
    "https://kinoui.com/r/chart-core.json",
    "https://kinoui.com/r/chart-grid.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/chart-root.json",
    "https://kinoui.com/r/chart-tiles.json",
    "https://kinoui.com/r/chart-tree-path.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/placeholder.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/circle-packing-chart.tsx",
      "content": "'use client'\n\nimport {\n  type CategoryChartProps,\n  type EntrancePhase,\n  figureProps,\n  IndexActive,\n  pickedName,\n  ShareTooltipContent,\n  useChartActive,\n  useChartLife,\n  useChartLoad,\n  useChartPick,\n  useIndexFocus,\n} from '@/registry/lib/chart-base'\nimport { CellStepLegend, StepLegendContext } from '@/registry/lib/chart-cells'\nimport { stepEdges, stepExtent, stepOf, stepStrength } from '@/registry/lib/chart-grid'\nimport { allWhole, numberOf } from '@/registry/lib/chart-math'\nimport {\n  type ChartFormat,\n  ChartFrame,\n  type ChartRootValue,\n  forcedSeriesColor,\n  formatterOf,\n  isMeasured,\n  labelOnClassName,\n  plotLayerClassName,\n  type PlotPoint,\n  stepBackLayerClassName,\n  swatchClassName,\n  useChartRootValue,\n  useLeaving,\n} from '@/registry/lib/chart-root'\nimport { linearScale } from '@/registry/lib/chart-scale'\nimport {\n  circleLabelFit,\n  packAt,\n  type PackedCircle,\n  type PackLayout,\n  packLayout,\n  packPoint,\n  packView,\n  type PackView,\n  startsWith,\n  type TileNode,\n  tileNodeAt,\n  tileTree,\n  topColor,\n} from '@/registry/lib/chart-tiles'\nimport {\n  TreeZoomContext,\n  TreeZoomPath,\n  useTreeZoomRoot,\n} from '@/registry/lib/chart-tree-path'\nimport { treeItem, type TreeStop, treeReader } from '@/registry/lib/chart-tree-reader'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport {\n  placeholderBreatheClassName,\n  placeholderFillClassName,\n} from '@/registry/lib/placeholder'\nimport { SwapText } from '@/registry/lib/swap'\nimport {\n  type ComponentProps,\n  createContext,\n  type CSSProperties,\n  memo,\n  type RefObject,\n  use,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The Circle packing chart: a whole as circles packed inside each other,\n * each leaf as large as its value. A row's `children` are the circles inside\n * it; rows with none pack into one cloud of bubbles. The part in view fills\n * the chart's round window, its circles coloured by the top of the tree they\n * are under or by a value of their own, and a press on a group zooms into it\n * as one move of the whole layer. The way back out, Escape, or the path\n * above the chart zoom out again. The circle under the pointer or the keys\n * stays bright while the rest step back, and new data moves every circle\n * from where it is.\n */\n\ninterface CirclePackingChartProps extends Omit<\n  CategoryChartProps,\n  | 'domain'\n  | 'tickCount'\n  | 'tickValues'\n  | 'allowDecimals'\n  | 'ordered'\n  | 'patterns'\n  | 'selected'\n  | 'defaultSelected'\n  | 'onSelectedChange'\n> {\n  /** The key of each row's value in the data: a circle's area. A row with `children` is worth them added up. */\n  dataKey: string\n  /** What the values are, such as \"Spend\": the tooltip's, the size key's and the data table's word for them. */\n  valueLabel?: string\n  /** The part zoomed into, as the `index` values from the top down to it; `[]`, the whole, by default. */\n  zoom?: string[]\n  defaultZoom?: string[]\n  onZoomChange?: (zoom: string[]) => void\n  /** What each circle of the part in view writes on itself, where it has the room: its name and value, its name, or nothing. */\n  labels?: 'value' | 'name' | 'none'\n  /** The key of a second value to colour the circles by, such as a change, in place of their group's colour. */\n  colorKey?: string\n  /** What the `colorKey` values are, such as \"Change\": the legend's, the tooltip's and the table's word for them. */\n  colorLabel?: string\n  /** How the `colorKey` values are written. */\n  colorFormat?: ChartFormat\n  /**\n   * How the circles arrive the first time the chart comes into view:\n   * growing from their centres, or simply there, the default, since a page\n   * that loads doesn't animate into place.\n   */\n  entrance?: 'draw' | 'none'\n}\n\nconst circlePackingChartKeys = [\n  'dataKey',\n  'valueLabel',\n  'zoom',\n  'defaultZoom',\n  'onZoomChange',\n  'labels',\n  'colorKey',\n  'colorLabel',\n  'colorFormat',\n  'entrance',\n]\n\n/** The room between two circles, and inside a group's edge, in px of the whole. */\nconst PADDING = 3\n\n/** How far from a circle, in px, the pointer still lights it: across the gaps between the circles in view. */\nconst NEAR_CIRCLE = 8\n\n/**\n * Each circle is a disc this many px across, scaled to its size, so a new\n * size is a transform rather than a box laid out again. 100 keeps the\n * scale a plain fraction of the radius.\n */\nconst DISC = 100\n\n/** The room a group's name chip adds to its width, in px. */\nconst GROUP_CHIP = 12\n\n/** The size key's largest circle, in px across its radius. */\nconst KEY_RADIUS = 28\n\ninterface CirclePackingContextValue {\n  /** A circle's radius on screen for each square root of value, in the part in view; none with nothing packed. */\n  perValue: number | null\n  /** Whether the plot is measured: until it is, the key keeps its room with nothing in it, so the plot doesn't move when it fills. */\n  measured: boolean\n  valueLabel: string\n  valueText: (value: number) => string\n}\n\nconst CirclePackingContext = createContext<CirclePackingContextValue | null>(null)\n\nfunction useCirclePacking() {\n  const packing = use(CirclePackingContext)\n  if (!packing)\n    throw new Error('Circle packing chart parts go inside a `CirclePackingChart`.')\n  return packing\n}\n\n/** How a circle is filled: its colour, the slot and the way forced colours draw it, and whether it is a group's tint. */\ninterface CircleFill {\n  color: string\n  slot: number\n  group: boolean\n  /** In forced colours: the series' system colour, a faint wash, or the page's text at a step's strength. */\n  forced: 'series' | 'faint' | number\n}\n\n/** A label of a circle of the part in view: where it sits now and where it came from, in px of the plot. */\ninterface PackLabel {\n  key: string\n  x: number\n  y: number\n  fromX: number\n  fromY: number\n  name: string\n  value: string | null\n  group: boolean\n  color: string\n}\n\n/**\n * The chart's root: the tree from the rows, the part of it in view, its\n * circles packed in the plot, and the colour each takes, with the frame its\n * path, legends and tooltip draw in.\n */\nfunction CirclePackingChart(props: CirclePackingChartProps) {\n  const {\n    data,\n    index,\n    dataKey,\n    config,\n    valueLabel,\n    labels = 'value',\n    colorKey,\n    colorLabel,\n    colorFormat,\n    entrance = 'none',\n    description,\n    empty,\n    className,\n    ref,\n  } = props\n  const tree = tileTree(data, index, dataKey)\n  const { state, hidden, view, nameOf, valueOf, zoomTo } = useTreeZoomRoot(props, tree, {\n    entrance: entrance !== 'none',\n  })\n  const { messages: words, valueText, locale, direction } = state\n\n  const load = useChartLoad(props)\n  const size = state.plotSize\n  const layout = packLayout(tree, {\n    width: size.width,\n    height: size.height,\n    padding: PADDING,\n    direction,\n    hidden,\n  })\n  const shown = packView(layout, view)\n  // While the placeholder or the error stands in for the data, no circle is drawn.\n  const circles = load.placeholder || load.failed ? [] : layout.circles\n  // The circles inside the part in view, in the order the keys step through them: the\n  // layout's, depth first, biggest first, without a hidden group's.\n  const inside = circles\n    .filter(\n      (circle) => circle.key !== view.key && startsWith(circle.node.path, view.path),\n    )\n    .map((circle) => circle.node)\n  const stops: TreeStop[] = inside.map((node, at) => ({\n    id: node.key,\n    name: nameOf(node),\n    value: node.value,\n    datum: node.datum,\n    index: at,\n  }))\n  const nodes = new Map(inside.map((node) => [node.key, node]))\n  const life = useChartLife(\n    props,\n    state,\n    load,\n    {\n      rows: inside.length,\n      shown: state.series.filter((key) => !hidden.includes(key)).length,\n      drawn: stops.length,\n    },\n    { entrance: entrance !== 'none', cascade: null },\n  )\n  const { status, phase } = life\n  // Its props leave out `selected`, so nothing is picked; a press opens or does nothing.\n  const pick = useChartPick(\n    {},\n    stops.map((stop) => stop.id),\n  )\n\n  // A second value's colour: a step of a ramp from zero, one way for below and the other for above.\n  const colorValues = colorKey\n    ? leavesOf(tree).map((node) => numberOf(node.datum[colorKey]))\n    : []\n  const colorScale = linearScale(stepExtent(colorValues), {\n    tickCount: 5,\n    nice: true,\n    allowDecimals: colorKey\n      ? !allWhole(\n          leavesOf(tree).map((node) => node.datum),\n          [colorKey],\n        )\n      : false,\n  })\n  const edges = colorKey ? stepEdges(colorScale.domain, colorScale.ticks) : []\n  const colorText = formatterOf(locale, colorFormat)\n  const colorName = colorLabel ?? colorKey ?? ''\n  const [stepEmphasis, setStepEmphasis] = useState<number | null>(null)\n  const zoomRef = useRef<HTMLDivElement>(null)\n  const labelsRef = useRef<HTMLDivElement>(null)\n  const colorOf = (node: TileNode): number | null =>\n    colorKey ? numberOf(node.datum[colorKey]) : null\n  const fillOf = (circle: PackedCircle): CircleFill => {\n    const slot = Math.max(0, state.series.indexOf(circle.top))\n    const group = circle.node.children.length > 0\n    if (colorKey) {\n      if (group) return { color: NEUTRAL_TINT, slot, group, forced: 'faint' }\n      const step = stepOf(colorOf(circle.node), edges)\n      return {\n        color: step === null ? 'var(--muted)' : divergingFill(step, edges),\n        slot,\n        group,\n        forced: step === null ? 'faint' : divergingStep(step, edges).strength,\n      }\n    }\n    const color = topColor(state.series, config, circle.top)\n    return group\n      ? { color: groupTint(color), slot, group, forced: 'faint' }\n      : { color, slot, group, forced: 'series' }\n  }\n\n  const viewTotal = view.children\n    .filter((child) => view.path.length > 0 || !hidden.includes(child.path[0] ?? ''))\n    .reduce((sum, child) => sum + child.value, 0)\n  const percent = numberFormatter(locale, {\n    style: 'percent',\n    maximumFractionDigits: 1,\n  })\n  const shareOf = (node: TileNode) => (viewTotal === 0 ? 0 : node.value / viewTotal)\n  const label = valueLabel ?? words.value\n  /** The groups between the part in view and `node`, by name: where it sits. */\n  const placeOf = (node: TileNode) =>\n    node.path\n      .slice(view.path.length, -1)\n      .map((_, at) =>\n        nameOf(tileNodeAt(tree, node.path.slice(0, view.path.length + at + 1))),\n      )\n      .join(' / ')\n  const anyDeep = inside.some((node) => node.path.length > view.path.length + 1)\n  const colourCell = (node: TileNode) => {\n    const value = colorOf(node)\n    return value === null ? words.noValue : colorText(value)\n  }\n\n  /** What a press or Enter on a circle zooms to: a group itself, a leaf's group, or nothing in view already. */\n  const zoomFor = (node: TileNode | undefined) => {\n    if (!node) return null\n    const target =\n      node.children.length > 0 ? node : tileNodeAt(tree, node.path.slice(0, -1))\n    return target.key === view.key ? null : () => zoomTo(target.path)\n  }\n  const under = (point: PlotPoint) => packAt(point, layout, view, shown, NEAR_CIRCLE)\n\n  const reader = treeReader({\n    stops,\n    direction,\n    hit: (point) => {\n      const key = under(point)\n      const found = key === null ? -1 : stops.findIndex((stop) => stop.id === key)\n      return found === -1 ? null : { kind: 'stop', index: found }\n    },\n    openAt: (point) => {\n      const key = under(point)\n      return key === null ? null : zoomFor(nodes.get(key))\n    },\n    open: (stop) => zoomFor(nodes.get(stop.id)),\n    back: view.path.length > 0 ? () => zoomTo(view.path.slice(0, -1)) : null,\n    // The tooltip sits above the circle's top, as fractions of the plot.\n    anchor: (stop) => {\n      const circle = layout.byKey.get(stop.id)\n      if (!circle || !isMeasured(size)) return null\n      const centre = packPoint(circle, shown)\n      return {\n        x: centre.x / size.width,\n        y: (centre.y - circle.r * shown.k) / size.height,\n        side: 'top',\n      }\n    },\n    words: {\n      describe: (stop) => {\n        const node = nodes.get(stop.id)\n        const name = pickedName(stop.name, pick.picked === stop.id, words)\n        if (!node) return `${name}: `\n        const place = placeOf(node)\n        const value = `${label} ${valueOf(node)}, ${percent.format(shareOf(node))}`\n        const colour = colorKey ? `, ${colorName} ${colourCell(node)}` : ''\n        return `${name}: ${place ? `${place}, ` : ''}${value}${colour}`\n      },\n      table: {\n        header: words.category,\n        columns: [\n          ...(anyDeep ? [words.group] : []),\n          label,\n          words.share,\n          ...(colorKey ? [colorName] : []),\n        ],\n        // Only the leaves, so the rows add up to the footer's total: a group is the sum of its own.\n        rows: inside.flatMap((node, at) =>\n          node.children.length > 0\n            ? []\n            : [\n                {\n                  key: node.key,\n                  name: stops[at]?.name ?? '',\n                  cells: [\n                    ...(anyDeep ? [placeOf(node)] : []),\n                    valueOf(node),\n                    percent.format(shareOf(node)),\n                    ...(colorKey ? [colourCell(node)] : []),\n                  ],\n                },\n              ],\n        ),\n        footer: [\n          ...(anyDeep ? [''] : []),\n          valueText(viewTotal),\n          percent.format(viewTotal === 0 ? 0 : 1),\n          ...(colorKey ? [''] : []),\n        ],\n      },\n      tooltip: (stop) => {\n        const node = nodes.get(stop.id)\n        const circle = layout.byKey.get(stop.id)\n        if (!node || !circle) return null\n        const fill = fillOf(circle)\n        const place = placeOf(node)\n        const share = percent.format(shareOf(node))\n        return (\n          <ShareTooltipContent\n            chart={state}\n            category={treeItem(stop)}\n            name={place ? `${place} / ${stop.name}` : stop.name}\n            rows={\n              colorKey\n                ? [\n                    { label, value: valueOf(node), share },\n                    { label: colorName, value: colourCell(node), share: null },\n                  ]\n                : [{ label: null, value: valueOf(node), share }]\n            }\n            swatch={\n              <span\n                aria-hidden\n                className={cn(swatchClassName, forcedSeriesColor(fill.slot))}\n                style={{ '--swatch': fill.color } as CSSProperties}\n              />\n            }\n          />\n        )\n      },\n    },\n  })\n  const root: ChartRootValue = {\n    ...state,\n    status,\n    reader,\n    markerOf: () => null,\n    selectable: pick.selectable,\n    picked: pick.picked === null ? null : { kind: 'node', id: pick.picked },\n    togglePicked: (target) => {\n      if (target.kind === 'node' && reader.holds(target)) pick.toggle(target.id)\n    },\n  }\n  const { focusProps, toldRef } = useIndexFocus(reader.items, props)\n\n  // Where the layer was drawn when the view last changed, and the labels that came with that\n  // change, which start where their circles were then and ride the zoom in. Any other label\n  // that arrives, with new data or a group shown again, starts in its own place.\n  const viewSignature = `${view.key}#${shown.k}#${shown.x}#${shown.y}`\n  const labelKeys = view.children.map((child) => child.key).join('\\u0000')\n  const [held, setHeld] = useState({\n    signature: viewSignature,\n    view: view.key,\n    labelKeys,\n    now: shown,\n    was: shown,\n    fresh: new Set<string>(),\n    pending: false,\n  })\n  if (held.signature !== viewSignature) {\n    const zoomed = held.view !== view.key\n    setHeld({\n      signature: viewSignature,\n      view: view.key,\n      labelKeys,\n      now: shown,\n      was: held.now,\n      fresh: zoomed\n        ? new Set(view.children.map((child) => child.key))\n        : new Set<string>(),\n      pending: zoomed,\n    })\n  } else if (held.labelKeys !== labelKeys) {\n    setHeld({ ...held, labelKeys, fresh: new Set<string>(), pending: false })\n  }\n  // The zoom's labels wait one commit, before the frame paints, for where the layer is drawn\n  // now: part way through a zoom turned elsewhere, it isn't the view before.\n  useLayoutEffect(() => {\n    if (!held.pending) return\n    const drawn = drawnFrom(zoomRef.current)\n    // eslint-disable-next-line react-hooks/set-state-in-effect -- the layer's drawn place is known only once the zoom has committed\n    setHeld((now) => ({ ...now, pending: false, was: drawn ?? now.was }))\n  }, [held.pending])\n  // The labels that just arrived began their moves a commit after the layer: start them with it.\n  useLayoutEffect(() => {\n    if (!held.pending && held.fresh.size > 0)\n      alignMoves(zoomRef.current, labelsRef.current)\n  }, [held])\n\n  // The labels of the view's own circles, where they fit whole on screen.\n  const ownLabels: PackLabel[] = []\n  if (status === 'ready') {\n    for (const child of view.children) {\n      const circle = layout.byKey.get(child.key)\n      if (!circle || circle.r <= 0) continue\n      const name = nameOf(child)\n      const group = child.children.length > 0\n      const value = valueText(child.value)\n      const fit = circleLabelFit(\n        circle.r * shown.k,\n        // A group's name sits on a chip, 6px wider each side.\n        state.textWidth(name) + (group ? GROUP_CHIP : 0),\n        state.textWidth(value),\n        group && labels === 'value' ? 'name' : labels,\n      )\n      if (fit === 'none') continue\n      const fresh = held.fresh.has(child.key)\n      if (fresh && held.pending) continue\n      const at = packPoint(circle, shown)\n      const from = fresh ? packPoint(circle, held.was) : at\n      ownLabels.push({\n        key: child.key,\n        x: at.x,\n        y: at.y,\n        fromX: from.x,\n        fromY: from.y,\n        name,\n        value: fit === 'value' ? value : null,\n        group,\n        color: fillOf(circle).color,\n      })\n    }\n  }\n\n  const perValue = packScale(layout)\n  return (\n    <TreeZoomContext value={{ tree, view, zoomTo, nameOf }}>\n      <StepLegendContext\n        value={{\n          slot: 'circle-packing-chart',\n          label: colorName,\n          edges,\n          fillOf: (step) => ({\n            color: divergingFill(step, edges),\n            strength: divergingStep(step, edges).strength,\n          }),\n          valueText: colorText,\n          textWidth: state.textWidth,\n          emphasis: stepEmphasis,\n          setEmphasis: setStepEmphasis,\n        }}\n      >\n        <CirclePackingContext\n          value={{\n            perValue: perValue === null ? null : perValue * shown.k,\n            measured: isMeasured(size),\n            valueLabel: label,\n            valueText,\n          }}\n        >\n          <ChartFrame\n            root={root}\n            focus={focusProps}\n            ref={ref}\n            slot='circle-packing-chart'\n            description={description}\n            empty={empty}\n            measuring={false}\n            inset={0}\n            data-orientation='vertical'\n            className={className}\n            {...figureProps(props, circlePackingChartKeys)}\n          >\n            <IndexActive items={reader.items} active={props} toldRef={toldRef}>\n              <CirclePackingCircles\n                zoomRef={zoomRef}\n                labelsRef={labelsRef}\n                layout={layout}\n                circles={circles}\n                shown={shown}\n                stops={stops}\n                labels={ownLabels}\n                phase={phase}\n                fillOf={fillOf}\n                stepOfCircle={(circle) =>\n                  colorKey && circle.node.children.length === 0\n                    ? stepOf(colorOf(circle.node), edges)\n                    : null\n                }\n                stepEmphasis={colorKey ? stepEmphasis : null}\n              />\n              {props.children}\n              {load.placeholder && <CirclePackingPlaceholder />}\n            </IndexActive>\n          </ChartFrame>\n        </CirclePackingContext>\n      </StepLegendContext>\n    </TreeZoomContext>\n  )\n}\n\n/** The leaves of the tree, whose second value colours them. */\nfunction leavesOf(node: TileNode): TileNode[] {\n  return node.children.length === 0 ? [node] : node.children.flatMap(leavesOf)\n}\n\n/** A circle's radius for each square root of value in `layout`, from any leaf with a size; none with none. */\nfunction packScale(layout: PackLayout): number | null {\n  const leaf = layout.circles.find(\n    (circle) =>\n      circle.node.children.length === 0 && circle.r > 0 && circle.node.value > 0,\n  )\n  return leaf ? leaf.r / Math.sqrt(leaf.node.value) : null\n}\n\n/** A group's see-through tint of its colour, so a group inside another reads a step deeper. */\nfunction groupTint(color: string) {\n  return `color-mix(in oklab, ${color} 16%, transparent)`\n}\n\n/** A group's tint when the circles are coloured by a value of their own, which a group doesn't take. */\nconst NEUTRAL_TINT = 'color-mix(in oklab, var(--foreground) 7%, transparent)'\n\n/**\n * Which side of zero the step at `step` among `edges` lies on, and how\n * strong its colour is: the step next to zero the faintest on either side,\n * steps as far from zero as strong on both, and one side only when every\n * value has one sign.\n */\nfunction divergingStep(\n  step: number,\n  edges: readonly number[],\n): { side: 'below' | 'above'; strength: number } {\n  const steps = Math.max(0, edges.length - 1)\n  const below = edges.slice(1).filter((edge) => edge <= 0).length\n  const above = steps - below\n  const side = step < below ? 'below' : 'above'\n  const fromZero = side === 'below' ? below - 1 - step : step - below\n  return { side, strength: stepStrength(fromZero, Math.max(below, above)) }\n}\n\n/** The colour of a step of the ramp: its side's colour, as strong as the step, over the page's muted fill. */\nfunction divergingFill(step: number, edges: readonly number[]) {\n  const { side, strength } = divergingStep(step, edges)\n  const color =\n    side === 'below'\n      ? 'var(--circle-packing-chart-negative, var(--destructive))'\n      : 'var(--circle-packing-chart-positive, var(--chart-2))'\n  return `color-mix(in oklab, ${color} ${Math.round(strength * 100)}%, var(--muted))`\n}\n\n/** Orders by key, the path joined, so a parent comes before what is inside it. */\nfunction byKey(a: { key: string }, b: { key: string }) {\n  return a.key < b.key ? -1 : a.key > b.key ? 1 : 0\n}\n\n/** The zoom's move on `layer`, if one is running. */\nfunction zoomMove(layer: HTMLElement | null) {\n  return layer\n    ?.getAnimations()\n    .find(\n      (animation) =>\n        animation instanceof CSSTransition &&\n        animation.transitionProperty === 'transform',\n    )\n}\n\n/**\n * Starts every label's move in `labels` when the layer's zoom started, on\n * the same duration and easing, so each label stays on its circle the\n * whole way.\n */\nfunction alignMoves(layer: HTMLElement | null, labels: HTMLElement | null) {\n  const zoom = zoomMove(layer)\n  if (!zoom || !labels || zoom.startTime === null) return\n  for (const move of labels.getAnimations({ subtree: true })) {\n    if (move instanceof CSSTransition && move.transitionProperty === 'translate') {\n      move.startTime = zoom.startTime\n    }\n  }\n}\n\n/**\n * Where the layer's zoom starts from, as drawn: the first frame of the move\n * the browser has just begun, from wherever the last one had reached, or\n * none with no move, as under reduced motion.\n */\nfunction drawnFrom(layer: HTMLElement | null): PackView | null {\n  const move = zoomMove(layer)\n  const first =\n    move?.effect instanceof KeyframeEffect ? move.effect.getKeyframes()[0] : undefined\n  if (typeof first?.transform !== 'string') return null\n  const { a, e, f } = new DOMMatrixReadOnly(first.transform)\n  return { k: a, x: e, y: f }\n}\n\n/**\n * The circles: one layer as large as the plot, cut to its round window,\n * moved and scaled as one to show the part in view, stepping back as one\n * while a circle or a group is lit, with what is lit shown bright above\n * it; and the labels of the view's circles above them, each riding its\n * circle.\n */\nfunction CirclePackingCircles({\n  zoomRef,\n  labelsRef,\n  layout,\n  circles,\n  shown,\n  stops,\n  labels,\n  phase,\n  fillOf,\n  stepOfCircle,\n  stepEmphasis,\n}: {\n  zoomRef: RefObject<HTMLDivElement | null>\n  labelsRef: RefObject<HTMLDivElement | null>\n  layout: PackLayout\n  circles: readonly PackedCircle[]\n  shown: PackView\n  stops: readonly TreeStop[]\n  labels: readonly PackLabel[]\n  phase: EntrancePhase\n  fillOf: (circle: PackedCircle) => CircleFill\n  stepOfCircle: (circle: PackedCircle) => number | null\n  stepEmphasis: number | null\n}) {\n  const chart = useChartRootValue()\n  const { spotlit } = useChartActive()\n  const leaving = useLeaving(chart.moves, circles, circleKey)\n  const leavingLabels = useLeaving(chart.moves, labels, labelKey)\n  // Lit: the circle under the pointer or the keys with what is inside it, or a group the\n  // legend brings forward, or the circles of a colour's step.\n  const litKey = spotlit === null ? null : (stops[spotlit]?.id ?? null)\n  const litCircle = litKey === null ? null : layout.byKey.get(litKey)\n  const lit = circles.filter((circle) =>\n    litCircle\n      ? circle.key === litCircle.key || startsWith(circle.node.path, litCircle.node.path)\n      : chart.emphasis !== null\n        ? circle.top === chart.emphasis\n        : stepEmphasis !== null && stepOfCircle(circle) === stepEmphasis,\n  )\n  const litSignature = lit.map(circleKey).join('\\u0000')\n  const [heldLit, setHeldLit] = useState({ signature: '', circles: lit })\n  if (lit.length > 0 && heldLit.signature !== litSignature) {\n    setHeldLit({ signature: litSignature, circles: lit })\n  }\n  const showLit = lit.length > 0 ? lit : heldLit.circles\n  if (chart.status === 'empty' || !isMeasured(chart.plotSize)) return null\n  const { window } = layout\n  const clip = `circle(${window.r}px at ${window.x}px ${window.y}px)`\n  const view = `translate(${shown.x}px, ${shown.y}px) scale(${shown.k})`\n  const waiting = phase === 'waiting'\n  const entering = phase === 'entering'\n  const litKeys = new Set(lit.map(circleKey))\n  // Drawn in the tree's order, a parent before what is inside it, whatever the values: a\n  // circle React moved in the page would lose its move and grow in again from nothing.\n  const drawn = [\n    ...circles.map((circle) => ({ circle, gone: false })),\n    ...leaving.map((circle) => ({ circle, gone: true })),\n  ].toSorted((a, b) => byKey(a.circle, b.circle))\n  return (\n    <>\n      <div\n        data-slot='circle-packing-chart-circles'\n        aria-hidden\n        // The clip-path cuts the zoomed layer to its window, but only `overflow-clip` keeps what\n        // it cuts from widening every scroller above the chart.\n        className={cn(plotLayerClassName, 'z-10 overflow-clip')}\n        style={{ clipPath: clip }}\n      >\n        {/* The view on the layer's own transform, never a variable its thousand circles inherit\n            and restyle with on every zoom. */}\n        <div\n          ref={zoomRef}\n          className='absolute inset-0 origin-top-left transition-none group-data-mounted/chart:transition-[transform] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:group-data-mounted/chart:transition-none'\n          style={{ transform: view }}\n        >\n          <div\n            data-dim={lit.length > 0 ? '' : undefined}\n            className={cn('absolute inset-0', stepBackLayerClassName)}\n          >\n            {drawn.map(({ circle, gone }) => (\n              <PackCircle\n                key={circle.key}\n                x={circle.x}\n                y={circle.y}\n                scale={(circle.r * 2) / DISC}\n                {...fillOf(circle)}\n                leaving={gone}\n                waiting={!gone && waiting}\n                entering={!gone && entering}\n              />\n            ))}\n          </div>\n          <div\n            data-slot='circle-packing-chart-lit'\n            data-off={lit.length === 0 ? '' : undefined}\n            className='absolute inset-0 transition-opacity duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing) data-off:opacity-0'\n          >\n            {showLit.toSorted(byKey).map((circle) => {\n              const now = layout.byKey.get(circle.key) ?? circle\n              return (\n                <PackCircle\n                  key={circle.key}\n                  x={now.x}\n                  y={now.y}\n                  scale={(now.r * 2) / DISC}\n                  {...fillOf(now)}\n                  leaving={false}\n                  waiting={false}\n                  entering={false}\n                  still\n                />\n              )\n            })}\n          </div>\n        </div>\n      </div>\n      <div\n        ref={labelsRef}\n        data-slot='circle-packing-chart-labels'\n        aria-hidden\n        className={cn(plotLayerClassName, 'z-10 overflow-clip')}\n        style={{ clipPath: clip }}\n      >\n        {[...labels, ...leavingLabels].toSorted(byKey).map((one) => {\n          const gone = !labels.includes(one)\n          // A label that leaves rides its circle to where the new view draws it.\n          const circle = layout.byKey.get(one.key)\n          const at = gone && circle ? packPoint(circle, shown) : one\n          return (\n            <PackLabelMark\n              key={one.key}\n              at={`${at.x}px ${at.y}px`}\n              from={`${one.fromX}px ${one.fromY}px`}\n              name={one.name}\n              value={one.value}\n              group={one.group}\n              color={one.color}\n              off={gone || waiting}\n              quiet={litKeys.size > 0 && !litKeys.has(one.key)}\n            />\n          )\n        })}\n      </div>\n    </>\n  )\n}\n\nfunction circleKey(circle: PackedCircle) {\n  return circle.key\n}\n\nfunction labelKey(label: PackLabel) {\n  return label.key\n}\n\n/**\n * One circle: a point placed at `x` and `y` px, holding a disc scaled to its\n * size, so a move and a new size are each one transform that turns back\n * from wherever it is. It grows in from its centre and shrinks into it as\n * it leaves; a `still` one, a lit circle's copy, appears in place and moves with its circle.\n * Memoised, so lighting a circle redraws none of them.\n */\nconst PackCircle = memo(function PackCircle({\n  x,\n  y,\n  scale,\n  color,\n  slot,\n  group,\n  forced,\n  leaving,\n  waiting,\n  entering,\n  still = false,\n}: CircleFill & {\n  x: number\n  y: number\n  /** The disc's scale: its size across over `DISC`. */\n  scale: number\n  leaving: boolean\n  /** Before the entrance, out of sight at its centre. */\n  waiting: boolean\n  entering: boolean\n  still?: boolean\n}) {\n  return (\n    <span\n      data-slot='circle-packing-chart-circle'\n      data-group={group ? '' : undefined}\n      data-leaving={leaving ? '' : undefined}\n      data-waiting={waiting ? '' : undefined}\n      data-entering={entering ? '' : undefined}\n      data-still={still ? '' : undefined}\n      className='group/circle absolute top-0 left-0 size-0 [translate:var(--circle-at)] transition-none group-data-mounted/chart:transition-[translate,opacity] duration-(--motion-layout-duration) ease-[var(--motion-layout-easing),var(--motion-layout-fade-easing)] group-data-mounted/chart:not-data-still:starting:opacity-0 data-waiting:opacity-0 data-entering:duration-(--motion-draw-duration) data-entering:ease-[var(--motion-draw-easing),var(--motion-draw-fade-easing)] data-leaving:opacity-0 data-leaving:duration-(--motion-exit-duration) data-leaving:ease-[var(--motion-exit-easing),var(--motion-exit-fade-easing)] motion-reduce:group-data-mounted/chart:transition-[opacity] motion-reduce:ease-(--motion-layout-fade-easing) motion-reduce:data-entering:ease-(--motion-draw-fade-easing) motion-reduce:data-leaving:ease-(--motion-exit-fade-easing)'\n      style={{ '--circle-at': `${x}px ${y}px` } as CSSProperties}\n    >\n      <span\n        className={cn(\n          // A disc `DISC` px across, centred on the point.\n          'absolute -top-[50px] -left-[50px] size-[100px] rounded-full bg-(--circle-fill) [transform:scale(var(--circle-scale))] transition-none group-data-mounted/chart:transition-[background-color,transform] duration-(--motion-layout-duration) ease-[var(--motion-layout-fade-easing),var(--motion-layout-easing)] group-data-mounted/chart:not-group-data-still/circle:starting:[transform:scale(0)] group-data-waiting/circle:[transform:scale(0)] group-data-leaving/circle:[transform:scale(0)] group-data-entering/circle:duration-(--motion-draw-duration) group-data-entering/circle:ease-[var(--motion-draw-fade-easing),var(--motion-draw-easing)] group-data-leaving/circle:duration-(--motion-exit-duration) group-data-leaving/circle:ease-[var(--motion-exit-fade-easing),var(--motion-exit-easing)] motion-reduce:group-data-mounted/chart:transition-[background-color] motion-reduce:ease-(--motion-layout-fade-easing) motion-reduce:group-data-mounted/chart:starting:[transform:scale(var(--circle-scale))] motion-reduce:group-data-waiting/circle:[transform:scale(var(--circle-scale))] motion-reduce:group-data-leaving/circle:[transform:scale(var(--circle-scale))]',\n          // In forced colours, a group is a faint wash of the page's grey, its circles each a system\n          // colour, or the text's colour at the strength of their step, as the colour key draws it.\n          forced === 'faint'\n            ? 'forced-colors:bg-[GrayText] forced-colors:opacity-30'\n            : forced === 'series'\n              ? forcedSeriesColor(slot)\n              : 'forced-colors:bg-[CanvasText] forced-colors:opacity-(--circle-strength)',\n        )}\n        style={\n          {\n            '--circle-fill': color,\n            '--circle-strength': typeof forced === 'number' ? forced : undefined,\n            '--circle-scale': scale,\n          } as CSSProperties\n        }\n      />\n    </span>\n  )\n})\n\n/**\n * A label of a circle in view, centred on it: a circle's name and value in\n * near white or near black for its colour, or a group's name in the text\n * colour on a chip of the page's colour, since it sits over the circles\n * inside.\n * It rides its circle while the view zooms, on the same move as the layer,\n * so it stays on it, and fades in and out where it comes and goes.\n */\nconst PackLabelMark = memo(function PackLabelMark({\n  at,\n  from,\n  name,\n  value,\n  group,\n  color,\n  off,\n  quiet,\n}: {\n  at: string\n  from: string\n  name: string\n  value: string | null\n  group: boolean\n  color: string\n  off: boolean\n  quiet: boolean\n}) {\n  return (\n    <span\n      className='absolute top-0 left-0 size-0 [translate:var(--label-at)] transition-none duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-mounted/chart:transition-[translate] group-data-mounted/chart:starting:[translate:var(--label-from)] motion-reduce:group-data-mounted/chart:transition-none'\n      style={{ '--label-at': at, '--label-from': from } as CSSProperties}\n    >\n      <span\n        data-off={off ? '' : undefined}\n        data-quiet={quiet ? '' : undefined}\n        className={cn(\n          'absolute top-0 left-0 flex -translate-1/2 flex-col items-center text-center leading-4 whitespace-nowrap transition-[opacity,color] duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing) group-data-mounted/chart:starting:opacity-0 data-off:opacity-0',\n          group\n            ? 'text-foreground data-quiet:text-muted-foreground bg-background/90 rounded-(--control-radius-xs) px-1.5 py-0.5 shadow-xs ring-1 ring-foreground/5 forced-colors:bg-[Canvas] forced-colors:text-[CanvasText] forced-colors:ring-[CanvasText]'\n            : labelOnClassName,\n        )}\n        style={group ? undefined : ({ '--label-on': color } as CSSProperties)}\n      >\n        {/* A name or value with a unit reads in its own order whatever the page's direction. */}\n        <span dir='auto' className='font-medium'>\n          {name}\n        </span>\n        {value !== null && (\n          <span dir='auto' className='tabular-nums'>\n            {value}\n          </span>\n        )}\n      </span>\n    </span>\n  )\n})\n\n/** The circles in the placeholder's tint, breathing slowly, while the data loads. */\nfunction CirclePackingPlaceholder() {\n  const chart = useChartRootValue()\n  if (!isMeasured(chart.plotSize)) return null\n  const layout = packLayout(PLACEHOLDER_TREE, {\n    width: chart.plotSize.width,\n    height: chart.plotSize.height,\n    padding: PADDING,\n    direction: chart.direction,\n  })\n  return (\n    <div\n      data-slot='circle-packing-chart-placeholder'\n      aria-hidden\n      className={cn(plotLayerClassName, 'z-10', placeholderBreatheClassName)}\n    >\n      {layout.circles.map((circle) => (\n        <span\n          key={circle.key}\n          className={cn('absolute rounded-full', placeholderFillClassName)}\n          style={{\n            left: circle.x - circle.r,\n            top: circle.y - circle.r,\n            width: circle.r * 2,\n            height: circle.r * 2,\n          }}\n        />\n      ))}\n    </div>\n  )\n}\n\n/** The shape the placeholder's circles take: a few of falling size, as most packings have. */\nconst PLACEHOLDER_TREE = tileTree(\n  [34, 22, 16, 11, 8, 5, 4].map((value, at) => ({ name: String(at), value })),\n  'name',\n  'value',\n)\n\n/**\n * The way back out: Kino's Breadcrumb of the parts above the one in view,\n * the whole first, each a button that zooms out to it, and the part in view\n * last. It sits above the plot, under a legend at the top.\n */\nfunction CirclePackingPath(props: ComponentProps<'nav'>) {\n  return <TreeZoomPath slot='circle-packing-chart-path' {...props} />\n}\n\n/**\n * The legend: a key of three nested circles with the values their sizes\n * stand for in the part in view, and with `colorKey`, the colour's steps,\n * whose values are written at their edges. Pointing at a step brings its\n * circles forward. It sits under or over the plot; the groups' colours are\n * `ChartLegend`'s.\n */\nfunction CirclePackingLegend({\n  position = 'bottom',\n  className,\n  ...props\n}: Omit<ComponentProps<'div'>, 'children'> & { position?: 'top' | 'bottom' }) {\n  const chart = useChartRootValue()\n  const packing = useCirclePacking()\n  if (chart.status !== 'ready') return null\n  return (\n    <div\n      data-slot='circle-packing-chart-legend'\n      className={cn(\n        'flex flex-wrap items-end justify-end gap-x-6 gap-y-2',\n        position === 'top' ? 'pb-3 [grid-area:top]' : 'pt-3 [grid-area:bottom]',\n        className,\n      )}\n      {...props}\n    >\n      {(packing.perValue !== null || !packing.measured) && (\n        <SizeKey\n          perValue={packing.perValue ?? 0}\n          label={packing.valueLabel}\n          valueText={packing.valueText}\n        />\n      )}\n      <CellStepLegend\n        data-slot='circle-packing-chart-steps'\n        className='p-0 [grid-area:auto]'\n      />\n    </div>\n  )\n}\n\n/**\n * Three circles nested on one base, the largest about `KEY_RADIUS` px\n * across its radius, each with the value it stands for at its top.\n */\nfunction SizeKey({\n  perValue,\n  label,\n  valueText,\n}: {\n  perValue: number\n  label: string\n  valueText: (value: number) => string\n}) {\n  const values = sizeKey(perValue, KEY_RADIUS)\n  // Values the format writes the same, such as two that round to 0, say nothing more.\n  const written = values\n    .map((value) => ({\n      value,\n      text: valueText(value),\n      r: Math.sqrt(value) * perValue,\n    }))\n    .filter((one, at, all) => all.findIndex((other) => other.text === one.text) === at)\n  // The key's box never follows its circles, which follow the plot's size: a box that did\n  // would resize the plot beside it, and the plot the key again, every frame.\n  const height = KEY_RADIUS * 2\n  return (\n    <div data-slot='circle-packing-chart-size-key' className='flex items-end gap-3'>\n      <span className='text-muted-foreground font-medium'>{label}</span>\n      <div aria-hidden className='flex' style={{ height }}>\n        <svg\n          width={height + 8}\n          height={height}\n          className='shrink-0 overflow-visible rtl:-scale-x-100'\n        >\n          {written.map((one) => (\n            <g key={one.value}>\n              <circle\n                cx={KEY_RADIUS}\n                cy={height - one.r}\n                r={one.r}\n                className='stroke-muted-foreground/60 fill-none forced-colors:stroke-[CanvasText]'\n              />\n              {/* From the circle's top to its value, beside the largest. */}\n              <line\n                x1={KEY_RADIUS}\n                x2={height + 8}\n                y1={height - one.r * 2}\n                y2={height - one.r * 2}\n                strokeDasharray='2 2'\n                className='stroke-muted-foreground/60 forced-colors:stroke-[CanvasText]'\n              />\n            </g>\n          ))}\n        </svg>\n        <span className='relative'>\n          {written.map((one) => (\n            <span\n              key={one.value}\n              className='text-muted-foreground absolute start-1 -translate-y-1/2 leading-4 whitespace-nowrap tabular-nums'\n              style={{ top: height - one.r * 2 }}\n            >\n              <SwapText text={one.text} />\n            </span>\n          ))}\n          {/* As wide as the widest value, so the key's width follows what it writes. */}\n          <span className='invisible ps-1 leading-4 whitespace-nowrap tabular-nums'>\n            {written.reduce(\n              (wide, one) => (one.text.length > wide.length ? one.text : wide),\n              '',\n            )}\n          </span>\n        </span>\n      </div>\n      <ul aria-label={label} className='sr-only'>\n        {written.map((one) => (\n          <li key={one.value}>{one.text}</li>\n        ))}\n      </ul>\n    </div>\n  )\n}\n\n/** The steps the size key's values round down to, within each power of ten. */\nconst KEY_STEPS = [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8]\n\n/** The roundest value at or below `value`: 1, 1.5, 2, 2.5, 3, 4, 5, 6 or 8 times a power of ten. */\nfunction roundBelow(value: number): number {\n  if (!(value > 0) || !Number.isFinite(value)) return 0\n  const power = 10 ** Math.floor(Math.log10(value))\n  const step = KEY_STEPS.findLast((one) => one * power <= value * (1 + 1e-9)) ?? 1\n  // Rounded, since a power of ten below 1 isn't exact: 3 × 0.1 is 0.30000000000000004.\n  return Number((step * power).toPrecision(12))\n}\n\n/**\n * The size key's values, largest first, for circles `perValue` px across\n * their radius for each square root of value: the roundest value whose\n * circle is at most `largest` px across its radius, then about a quarter\n * and a twenty-fifth of it, half and a fifth as wide.\n */\nfunction sizeKey(perValue: number, largest: number): number[] {\n  if (!(perValue > 0)) return []\n  const top = roundBelow((largest / perValue) ** 2)\n  return [top, roundBelow(top / 4), roundBelow(top / 25)].filter((value) => value > 0)\n}\n\nexport {\n  CirclePackingChart,\n  type CirclePackingChartProps,\n  CirclePackingLegend,\n  CirclePackingPath,\n  divergingStep,\n  roundBelow,\n  sizeKey,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/circle-packing-chart.tsx"
    }
  ],
  "type": "registry:component"
}