{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sunburst",
  "type": "registry:component",
  "title": "Sunburst",
  "description": "A hierarchy as rings around a centre: each ring a level, each arc a part sized by its share of its parent, with zooming into any arc by click or Enter and back out by the centre, the trail or Backspace.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-hierarchy",
    "d3-shape"
  ],
  "devDependencies": [
    "@types/d3-hierarchy",
    "@types/d3-shape"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/viz/sunburst.tsx",
      "type": "registry:component",
      "target": "components/viz/sunburst.tsx",
      "content": "\"use client\";\n/**\n * @name sunburst\n * @category viz\n * @description A hierarchy as rings around a centre: each ring a level, each arc a part sized by its share of its parent, with zooming into any arc by click or Enter and back out by the centre, the trail or Backspace.\n * @when Showing how a total divides level by level when the depth matters as much as the sizes: a path through categories, a file system, a budget in three levels. For sizes that must be compared closely use treemap (areas in rectangles are easier to judge than arcs); for one level use donut-chart.\n * @example\n * <Sunburst\n *   label=\"Visits by source\"\n *   data={{\n *     name: \"All visits\",\n *     children: [\n *       { name: \"Search\", children: [{ name: \"Organic\", value: 420 }, { name: \"Paid\", value: 160 }] },\n *       { name: \"Social\", children: [{ name: \"Video\", value: 120 }, { name: \"Posts\", value: 80 }] },\n *       { name: \"Direct\", value: 300 },\n *     ],\n *   }}\n * />\n */\nimport { hierarchy, partition, type HierarchyRectangularNode } from \"d3-hierarchy\";\nimport { arc } from \"d3-shape\";\nimport { useMemo, type KeyboardEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\nimport {\n  ChartContainer,\n  ChartEmpty,\n  ChartLegend,\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 SunburstLabels = { trail: string; part: string; value: string; share: string; canOpen: string; up: string };\n\nexport type SunburstProps = Omit<ChartBaseProps, \"defaultValue\"> & {\n  /** The tree. Leaves carry a `value`; a branch is the sum of its children. */\n  data: ChartTreeNode;\n  /** How many rings are drawn below the part in view. Default 3. */\n  depth?: number;\n  /** The names from the root to the part in view. Controlled with `onPathChange`. */\n  path?: readonly string[];\n  defaultPath?: readonly string[];\n  onPathChange?: (path: readonly string[]) => void;\n  /** The legend of the top-level groups. Default true. */\n  showLegend?: boolean;\n  labels?: Partial<SunburstLabels>;\n};\n\nconst LABELS: SunburstLabels = { trail: \"Level\", part: \"Part\", value: \"Value\", share: \"Share\", canOpen: \"press Enter to open\", up: \"Back one level\" };\nconst EMPTY: readonly string[] = [];\n/** Deeper rings step back so the levels read apart: the colour stays the group's. */\nconst RING_OPACITY = [1, 0.72, 0.5, 0.36];\n\ntype Node = HierarchyRectangularNode<ChartTreeNode>;\n\nexport function Sunburst({\n  data,\n  depth: rings = 3,\n  path: pathProp,\n  defaultPath = EMPTY,\n  onPathChange,\n  showLegend = true,\n  labels: given,\n  label,\n  aspect = 1,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: SunburstProps) {\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\n  const nodes = useMemo(() => {\n    const root = 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    const laid = partition<ChartTreeNode>().size([2 * Math.PI, rings + 1])(root);\n    return laid.descendants().filter((node) => node.depth > 0 && node.depth <= rings && node.x1 - node.x0 > 0.001);\n  }, [focus.node, rings]);\n  const cursor = useChartCursor(nodes.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 openable = (node: Node): boolean => Boolean(node.children && node.children.length > 0);\n  const open = (node: Node): void => {\n    if (!openable(node)) return;\n    setPath([...focus.path, ...trailOf(node)]);\n    cursor.select(null);\n  };\n  const up = (): void => {\n    if (focus.path.length === 0) return;\n    setPath(focus.path.slice(0, -1));\n    cursor.select(null);\n  };\n  const current = cursor.active === null ? undefined : nodes[cursor.active];\n  const describe = (node: Node): string => `${trailOf(node).join(\" / \")}: ${number(node.value ?? 0)}, ${percent((node.value ?? 0) / whole)}${openable(node) ? `, ${labels.canOpen}` : \"\"}`;\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      up();\n    } else cursor.svgProps.onKeyDown(event);\n  };\n  const table = { caption: label, columns: [labels.part, labels.value, labels.share], rows: chartTreeRows(data, number, percent) };\n\n  return (\n    <div data-slot=\"sunburst\" 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 && current ? describe(current) : \"\"}>\n        {({ width, height: plotHeight }) => {\n          if (total <= 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const radius = Math.min(width, plotHeight) / 2 - 2;\n          const ring = radius / (rings + 1);\n          const shape = arc<Node>()\n            .startAngle((node) => node.x0)\n            .endAngle((node) => node.x1)\n            .innerRadius((node) => node.y0 * ring)\n            .outerRadius((node) => node.y1 * ring - 1)\n            .padAngle(0.006)\n            .padRadius(radius / 2)\n            .cornerRadius(2);\n          const cx = width / 2;\n          const cy = plotHeight / 2;\n          const at = (node: Node): [number, number] => {\n            const angle = (node.x0 + node.x1) / 2 - Math.PI / 2;\n            const r = ((node.y0 + node.y1) / 2) * ring;\n            return [cx + Math.cos(angle) * r, cy + Math.sin(angle) * r];\n          };\n          const shownAt = current ? at(current) : undefined;\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps} onKeyDown={onKeyDown}>\n                <g transform={`translate(${cx},${cy})`} aria-hidden=\"true\">\n                  {nodes.map((node, index) => (\n                    <path\n                      key={index}\n                      d={shape(node) ?? \"\"}\n                      className={cn(chartSeries(colourOf(node)).fill, openable(node) && \"cursor-pointer\", \"transition-opacity duration-instant motion-reduce:transition-none\")}\n                      fillOpacity={(RING_OPACITY[node.depth - 1] ?? 0.3) * (cursor.active !== null && cursor.active !== index ? 0.5 : 1)}\n                      onPointerEnter={() => cursor.point(index)}\n                      onClick={() => open(node)}\n                    />\n                  ))}\n                  {current ? <path d={shape(current) ?? \"\"} fill=\"none\" className=\"pointer-events-none stroke-foreground\" strokeWidth={2} /> : null}\n                  <circle r={Math.max(0, ring - 2)} className={cn(\"fill-background\", focus.path.length > 0 && \"cursor-pointer\")} onClick={up} />\n                  <text textAnchor=\"middle\" dy=\"-0.2em\" className=\"pointer-events-none fill-foreground text-sm font-medium\">\n                    {fitText(focus.node.name, ring * 1.7, 14)}\n                  </text>\n                  <text textAnchor=\"middle\" dy=\"1.2em\" className=\"pointer-events-none fill-muted-foreground text-xs tabular-nums\">\n                    {number(total)}\n                  </text>\n                </g>\n              </ChartSvg>\n              {focus.path.length > 0 ? (\n                <button type=\"button\" onClick={up} className=\"absolute start-0 top-0 min-h-10 rounded-control border bg-background px-3 text-sm hover:bg-accent\">\n                  {labels.up}\n                </button>\n              ) : null}\n              {current && shownAt ? (\n                <ChartTooltip\n                  x={shownAt[0]}\n                  y={shownAt[1]}\n                  side={shownAt[0] > 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      {showLegend && focus.path.length === 0 && (data.children?.length ?? 0) > 1 ? (\n        <ChartLegend items={(data.children ?? []).map((child, index) => ({ label: child.name, index: index < 5 ? index : -1, value: percent(chartTreeTotal(child) / whole) }))} mark=\"rect\" />\n      ) : null}\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Showing how a total divides level by level when the depth matters as much as the sizes: a path through categories, a file system, a budget in three levels. For sizes that must be compared closely use treemap (areas in rectangles are easier to judge than arcs); for one level use donut-chart.",
    "example": "<Sunburst\n  label=\"Visits by source\"\n  data={{\n    name: \"All visits\",\n    children: [\n      { name: \"Search\", children: [{ name: \"Organic\", value: 420 }, { name: \"Paid\", value: 160 }] },\n      { name: \"Social\", children: [{ name: \"Video\", value: 120 }, { name: \"Posts\", value: 80 }] },\n      { name: \"Direct\", value: 300 },\n    ],\n  }}\n/>",
    "client": true
  }
}
