{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "treemap",
  "type": "registry:component",
  "title": "Treemap",
  "description": "A whole split into nested rectangles whose areas are the parts' sizes: groups in their own colours, the parts inside them labelled where they fit, 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/treemap.tsx",
      "type": "registry:component",
      "target": "components/viz/treemap.tsx",
      "content": "\"use client\";\n/**\n * @name treemap\n * @category viz\n * @description A whole split into nested rectangles whose areas are the parts' sizes: groups in their own colours, the parts inside them labelled where they fit, with zooming into a group by click or Enter and back out by the trail or Backspace.\n * @when Showing how a large total divides across a hierarchy (a budget by department and team, storage by folder) when there are too many parts for a donut. For a few parts use donut-chart; to see the levels as rings use sunburst; to compare exact sizes use bar-chart.\n * @example\n * <Treemap\n *   label=\"Spending by area\"\n *   data={{\n *     name: \"All spending\",\n *     children: [\n *       { name: \"Housing\", children: [{ name: \"Rent\", value: 1200 }, { name: \"Power\", value: 140 }] },\n *       { name: \"Food\", children: [{ name: \"Groceries\", value: 420 }, { name: \"Cafés\", value: 90 }] },\n *       { name: \"Travel\", value: 260 },\n *     ],\n *   }}\n * />\n */\nimport { hierarchy, treemap, treemapSquarify, type HierarchyRectangularNode } 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 TreemapLabels = {\n  /** The name of the trail of levels. */\n  trail: string;\n  /** The column names of the table alternative. */\n  part: string;\n  value: string;\n  share: string;\n  /** Said with a group that can be opened. */\n  canOpen: string;\n};\n\nexport type TreemapProps = 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  /** Words, for translation. */\n  labels?: Partial<TreemapLabels>;\n};\n\nconst LABELS: TreemapLabels = { trail: \"Level\", part: \"Part\", value: \"Value\", share: \"Share\", canOpen: \"press Enter to open\" };\nconst EMPTY: readonly string[] = [];\n\nexport function Treemap({ data, path: pathProp, defaultPath = EMPTY, onPathChange, labels: given, label, aspect, height, emptyLabel, locale, formatValue, className, ...props }: TreemapProps) {\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  // A group keeps its colour while zoomed: the colour belongs to the top-level group it is in.\n  const topIndex = (name: string): number => data.children?.findIndex((child) => child.name === name) ?? 0;\n\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 leaves = useMemo(() => root.leaves(), [root]);\n  const cursor = useChartCursor(leaves.length);\n  const groupOf = (node: HierarchyRectangularNode<ChartTreeNode> | (typeof leaves)[number]): string => node.ancestors().find((a) => a.depth === 1)?.data.name ?? node.data.name;\n  const colourOf = (node: (typeof leaves)[number]): number => {\n    const top = focus.path.length > 0 ? (focus.path[0] ?? \"\") : groupOf(node);\n    const index = topIndex(top);\n    return index >= 0 && index < 5 ? index : -1;\n  };\n  const openable = (node: (typeof leaves)[number]): boolean => node.depth > 1;\n\n  const table = { caption: label, columns: [labels.part, labels.value, labels.share], rows: chartTreeRows(data, number, percent) };\n  const current = cursor.active === null ? undefined : leaves[cursor.active];\n  const describe = (node: (typeof leaves)[number]): string =>\n    `${node\n      .ancestors()\n      .reverse()\n      .slice(1)\n      .map((a) => a.data.name)\n      .join(\" / \")}: ${number(node.value ?? 0)}, ${percent((node.value ?? 0) / whole)}${openable(node) ? `, ${labels.canOpen}` : \"\"}`;\n\n  const open = (node: (typeof leaves)[number]): void => {\n    const group = node.ancestors().find((a) => a.depth === 1);\n    if (!group || group === node) return;\n    setPath([...focus.path, group.data.name]);\n    cursor.select(null);\n  };\n  const onKeyDown = (event: KeyboardEvent<SVGSVGElement>): void => {\n    if ((event.key === \"Enter\" || event.key === \" \") && current) {\n      event.preventDefault();\n      open(current);\n      return;\n    }\n    if (event.key === \"Backspace\" && focus.path.length > 0) {\n      event.preventDefault();\n      setPath(focus.path.slice(0, -1));\n      cursor.select(null);\n      return;\n    }\n    cursor.svgProps.onKeyDown(event);\n  };\n\n  return (\n    <div data-slot=\"treemap\" className={cn(\"flex w-full min-w-0 flex-col gap-2\", className)} {...props}>\n      <div className=\"flex flex-wrap items-baseline justify-between gap-x-4\">\n        <ChartTrail aria-label={labels.trail} trail={[data.name, ...focus.path]} onNavigate={(depth) => setPath(focus.path.slice(0, depth))} />\n        <span className=\"text-sm tabular-nums text-muted-foreground\">{number(total)}</span>\n      </div>\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 laid = treemap<ChartTreeNode>()\n            .tile(treemapSquarify)\n            .size([width, plotHeight])\n            .paddingInner(2)\n            .paddingTop((node) => (node.depth === 1 && node.children ? 18 : 0))\n            .round(true)(root.copy());\n          const placed = laid.leaves();\n          const groups = laid.children?.filter((child) => child.children) ?? [];\n          const shown = cursor.active === null ? undefined : placed[cursor.active];\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) => {\n                    const w = group.x1 - group.x0;\n                    return w > 30 ? (\n                      <text key={group.data.name} x={group.x0 + 4} y={group.y0 + 12} className=\"fill-muted-foreground text-xs\">\n                        {fitText(group.data.name, w - 8)}\n                      </text>\n                    ) : null;\n                  })}\n                  {placed.map((node, index) => {\n                    const w = node.x1 - node.x0;\n                    const h = node.y1 - node.y0;\n                    if (w <= 0 || h <= 0) return null;\n                    const style = chartSeries(colourOf(leaves[index] ?? node));\n                    const dim = cursor.active !== null && cursor.active !== index;\n                    return (\n                      <g\n                        key={index}\n                        className={cn(\"cursor-pointer transition-opacity duration-instant motion-reduce:transition-none\", dim && \"opacity-55\")}\n                        onPointerEnter={() => cursor.point(index)}\n                        onClick={() => {\n                          const leaf = leaves[index];\n                          if (leaf) open(leaf);\n                        }}\n                      >\n                        <rect x={node.x0} y={node.y0} width={w} height={h} className={cn(style.fill, \"[rx:min(var(--radius),4px)]\")} fillOpacity={0.24} />\n                        <rect x={node.x0} y={node.y0} width={w} height={Math.min(3, h)} className={style.fill} />\n                        {w > 36 && h > 30 ? (\n                          <>\n                            <text x={node.x0 + 6} y={node.y0 + 18} className=\"fill-foreground text-xs font-medium\">\n                              {fitText(node.data.name, w - 12)}\n                            </text>\n                            {h > 46 ? (\n                              <text x={node.x0 + 6} y={node.y0 + 34} className=\"fill-muted-foreground text-xs tabular-nums\">\n                                {fitText(number(node.value ?? 0), w - 12)}\n                              </text>\n                            ) : null}\n                          </>\n                        ) : null}\n                      </g>\n                    );\n                  })}\n                  {shown ? (\n                    <rect\n                      x={shown.x0 + 1}\n                      y={shown.y0 + 1}\n                      width={Math.max(0, shown.x1 - shown.x0 - 2)}\n                      height={Math.max(0, shown.y1 - shown.y0 - 2)}\n                      fill=\"none\"\n                      className=\"pointer-events-none stroke-foreground\"\n                      strokeWidth={2}\n                    />\n                  ) : null}\n                </g>\n              </ChartSvg>\n              {shown && current ? (\n                <ChartTooltip\n                  x={(shown.x0 + shown.x1) / 2}\n                  y={(shown.y0 + shown.y1) / 2}\n                  side={(shown.x0 + shown.x1) / 2 > width / 2 ? \"left\" : \"right\"}\n                  title={current\n                    .ancestors()\n                    .reverse()\n                    .slice(1, -1)\n                    .map((a) => a.data.name)\n                    .join(\" / \")}\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 how a large total divides across a hierarchy (a budget by department and team, storage by folder) when there are too many parts for a donut. For a few parts use donut-chart; to see the levels as rings use sunburst; to compare exact sizes use bar-chart.",
    "example": "<Treemap\n  label=\"Spending by area\"\n  data={{\n    name: \"All spending\",\n    children: [\n      { name: \"Housing\", children: [{ name: \"Rent\", value: 1200 }, { name: \"Power\", value: 140 }] },\n      { name: \"Food\", children: [{ name: \"Groceries\", value: 420 }, { name: \"Cafés\", value: 90 }] },\n      { name: \"Travel\", value: 260 },\n    ],\n  }}\n/>",
    "client": true
  }
}
