{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "circle-pack",
  "type": "registry:component",
  "title": "Circle Pack",
  "description": "A hierarchy as circles inside circles: each group an outline holding its parts, each part a circle whose area is its size, with zooming into a group by click or Enter and back out by the trail or Backspace.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-hierarchy"
  ],
  "devDependencies": [
    "@types/d3-hierarchy"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/viz/circle-pack.tsx",
      "type": "registry:component",
      "target": "components/viz/circle-pack.tsx",
      "content": "\"use client\";\n/**\n * @name circle-pack\n * @category viz\n * @description A hierarchy as circles inside circles: each group an outline holding its parts, each part a circle whose area is its size, with zooming into a group by click or Enter and back out by the trail or Backspace.\n * @when Showing groups and their members when the grouping matters more than precise sizes: topics and their articles, teams and their projects. To compare sizes closely use treemap or bar-chart; for levels as rings use sunburst.\n * @example\n * <CirclePack\n *   label=\"Articles by topic\"\n *   data={{\n *     name: \"All articles\",\n *     children: [\n *       { name: \"Science\", children: [{ name: \"Space\", value: 40 }, { name: \"Biology\", value: 25 }] },\n *       { name: \"Arts\", children: [{ name: \"Film\", value: 30 }, { name: \"Music\", value: 18 }] },\n *     ],\n *   }}\n * />\n */\nimport { hierarchy, pack, type HierarchyNode } from \"d3-hierarchy\";\nimport { useMemo, type KeyboardEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\nimport {\n  ChartContainer,\n  ChartEmpty,\n  chartSeries,\n  ChartSvg,\n  ChartTooltip,\n  ChartTrail,\n  chartTreeFind,\n  chartTreeRows,\n  chartTreeTotal,\n  fitText,\n  formatNumber,\n  useChartCursor,\n  type ChartBaseProps,\n  type ChartTreeNode,\n} from \"@/components/viz/chart\";\n\nexport type CirclePackLabels = { trail: string; part: string; value: string; share: string; canOpen: string };\n\nexport type CirclePackProps = Omit<ChartBaseProps, \"defaultValue\"> & {\n  /** The tree. Leaves carry a `value`; a branch is the sum of its children. */\n  data: ChartTreeNode;\n  /** The names from the root to the group in view. Controlled with `onPathChange`. */\n  path?: readonly string[];\n  defaultPath?: readonly string[];\n  onPathChange?: (path: readonly string[]) => void;\n  labels?: Partial<CirclePackLabels>;\n};\n\nconst LABELS: CirclePackLabels = { trail: \"Level\", part: \"Part\", value: \"Value\", share: \"Share\", canOpen: \"press Enter to open\" };\nconst EMPTY: readonly string[] = [];\n\ntype Node = HierarchyNode<ChartTreeNode>;\n\nexport function CirclePack({\n  data,\n  path: pathProp,\n  defaultPath = EMPTY,\n  onPathChange,\n  labels: given,\n  label,\n  aspect = 1,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: CirclePackProps) {\n  const labels = { ...LABELS, ...given };\n  const [path, setPath] = useControllableState<readonly string[]>({ value: pathProp, defaultValue: defaultPath, onChange: onPathChange });\n  const focus = useMemo(() => chartTreeFind(data, path), [data, path]);\n  const total = chartTreeTotal(focus.node);\n  const whole = chartTreeTotal(data) || 1;\n  const number = formatValue ?? ((value: number) => formatNumber(value, locale));\n  const percent = (share: number): string => formatNumber(share, locale, { style: \"percent\", maximumFractionDigits: 1 });\n  const topIndex = (name: string): number => data.children?.findIndex((child) => child.name === name) ?? 0;\n  const root = useMemo(\n    () =>\n      hierarchy<ChartTreeNode>(focus.node, (node) => node.children as ChartTreeNode[] | undefined)\n        .sum((node) => (node.children && node.children.length > 0 ? 0 : Math.max(0, node.value ?? 0)))\n        .sort((a, b) => (b.value ?? 0) - (a.value ?? 0)),\n    [focus.node],\n  );\n  const rootLeaves = useMemo(() => root.leaves(), [root]);\n  const cursor = useChartCursor(rootLeaves.length);\n  const colourOf = (node: Node): number => {\n    const top = focus.path[0] ?? node.ancestors().find((a) => a.depth === 1)?.data.name ?? node.data.name;\n    const index = topIndex(top);\n    return index >= 0 && index < 5 ? index : -1;\n  };\n  const trailOf = (node: Node): string[] =>\n    node\n      .ancestors()\n      .reverse()\n      .slice(1)\n      .map((a) => a.data.name);\n  const groupOf = (node: Node): Node | undefined => node.ancestors().find((a) => a.depth === 1 && a !== node);\n  const open = (node: Node): void => {\n    const group = groupOf(node);\n    if (!group) return;\n    setPath([...focus.path, group.data.name]);\n    cursor.select(null);\n  };\n  const describe = (node: Node): string => `${trailOf(node).join(\" / \")}: ${number(node.value ?? 0)}, ${percent((node.value ?? 0) / whole)}${groupOf(node) ? `, ${labels.canOpen}` : \"\"}`;\n  const reading = cursor.active === null ? undefined : rootLeaves[cursor.active];\n  const table = { caption: label, columns: [labels.part, labels.value, labels.share], rows: chartTreeRows(data, number, percent) };\n\n  return (\n    <div data-slot=\"circle-pack\" className={cn(\"flex w-full min-w-0 flex-col gap-2\", className)} {...props}>\n      <ChartTrail aria-label={labels.trail} trail={[data.name, ...focus.path]} onNavigate={(depth) => setPath(focus.path.slice(0, depth))} />\n      <ChartContainer aspect={aspect} height={height} table={table} announcement={cursor.keyboard && reading ? describe(reading) : \"\"}>\n        {({ width, height: plotHeight }) => {\n          if (total <= 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const laid = pack<ChartTreeNode>()\n            .size([width, plotHeight])\n            .padding((node) => (node.depth === 0 ? 4 : 3))(root.copy());\n          const leaves = laid.leaves();\n          const groups = laid.descendants().filter((node) => node.depth > 0 && node.children);\n          const current = cursor.active === null ? undefined : leaves[cursor.active];\n          const onKeyDown = (event: KeyboardEvent<SVGSVGElement>): void => {\n            if ((event.key === \"Enter\" || event.key === \" \") && current) {\n              event.preventDefault();\n              open(current);\n            } else if (event.key === \"Backspace\" && focus.path.length > 0) {\n              event.preventDefault();\n              setPath(focus.path.slice(0, -1));\n              cursor.select(null);\n            } else cursor.svgProps.onKeyDown(event);\n          };\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps} onKeyDown={onKeyDown}>\n                <g aria-hidden=\"true\">\n                  {groups.map((group, index) => (\n                    <circle\n                      key={`g${index}`}\n                      cx={group.x}\n                      cy={group.y}\n                      r={group.r}\n                      className={cn(chartSeries(colourOf(group)).stroke, \"fill-none cursor-pointer\")}\n                      strokeOpacity={0.7}\n                      strokeWidth={1.5}\n                      onClick={() => open(group.leaves()[0] ?? group)}\n                    />\n                  ))}\n                  {leaves.map((node, index) => (\n                    <g\n                      key={index}\n                      className={cn(\"cursor-pointer transition-opacity duration-instant motion-reduce:transition-none\", cursor.active !== null && cursor.active !== index && \"opacity-50\")}\n                      onPointerEnter={() => cursor.point(index)}\n                      onClick={() => open(node)}\n                    >\n                      <circle cx={node.x} cy={node.y} r={node.r} className={chartSeries(colourOf(node)).fill} fillOpacity={0.3} />\n                      {node.r > 22 ? (\n                        <text x={node.x} y={node.y} dy=\"0.32em\" textAnchor=\"middle\" className=\"pointer-events-none fill-foreground text-xs\">\n                          {fitText(node.data.name, node.r * 1.7)}\n                        </text>\n                      ) : null}\n                    </g>\n                  ))}\n                  {groups.map((group, index) =>\n                    group.r > 40 ? (\n                      <text key={`t${index}`} x={group.x} y={group.y - group.r + 14} textAnchor=\"middle\" className=\"pointer-events-none fill-muted-foreground text-xs font-medium\">\n                        {fitText(group.data.name, group.r * 1.4)}\n                      </text>\n                    ) : null,\n                  )}\n                  {current ? <circle cx={current.x} cy={current.y} r={current.r + 1} fill=\"none\" className=\"pointer-events-none stroke-foreground\" strokeWidth={2} /> : null}\n                </g>\n              </ChartSvg>\n              {current ? (\n                <ChartTooltip\n                  x={current.x}\n                  y={current.y}\n                  side={current.x > width / 2 ? \"left\" : \"right\"}\n                  title={trailOf(current).slice(0, -1).join(\" / \") || undefined}\n                  rows={[{ label: current.data.name, value: `${number(current.value ?? 0)} · ${percent((current.value ?? 0) / whole)}`, index: colourOf(current), mark: \"rect\" }]}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Showing groups and their members when the grouping matters more than precise sizes: topics and their articles, teams and their projects. To compare sizes closely use treemap or bar-chart; for levels as rings use sunburst.",
    "example": "<CirclePack\n  label=\"Articles by topic\"\n  data={{\n    name: \"All articles\",\n    children: [\n      { name: \"Science\", children: [{ name: \"Space\", value: 40 }, { name: \"Biology\", value: 25 }] },\n      { name: \"Arts\", children: [{ name: \"Film\", value: 30 }, { name: \"Music\", value: 18 }] },\n    ],\n  }}\n/>",
    "client": true
  }
}
