{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-treemap",
  "type": "registry:component",
  "title": "Zoomable Treemap",
  "description": "A squarified treemap of groups and leaves, colored on a diverging scale by month-over-month change. Clicking a group zooms it to fill the frame as the other tiles fly out, with a breadcrumb and Escape to zoom back.",
  "author": "Hyperblur <hello@hyperblur.dev>",
  "dependencies": [],
  "registryDependencies": [],
  "categories": [
    "charts",
    "chart",
    "treemap",
    "hierarchy",
    "drill-down",
    "svg",
    "cost"
  ],
  "docs": "https://hyperblur.dev/effects/chart-treemap",
  "files": [
    {
      "path": "registry/hyperblur/chart-treemap.tsx",
      "type": "registry:component",
      "target": "components/hyperblur/chart-treemap.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface TreemapLeaf {\n  name: string;\n  value: number;\n  change?: number;\n}\n\nexport interface TreemapGroup {\n  name: string;\n  children: TreemapLeaf[];\n}\n\nexport interface ChartTreemapProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\" | \"title\" | \"onSelect\"> {\n  data?: TreemapGroup[];\n  height?: number;\n  title?: string;\n  summary?: string;\n  format?: (value: number) => string;\n  rootLabel?: string;\n  colorBy?: \"change\" | \"group\";\n  increaseColor?: string;\n  decreaseColor?: string;\n  palette?: string[];\n  onZoom?: (group: string | null) => void;\n  onSelect?: (leaf: TreemapLeaf & { group: string }) => void;\n}\n\nconst defaultData: TreemapGroup[] = [\n  {\n    name: \"Compute\",\n    children: [\n      { name: \"Instances\", value: 18400, change: 6.2 },\n      { name: \"Kubernetes\", value: 12900, change: 14.8 },\n      { name: \"GPU jobs\", value: 7600, change: 31 },\n      { name: \"Functions\", value: 3100, change: -8.4 },\n    ],\n  },\n  {\n    name: \"Data\",\n    children: [\n      { name: \"Warehouse\", value: 9800, change: 4.1 },\n      { name: \"Postgres\", value: 6200, change: -2.3 },\n      { name: \"Cache\", value: 2400, change: 0.6 },\n      { name: \"Search\", value: 1900, change: 9.7 },\n    ],\n  },\n  {\n    name: \"Storage\",\n    children: [\n      { name: \"Object storage\", value: 5600, change: 3.2 },\n      { name: \"Block volumes\", value: 3900, change: -11.5 },\n      { name: \"Backups\", value: 1700, change: 1.1 },\n    ],\n  },\n  {\n    name: \"Network\",\n    children: [\n      { name: \"Egress\", value: 4800, change: 18.9 },\n      { name: \"CDN\", value: 2900, change: -4.6 },\n      { name: \"Load balancers\", value: 1300, change: 0 },\n    ],\n  },\n  {\n    name: \"Observability\",\n    children: [\n      { name: \"Logs\", value: 3600, change: 22.4 },\n      { name: \"Metrics\", value: 1800, change: -6.1 },\n      { name: \"Traces\", value: 1100, change: 3.5 },\n    ],\n  },\n];\n\nconst defaultPalette = [\"#2f7bff\", \"#22c3a6\", \"#a78bfa\", \"#f5b544\", \"#f472b6\", \"#7fb3ff\"];\n\ninterface Box {\n  x: number;\n  y: number;\n  w: number;\n  h: number;\n}\n\nfunction worst(row: number[], side: number) {\n  const sum = row.reduce((a, b) => a + b, 0);\n  const max = Math.max(...row);\n  const min = Math.min(...row);\n  const s2 = side * side;\n  return Math.max((s2 * max) / (sum * sum), (sum * sum) / (s2 * min));\n}\n\nfunction squarify(values: number[], box: Box): Box[] {\n  const out: Box[] = new Array(values.length);\n  const total = values.reduce((a, b) => a + b, 0);\n  if (total <= 0 || box.w <= 0 || box.h <= 0) return values.map(() => ({ x: box.x, y: box.y, w: 0, h: 0 }));\n  const order = values.map((v, i) => ({ v, i })).sort((a, b) => b.v - a.v);\n  const scale = (box.w * box.h) / total;\n  let { x, y, w, h } = box;\n  let k = 0;\n  while (k < order.length) {\n    const side = Math.min(w, h);\n    const row = [order[k]];\n    let j = k + 1;\n    while (j < order.length) {\n      const a = row.map((r) => r.v * scale);\n      const b = [...a, order[j].v * scale];\n      if (worst(b, side) <= worst(a, side)) {\n        row.push(order[j]);\n        j++;\n      } else break;\n    }\n    const area = row.reduce((acc, r) => acc + r.v * scale, 0);\n    if (w >= h) {\n      const cw = h > 0 ? area / h : 0;\n      let cy = y;\n      row.forEach((r) => {\n        const rh = cw > 0 ? (r.v * scale) / cw : 0;\n        out[r.i] = { x, y: cy, w: cw, h: rh };\n        cy += rh;\n      });\n      x += cw;\n      w -= cw;\n    } else {\n      const rh = w > 0 ? area / w : 0;\n      let cx = x;\n      row.forEach((r) => {\n        const cw = rh > 0 ? (r.v * scale) / rh : 0;\n        out[r.i] = { x: cx, y, w: cw, h: rh };\n        cx += cw;\n      });\n      y += rh;\n      h -= rh;\n    }\n    k = j;\n  }\n  return out;\n}\n\nfunction hexRgb(hex: string): [number, number, number] {\n  const h = hex.replace(\"#\", \"\");\n  const full = h.length === 3 ? h.split(\"\").map((c) => c + c).join(\"\") : h.padEnd(6, \"0\");\n  const n = parseInt(full.slice(0, 6), 16);\n  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];\n}\n\nfunction mix(a: string, b: string, t: number) {\n  const x = hexRgb(a);\n  const y = hexRgb(b);\n  const c = x.map((v, i) => Math.round(v + (y[i] - v) * t));\n  return `rgb(${c[0]}, ${c[1]}, ${c[2]})`;\n}\n\nconst css = `\n.hb-wi3 {\n  position: relative;\n  width: 100%;\n  box-sizing: border-box;\n  color: #ededed;\n  font-family: inherit;\n  font-size: 12px;\n}\n.hb-wi3 *, .hb-wi3 *::before, .hb-wi3 *::after { box-sizing: border-box; }\n.hb-wi3-bar { display: flex; align-items: center; justify-content: space-between; gap: 10px; height: 26px; margin-bottom: 8px; }\n.hb-wi3-crumbs { display: flex; align-items: center; gap: 4px; min-width: 0; font-size: 12px; }\n.hb-wi3-crumb {\n  height: 24px;\n  padding: 0 8px;\n  border: 0;\n  border-radius: 7px;\n  background: transparent;\n  color: #8f8f8f;\n  font: inherit;\n  cursor: pointer;\n  transition: background 0.2s ease, color 0.2s ease;\n}\n.hb-wi3-crumb:hover { background: #171717; color: #ededed; }\n.hb-wi3-crumb:focus-visible { outline: none; box-shadow: 0 0 0 2px rgba(127, 179, 255, 0.7); }\n.hb-wi3-crumb[aria-current=\"page\"] { color: #ededed; font-weight: 550; cursor: default; background: transparent; }\n.hb-wi3-sep { color: #4a4a4a; }\n.hb-wi3-scale { display: flex; align-items: center; gap: 6px; font-size: 10.5px; color: #8f8f8f; white-space: nowrap; }\n.hb-wi3-ramp { width: 64px; height: 6px; border-radius: 3px; }\n.hb-wi3-plot { position: relative; width: 100%; height: var(--hb-wi3-h, 260px); overflow: hidden; border-radius: 10px; background: #0d0d0d; }\n.hb-wi3-svg { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }\n.hb-wi3-rect {\n  transition: transform 0.65s cubic-bezier(0.65, 0, 0.25, 1), opacity 0.4s ease, filter 0.2s ease;\n}\n.hb-wi3[data-in=\"false\"] .hb-wi3-rect { transition: none; }\n.hb-wi3-rect[data-dim=\"true\"] { opacity: 0; }\n.hb-wi3-rect[data-hot=\"true\"] { filter: brightness(1.25); }\n.hb-wi3-tile {\n  position: absolute;\n  display: flex;\n  flex-direction: column;\n  justify-content: flex-end;\n  gap: 1px;\n  padding: 6px 7px;\n  border: 0;\n  margin: 0;\n  background: transparent;\n  color: #fff;\n  font: inherit;\n  text-align: left;\n  overflow: hidden;\n  cursor: pointer;\n  transition: left 0.65s cubic-bezier(0.65, 0, 0.25, 1), top 0.65s cubic-bezier(0.65, 0, 0.25, 1), width 0.65s cubic-bezier(0.65, 0, 0.25, 1), height 0.65s cubic-bezier(0.65, 0, 0.25, 1), opacity 0.4s ease;\n}\n.hb-wi3[data-in=\"false\"] .hb-wi3-tile { transition: none; }\n.hb-wi3-tile:focus-visible { outline: none; box-shadow: inset 0 0 0 2px #ededed; }\n.hb-wi3-tile[data-dim=\"true\"] { opacity: 0; pointer-events: none; }\n.hb-wi3-tile b { font-size: 11.5px; font-weight: 600; line-height: 1.15; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.35); }\n.hb-wi3-tile span { font-size: 10.5px; color: rgba(255, 255, 255, 0.78); font-variant-numeric: tabular-nums; white-space: nowrap; }\n.hb-wi3-tile [data-hide=\"true\"] { display: none; }\n.hb-wi3-tile > * { opacity: 0; transform: translateY(4px); transition: opacity 0.35s ease, transform 0.35s ease; transition-delay: var(--hb-wi3-d, 0ms); }\n.hb-wi3[data-in=\"true\"] .hb-wi3-tile > * { opacity: 1; transform: none; }\n.hb-wi3-head {\n  position: absolute;\n  display: flex;\n  align-items: center;\n  gap: 6px;\n  height: 18px;\n  padding: 0 6px;\n  border: 0;\n  background: transparent;\n  color: #ededed;\n  font: inherit;\n  font-size: 10.5px;\n  font-weight: 600;\n  letter-spacing: 0.02em;\n  text-transform: uppercase;\n  white-space: nowrap;\n  overflow: hidden;\n  cursor: zoom-in;\n  transition: opacity 0.3s ease;\n}\n.hb-wi3-head em { font-style: normal; font-weight: 500; color: #8f8f8f; text-transform: none; letter-spacing: 0; font-variant-numeric: tabular-nums; }\n.hb-wi3-head:focus-visible { outline: none; box-shadow: inset 0 0 0 1.5px rgba(127, 179, 255, 0.8); border-radius: 4px; }\n.hb-wi3-head[data-dim=\"true\"] { opacity: 0; pointer-events: none; }\n.hb-wi3-tip {\n  position: absolute;\n  z-index: 4;\n  min-width: 150px;\n  padding: 8px 10px;\n  border-radius: 10px;\n  background: rgba(17, 17, 17, 0.95);\n  border: 1px solid #262626;\n  box-shadow: 0 14px 30px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.05);\n  pointer-events: none;\n  white-space: nowrap;\n}\n.hb-wi3-tip small { display: block; font-size: 10.5px; color: #8f8f8f; }\n.hb-wi3-tip strong { display: block; margin-top: 2px; font-size: 12.5px; font-weight: 600; }\n.hb-wi3-tip div { display: flex; justify-content: space-between; gap: 14px; margin-top: 5px; font-size: 11.5px; font-variant-numeric: tabular-nums; color: #a1a1a1; }\n.hb-wi3-tip div b { color: #ededed; font-weight: 550; }\n.hb-wi3-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }\n@media (prefers-reduced-motion: reduce) {\n  .hb-wi3-rect, .hb-wi3-tile, .hb-wi3-tile > *, .hb-wi3-head { transition: none !important; }\n  .hb-wi3-tile > * { opacity: 1; transform: none; }\n}\n`;\n\nexport function ChartTreemap({\n  data = defaultData,\n  height = 260,\n  title = \"Cloud spend by service, October\",\n  summary,\n  format,\n  rootLabel = \"All services\",\n  colorBy = \"change\",\n  increaseColor = \"#ff6b5b\",\n  decreaseColor = \"#22c3a6\",\n  palette = defaultPalette,\n  onZoom,\n  onSelect,\n  className,\n  style,\n  ...rest\n}: ChartTreemapProps) {\n  const id = React.useId().replace(/:/g, \"\");\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const [width, setWidth] = React.useState(600);\n  const [inView, setInView] = React.useState(false);\n  const [zoom, setZoom] = React.useState<string | null>(null);\n  const [hot, setHot] = React.useState<string | null>(null);\n  const [tip, setTip] = React.useState<{ key: string; x: number; y: number } | null>(null);\n  const fmt = format ?? ((v: number) => (v >= 1000 ? `$${(v / 1000).toFixed(v >= 10000 ? 0 : 1)}k` : `$${Math.round(v)}`));\n\n  React.useEffect(() => {\n    const el = plotRef.current;\n    if (!el) return;\n    const measure = () => setWidth(Math.max(120, el.clientWidth));\n    measure();\n    const ro = new ResizeObserver(measure);\n    ro.observe(el);\n    const t = window.setTimeout(() => setInView(true), 80);\n    return () => {\n      ro.disconnect();\n      window.clearTimeout(t);\n    };\n  }, []);\n\n  const H = height;\n  const total = data.reduce((a, g) => a + g.children.reduce((b, c) => b + c.value, 0), 0);\n\n  const layout = React.useMemo(() => {\n    const groupTotals = data.map((g) => g.children.reduce((a, c) => a + c.value, 0));\n    const groupBoxes = squarify(groupTotals, { x: 0, y: 0, w: width, h: H });\n    const leaves: { key: string; group: string; gi: number; leaf: TreemapLeaf; root: Box; zoomed: Box | null }[] = [];\n    const heads: { name: string; box: Box; total: number; showHead: boolean }[] = [];\n    data.forEach((g, gi) => {\n      const gb = groupBoxes[gi];\n      const showHead = gb.h > 46 && gb.w > 70;\n      const inner = showHead ? { x: gb.x + 2, y: gb.y + 20, w: gb.w - 4, h: gb.h - 22 } : { x: gb.x + 2, y: gb.y + 2, w: gb.w - 4, h: gb.h - 4 };\n      heads.push({ name: g.name, box: gb, total: groupTotals[gi], showHead });\n      const rb = squarify(g.children.map((c) => c.value), inner);\n      const zb = zoom === g.name ? squarify(g.children.map((c) => c.value), { x: 0, y: 0, w: width, h: H }) : null;\n      g.children.forEach((c, ci) => leaves.push({ key: `${g.name}/${c.name}`, group: g.name, gi, leaf: c, root: rb[ci], zoomed: zb ? zb[ci] : null }));\n    });\n    const zg = zoom ? heads.find((h) => h.name === zoom) : null;\n    const map = (b: Box): Box => {\n      if (!zg || zg.box.w <= 0 || zg.box.h <= 0) return b;\n      const sx = width / zg.box.w;\n      const sy = H / zg.box.h;\n      return { x: (b.x - zg.box.x) * sx, y: (b.y - zg.box.y) * sy, w: b.w * sx, h: b.h * sy };\n    };\n    return {\n      leaves: leaves.map((l) => ({ ...l, box: l.zoomed ?? map(l.root) })),\n      heads: heads.map((h) => ({ ...h, view: map(h.box) })),\n    };\n  }, [data, width, H, zoom]);\n\n  const colorOf = (leaf: TreemapLeaf, gi: number) => {\n    if (colorBy === \"group\") return mix(\"#141414\", palette[gi % palette.length], 0.72);\n    const c = leaf.change ?? 0;\n    const t = Math.min(1, Math.abs(c) / 25);\n    if (Math.abs(c) < 0.5) return \"#2a2a2a\";\n    return mix(\"#1c1c1c\", c > 0 ? increaseColor : decreaseColor, 0.28 + t * 0.62);\n  };\n\n  const goZoom = (g: string | null) => {\n    setZoom(g);\n    setTip(null);\n    onZoom?.(g);\n  };\n\n  const f = (n: number) => n.toFixed(2);\n  const tipLeaf = tip ? layout.leaves.find((l) => l.key === tip.key) : null;\n  const desc =\n    summary ??\n    `Treemap of ${fmt(total)} across ${data.length} groups: ${data.map((g) => `${g.name} ${fmt(g.children.reduce((a, c) => a + c.value, 0))}`).join(\", \")}.`;\n\n  return (\n    <div\n      {...rest}\n      className={[\"hb-wi3\", className].filter(Boolean).join(\" \")}\n      style={{ ...style, [\"--hb-wi3-h\" as string]: `${H}px` } as React.CSSProperties}\n      data-in={inView}\n      onKeyDown={(e) => {\n        if (e.key === \"Escape\" && zoom) goZoom(null);\n      }}\n    >\n      <style href=\"hb-chart-treemap\" precedence=\"default\">{css}</style>\n      <div className=\"hb-wi3-bar\">\n        <nav className=\"hb-wi3-crumbs\" aria-label=\"Treemap level\">\n          <button type=\"button\" className=\"hb-wi3-crumb\" aria-current={zoom ? undefined : \"page\"} onClick={() => zoom && goZoom(null)}>\n            {rootLabel}\n          </button>\n          {zoom ? (\n            <>\n              <span className=\"hb-wi3-sep\" aria-hidden=\"true\">/</span>\n              <button type=\"button\" className=\"hb-wi3-crumb\" aria-current=\"page\">\n                {zoom}\n              </button>\n            </>\n          ) : null}\n        </nav>\n        {colorBy === \"change\" ? (\n          <div className=\"hb-wi3-scale\" aria-hidden=\"true\">\n            <span>-25%</span>\n            <span className=\"hb-wi3-ramp\" style={{ background: `linear-gradient(90deg, ${decreaseColor}, #2a2a2a 50%, ${increaseColor})` }} />\n            <span>+25%</span>\n          </div>\n        ) : null}\n      </div>\n      <div ref={plotRef} className=\"hb-wi3-plot\" onPointerLeave={() => { setTip(null); setHot(null); }}>\n        <svg className=\"hb-wi3-svg\" viewBox={`0 0 ${width} ${H}`} preserveAspectRatio=\"none\" role=\"img\" aria-labelledby={`${id}-t ${id}-d`}>\n          <title id={`${id}-t`}>{title}</title>\n          <desc id={`${id}-d`}>{desc}</desc>\n          {layout.leaves.map((l) => {\n            const b = l.box;\n            const x = b.x + 1;\n            const y = b.y + 1;\n            const w = Math.max(0, b.w - 2);\n            const h = Math.max(0, b.h - 2);\n            const transform = inView ? `translate(${f(x)}px, ${f(y)}px) scale(${f(w)}, ${f(h)})` : `translate(${f(x + w / 2)}px, ${f(y + h / 2)}px) scale(0, 0)`;\n            return <rect key={l.key} className=\"hb-wi3-rect\" x={0} y={0} width={1} height={1} fill={colorOf(l.leaf, l.gi)} data-dim={zoom !== null && l.group !== zoom} data-hot={hot === l.key} style={{ transform }} />;\n          })}\n        </svg>\n        {layout.heads.map((h) =>\n          h.showHead ? (\n            <button\n              key={h.name}\n              type=\"button\"\n              className=\"hb-wi3-head\"\n              data-dim={zoom !== null}\n              tabIndex={zoom ? -1 : 0}\n              aria-label={`Zoom into ${h.name}, ${fmt(h.total)}`}\n              style={{ left: h.view.x + 2, top: h.view.y + 1, maxWidth: Math.max(0, h.view.w - 4) }}\n              onClick={() => goZoom(h.name)}\n            >\n              {h.name}\n              <em>{fmt(h.total)}</em>\n            </button>\n          ) : null,\n        )}\n        {layout.leaves.map((l, i) => {\n          const b = l.box;\n          const big = b.w > 62 && b.h > 34;\n          const med = b.w > 44 && b.h > 20;\n          const c = l.leaf.change ?? 0;\n          return (\n            <button\n              key={l.key}\n              type=\"button\"\n              className=\"hb-wi3-tile\"\n              data-dim={zoom !== null && l.group !== zoom}\n              tabIndex={zoom !== null && l.group !== zoom ? -1 : 0}\n              aria-label={`${l.leaf.name}, ${l.group}, ${fmt(l.leaf.value)}, ${c >= 0 ? \"up\" : \"down\"} ${Math.abs(c).toFixed(1)} percent`}\n              style={{ left: b.x + 1, top: b.y + 1, width: Math.max(0, b.w - 2), height: Math.max(0, b.h - 2), [\"--hb-wi3-d\" as string]: `${300 + i * 35}ms` } as React.CSSProperties}\n              onPointerEnter={() => setHot(l.key)}\n              onPointerMove={(e) => {\n                const r = plotRef.current?.getBoundingClientRect();\n                if (!r) return;\n                const px = e.clientX - r.left;\n                const py = e.clientY - r.top;\n                setTip({ key: l.key, x: px > r.width - 170 ? px - 162 : px + 12, y: py > r.height - 90 ? py - 84 : py + 12 });\n              }}\n              onPointerLeave={() => {\n                setHot(null);\n                setTip(null);\n              }}\n              onFocus={() => setHot(l.key)}\n              onBlur={() => setHot(null)}\n              onClick={() => {\n                if (zoom === null) goZoom(l.group);\n                else onSelect?.({ ...l.leaf, group: l.group });\n              }}\n            >\n              <b data-hide={!med}>{l.leaf.name}</b>\n              <span data-hide={!big}>\n                {fmt(l.leaf.value)} · {c > 0 ? \"+\" : \"\"}\n                {c.toFixed(1)}%\n              </span>\n            </button>\n          );\n        })}\n        {tipLeaf && tip ? (\n          <div className=\"hb-wi3-tip\" style={{ left: tip.x, top: tip.y }}>\n            <small>{tipLeaf.group}</small>\n            <strong>{tipLeaf.leaf.name}</strong>\n            <div>\n              <span>Spend</span>\n              <b>{fmt(tipLeaf.leaf.value)}</b>\n            </div>\n            <div>\n              <span>vs September</span>\n              <b style={{ color: (tipLeaf.leaf.change ?? 0) > 0 ? increaseColor : (tipLeaf.leaf.change ?? 0) < 0 ? decreaseColor : \"#ededed\" }}>\n                {(tipLeaf.leaf.change ?? 0) > 0 ? \"+\" : \"\"}\n                {(tipLeaf.leaf.change ?? 0).toFixed(1)}%\n              </b>\n            </div>\n            <div>\n              <span>Share of total</span>\n              <b>{total > 0 ? ((tipLeaf.leaf.value / total) * 100).toFixed(1) : \"0\"}%</b>\n            </div>\n          </div>\n        ) : null}\n        <div className=\"hb-wi3-sr\" aria-live=\"polite\">\n          {zoom ? `Showing ${zoom}` : `Showing ${rootLabel}`}\n        </div>\n      </div>\n    </div>\n  );\n}\n"
    }
  ]
}