{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "treemap-chart",
  "title": "Treemap Chart",
  "description": "A squarified treemap of a two-level hierarchy: tile area follows value, tiles are coloured by growth from red through neutral to green, groups carry labelled headers, and clicking a group zooms into it with tiles gliding to their new places.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/treemap-chart/treemap-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type ChartTheme = \"dark\" | \"light\";\n\nexport interface TreemapLeaf {\n  label: string;\n  value: number;\n  /** Optional change (e.g. growth in %), used to colour tiles from red through neutral to green. */\n  change?: number;\n}\n\nexport interface TreemapGroup {\n  label: string;\n  children: TreemapLeaf[];\n}\n\nexport interface TreemapChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"div\">,\n  \"title\"\n> {\n  theme?: ChartTheme;\n  title?: string;\n  subtitle?: string;\n  groups?: TreemapGroup[];\n  /** How tiles are coloured: by `change` (diverging) or by group. */\n  colorBy?: \"change\" | \"group\";\n  /** The change that maps to full colour, in the same units as `change`. */\n  changeRange?: number;\n  /** Height of the treemap, in px. */\n  height?: number;\n  formatValue?: (value: number) => string;\n  formatChange?: (value: number) => string;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#0E0E0E\",\n    border: \"rgba(255,255,255,0.08)\",\n    text: \"#F4F5F7\",\n    sub: \"rgba(255,255,255,0.55)\",\n    tileText: \"#FFFFFF\",\n    tip: \"rgba(20,20,20,0.96)\",\n    tipBorder: \"rgba(255,255,255,0.12)\",\n    chip: \"rgba(255,255,255,0.06)\",\n    gap: \"#0E0E0E\",\n    neutral: [52, 55, 62],\n    pos: [22, 163, 112],\n    neg: [214, 60, 76],\n    series: [\"#3B6FD8\", \"#0E9F80\", \"#7B5CE0\", \"#D9822B\", \"#C2416B\"],\n  },\n  light: {\n    card: \"#FFFFFF\",\n    border: \"rgba(0,0,0,0.07)\",\n    text: \"#111317\",\n    sub: \"rgba(17,19,23,0.55)\",\n    tileText: \"#FFFFFF\",\n    tip: \"rgba(255,255,255,0.98)\",\n    tipBorder: \"rgba(0,0,0,0.08)\",\n    chip: \"rgba(0,0,0,0.05)\",\n    gap: \"#FFFFFF\",\n    neutral: [150, 156, 166],\n    pos: [16, 150, 100],\n    neg: [220, 64, 78],\n    series: [\"#3B6FD8\", \"#0E9F80\", \"#7B5CE0\", \"#D9822B\", \"#C2416B\"],\n  },\n};\n\nconst DEFAULT_GROUPS: TreemapGroup[] = [\n  {\n    label: \"North America\",\n    children: [\n      { label: \"Platform\", value: 4200, change: 12.4 },\n      { label: \"Payments\", value: 2900, change: 18.2 },\n      { label: \"Analytics\", value: 1650, change: 6.1 },\n      { label: \"Support\", value: 820, change: -3.4 },\n      { label: \"Marketplace\", value: 610, change: 24.8 },\n      { label: \"Training\", value: 260, change: -8.9 },\n    ],\n  },\n  {\n    label: \"Europe\",\n    children: [\n      { label: \"Platform\", value: 2700, change: 8.7 },\n      { label: \"Payments\", value: 1900, change: 14.1 },\n      { label: \"Analytics\", value: 980, change: -1.2 },\n      { label: \"Support\", value: 540, change: 2.3 },\n      { label: \"Marketplace\", value: 330, change: 31.5 },\n    ],\n  },\n  {\n    label: \"Asia Pacific\",\n    children: [\n      { label: \"Platform\", value: 1600, change: 22.6 },\n      { label: \"Payments\", value: 1250, change: 35.4 },\n      { label: \"Analytics\", value: 520, change: 15.8 },\n      { label: \"Support\", value: 260, change: -5.6 },\n    ],\n  },\n  {\n    label: \"Latin America\",\n    children: [\n      { label: \"Payments\", value: 720, change: 41.2 },\n      { label: \"Platform\", value: 480, change: -4.8 },\n      { label: \"Support\", value: 150, change: -12.5 },\n    ],\n  },\n];\n\ntype Rect = { x: number; y: number; w: number; h: number };\ntype Tile = Rect & {\n  id: string;\n  g: number;\n  c: number;\n  label: string;\n  value: number;\n  change?: number;\n};\n\nconst compact = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(entry.contentRect.width),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\n/** 0 → 1 (linear) once the element scrolls into view; 1 straight away with reduced motion. */\nfunction useReveal(\n  ref: React.RefObject<HTMLElement | null>,\n  reduce: boolean,\n  duration = 1100,\n) {\n  const [t, setT] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el || reduce) return;\n    let raf = 0;\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        io.disconnect();\n        const start = performance.now();\n        const tick = (now: number) => {\n          const k = Math.min(1, (now - start) / duration);\n          setT(k);\n          if (k < 1) raf = requestAnimationFrame(tick);\n        };\n        raf = requestAnimationFrame(tick);\n      },\n      { threshold: 0.2 },\n    );\n    io.observe(el);\n    return () => {\n      io.disconnect();\n      cancelAnimationFrame(raf);\n    };\n  }, [ref, reduce, duration]);\n  return reduce ? 1 : t;\n}\n\n/** Squarified treemap (Bruls, Huizing & van Wijk): rows of tiles kept as close to square as possible. */\nfunction squarify(values: number[], rect: Rect): Rect[] {\n  const out: Rect[] = new Array(values.length);\n  const total = values.reduce((a, b) => a + b, 0);\n  if (!total || rect.w <= 0 || rect.h <= 0)\n    return values.map(() => ({ x: rect.x, y: rect.y, w: 0, h: 0 }));\n  const scale = (rect.w * rect.h) / total;\n  const items = values\n    .map((v, i) => ({ i, a: v * scale }))\n    .sort((p, q) => q.a - p.a);\n  let { x, y, w, h } = rect;\n  const worst = (row: { a: number }[], side: number) => {\n    const s = row.reduce((t, r) => t + r.a, 0);\n    const max = Math.max(...row.map((r) => r.a));\n    const min = Math.min(...row.map((r) => r.a));\n    return Math.max(\n      (side * side * max) / (s * s),\n      (s * s) / (side * side * min),\n    );\n  };\n  const place = (row: { i: number; a: number }[]) => {\n    const s = row.reduce((t, r) => t + r.a, 0);\n    if (w >= h) {\n      const cw = s / h;\n      let cy = y;\n      for (const r of row) {\n        const rh = r.a / cw;\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 = s / w;\n      let cx = x;\n      for (const r of row) {\n        const rw = r.a / rh;\n        out[r.i] = { x: cx, y, w: rw, h: rh };\n        cx += rw;\n      }\n      y += rh;\n      h -= rh;\n    }\n  };\n  let row: { i: number; a: number }[] = [];\n  for (const item of items) {\n    const side = Math.min(w, h);\n    if (!row.length || worst([...row, item], side) <= worst(row, side))\n      row.push(item);\n    else {\n      place(row);\n      row = [item];\n    }\n  }\n  if (row.length) place(row);\n  return out;\n}\n\nexport function TreemapChart({\n  theme = \"dark\",\n  title = \"Revenue by region and product\",\n  subtitle = \"Trailing 12 months, tiles coloured by year-over-year growth\",\n  groups = DEFAULT_GROUPS,\n  colorBy = \"change\",\n  changeRange = 30,\n  height = 380,\n  formatValue = (v) => `$${compact.format(v * 1000)}`,\n  formatChange = (v) => `${v > 0 ? \"+\" : \"\"}${v.toFixed(1)}%`,\n  className,\n  style,\n  ...props\n}: TreemapChartProps) {\n  const pal = PALETTES[theme];\n  const reduce = useReducedMotion();\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(boxRef);\n  const reveal = useReveal(boxRef, reduce);\n  const [focus, setFocus] = React.useState<number | null>(null);\n  const [active, setActive] = React.useState<string | null>(null);\n  const h = width > 0 && width < 520 ? Math.round(height * 0.8) : height;\n  const grand = groups.reduce(\n    (s, g) => s + g.children.reduce((t, c) => t + c.value, 0),\n    0,\n  );\n\n  // Lay out the tiles for the current view: every group (with a label strip), or one group full-size.\n  const tiles = React.useMemo<Tile[]>(() => {\n    if (!width) return [];\n    const out: Tile[] = [];\n    const leaves = (g: number, r: Rect) =>\n      squarify(\n        groups[g].children.map((c) => c.value),\n        r,\n      ).forEach((rc, c) => {\n        const leaf = groups[g].children[c];\n        out.push({\n          ...rc,\n          id: `${g}:${c}`,\n          g,\n          c,\n          label: leaf.label,\n          value: leaf.value,\n          change: leaf.change,\n        });\n      });\n    if (focus !== null && groups[focus])\n      leaves(focus, { x: 0, y: 0, w: width, h });\n    else {\n      const totals = groups.map((g) =>\n        g.children.reduce((t, c) => t + c.value, 0),\n      );\n      squarify(totals, { x: 0, y: 0, w: width, h }).forEach((r, g) => {\n        const strip = r.h > 60 && r.w > 70 ? 22 : 0;\n        leaves(g, {\n          x: r.x + 1,\n          y: r.y + strip + 1,\n          w: Math.max(0, r.w - 2),\n          h: Math.max(0, r.h - strip - 2),\n        });\n      });\n    }\n    return out;\n  }, [groups, focus, width, h]);\n\n  const groupRects = React.useMemo(() => {\n    if (!width || focus !== null) return [];\n    const totals = groups.map((g) =>\n      g.children.reduce((t, c) => t + c.value, 0),\n    );\n    return squarify(totals, { x: 0, y: 0, w: width, h });\n  }, [groups, focus, width, h]);\n\n  // Animate tiles between layouts (drilling in and out): the layout on screen is captured when the\n  // visitor drills, and each tile eases from its old rect to its new one.\n  const prev = React.useRef<Map<string, Rect>>(new Map());\n  const [from, setFrom] = React.useState<Map<string, Rect> | null>(null);\n  const [morph, setMorph] = React.useState(1);\n  const drill = (next: number | null) => {\n    if (next === focus) return;\n    setActive(null);\n    if (!reduce) {\n      setFrom(new Map(prev.current));\n      setMorph(0);\n    }\n    setFocus(next);\n  };\n  React.useEffect(() => {\n    if (!from) return;\n    let raf = 0;\n    const start = performance.now();\n    const tick = (now: number) => {\n      const k = Math.min(1, (now - start) / 520);\n      setMorph(k);\n      if (k < 1) raf = requestAnimationFrame(tick);\n    };\n    raf = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(raf);\n  }, [from]);\n  React.useEffect(() => {\n    prev.current = new Map(\n      tiles.map((t) => [t.id, { x: t.x, y: t.y, w: t.w, h: t.h }]),\n    );\n  });\n  const e = 1 - Math.pow(1 - morph, 3);\n  const shown = tiles.map((t) => {\n    const f = from?.get(t.id);\n    if (!from || morph >= 1) return { ...t, fade: 1 };\n    // Tiles that weren't on screen before (other regions, when zooming out) fade in instead.\n    if (!f) return { ...t, fade: e };\n    return {\n      ...t,\n      x: f.x + (t.x - f.x) * e,\n      y: f.y + (t.y - f.y) * e,\n      w: f.w + (t.w - f.w) * e,\n      h: f.h + (t.h - f.h) * e,\n      fade: 1,\n    };\n  });\n\n  const fill = (t: Tile) => {\n    if (colorBy === \"change\" && t.change !== undefined) {\n      const k = Math.max(-1, Math.min(1, t.change / changeRange));\n      const to = k >= 0 ? pal.pos : pal.neg;\n      const m = Math.pow(Math.abs(k), 0.75);\n      return `rgb(${pal.neutral.map((v, i) => Math.round(v + (to[i] - v) * m)).join(\",\")})`;\n    }\n    return pal.series[t.g % pal.series.length];\n  };\n\n  const order = shown.map((t) => t.id);\n  const onKey = (event: React.KeyboardEvent) => {\n    if (event.key === \"Escape\") {\n      if (active) setActive(null);\n      else if (focus !== null) drill(null);\n      return;\n    }\n    if (event.key === \"Enter\" && active && focus === null) {\n      drill(Number(active.split(\":\")[0]));\n      return;\n    }\n    if (\n      ![\"ArrowRight\", \"ArrowLeft\", \"ArrowDown\", \"ArrowUp\"].includes(\n        event.key,\n      ) ||\n      !order.length\n    )\n      return;\n    event.preventDefault();\n    const dir =\n      event.key === \"ArrowRight\" || event.key === \"ArrowDown\" ? 1 : -1;\n    const at = active ? order.indexOf(active) : -1;\n    setActive(order[(at + dir + order.length) % order.length] ?? null);\n  };\n\n  const at = shown.find((t) => t.id === active) ?? null;\n  const groupTotal = (g: number) =>\n    groups[g].children.reduce((s, c) => s + c.value, 0);\n  const viewTotal = focus !== null ? groupTotal(focus) : grand;\n  const tipLeft = at\n    ? Math.max(0, Math.min(width - 196, at.x + at.w / 2 - 98))\n    : 0;\n  const tipTop = at\n    ? at.y + at.h + 120 < h\n      ? at.y + Math.min(at.h, 60) + 6\n      : Math.max(0, at.y - 116)\n    : 0;\n  const summary = `${title}. ${groups.map((g) => `${g.label} ${formatValue(groupTotal(groups.indexOf(g)))}: ${g.children.map((c) => `${c.label} ${formatValue(c.value)}${c.change !== undefined ? ` (${formatChange(c.change)})` : \"\"}`).join(\", \")}`).join(\"; \")}.`;\n\n  return (\n    <div\n      className={cn(\n        \"w-full overflow-hidden rounded-[20px] p-5 sm:p-7\",\n        className,\n      )}\n      style={{\n        background: pal.card,\n        border: `1px solid ${pal.border}`,\n        color: pal.text,\n        fontFamily: \"Inter, -apple-system, BlinkMacSystemFont, sans-serif\",\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-4\">\n        <div className=\"min-w-0\">\n          <p className=\"text-[15px] font-semibold tracking-[-0.01em]\">\n            {title}\n          </p>\n          {subtitle && (\n            <p className=\"mt-1 text-[12.5px]\" style={{ color: pal.sub }}>\n              {subtitle}\n            </p>\n          )}\n        </div>\n        <div className=\"text-right\">\n          <p className=\"text-[22px] leading-none font-semibold tracking-[-0.02em] tabular-nums\">\n            {formatValue(viewTotal)}\n          </p>\n          <p className=\"mt-1 text-[11.5px]\" style={{ color: pal.sub }}>\n            {focus !== null\n              ? `${groups[focus].label}, ${((viewTotal / grand) * 100).toFixed(0)}% of total`\n              : \"Total\"}\n          </p>\n        </div>\n      </div>\n\n      <div className=\"mt-4 flex min-h-7 flex-wrap items-center justify-between gap-3\">\n        <nav\n          aria-label=\"Treemap level\"\n          className=\"flex items-center gap-1.5 text-[12.5px] font-medium\"\n        >\n          <button\n            type=\"button\"\n            onClick={() => drill(null)}\n            disabled={focus === null}\n            className=\"cursor-pointer rounded-md px-1.5 py-0.5 disabled:cursor-default\"\n            style={{\n              color: focus === null ? pal.text : pal.sub,\n              background: focus === null ? pal.chip : \"transparent\",\n            }}\n          >\n            All regions\n          </button>\n          {focus !== null && (\n            <>\n              <span style={{ color: pal.sub }}>/</span>\n              <span\n                className=\"rounded-md px-1.5 py-0.5\"\n                style={{ background: pal.chip }}\n                aria-current=\"page\"\n              >\n                {groups[focus].label}\n              </span>\n            </>\n          )}\n        </nav>\n        {colorBy === \"change\" && (\n          <div\n            className=\"flex items-center gap-2 text-[11px] tabular-nums\"\n            style={{ color: pal.sub }}\n          >\n            {formatChange(-changeRange)}\n            <span\n              className=\"h-2 w-28 rounded-full\"\n              style={{\n                background: `linear-gradient(90deg, rgb(${pal.neg.join(\",\")}), rgb(${pal.neutral.join(\",\")}), rgb(${pal.pos.join(\",\")}))`,\n              }}\n            />\n            {formatChange(changeRange)}\n          </div>\n        )}\n      </div>\n\n      <div\n        ref={boxRef}\n        role=\"img\"\n        aria-label={summary}\n        tabIndex={0}\n        onKeyDown={onKey}\n        onBlur={() => setActive(null)}\n        onPointerLeave={(ev) => ev.pointerType === \"mouse\" && setActive(null)}\n        className=\"relative mt-3 w-full overflow-hidden rounded-xl outline-none focus-visible:ring-2\"\n        style={{ height: h }}\n      >\n        {width > 0 && (\n          <>\n            {groupRects.map((r, g) =>\n              r.h > 60 && r.w > 70 ? (\n                <button\n                  key={groups[g].label}\n                  type=\"button\"\n                  tabIndex={-1}\n                  onClick={() => drill(g)}\n                  className=\"absolute flex cursor-zoom-in items-center gap-1.5 truncate px-2 text-left text-[11.5px] font-semibold\"\n                  style={{\n                    left: r.x,\n                    top: r.y,\n                    width: r.w,\n                    height: 22,\n                    color: pal.text,\n                    opacity: Math.min(1, reveal * 2),\n                  }}\n                >\n                  <span className=\"truncate\">{groups[g].label}</span>\n                  <span\n                    className=\"shrink-0 font-normal tabular-nums\"\n                    style={{ color: pal.sub }}\n                  >\n                    {formatValue(groupTotal(g))}\n                  </span>\n                </button>\n              ) : null,\n            )}\n            {shown.map((t, i) => {\n              const k = Math.min(\n                1,\n                Math.max(\n                  0,\n                  reveal * 1.8 - (i / Math.max(1, shown.length)) * 0.8,\n                ),\n              );\n              const big = t.w > 84 && t.h > 52;\n              const mid = !big && t.w > 46 && t.h > 24;\n              return (\n                <div\n                  key={t.id}\n                  onPointerEnter={() => setActive(t.id)}\n                  onPointerDown={() => setActive(t.id)}\n                  onClick={() => focus === null && drill(t.g)}\n                  className={cn(\n                    \"absolute overflow-hidden rounded-[6px] p-2\",\n                    focus === null ? \"cursor-zoom-in\" : \"cursor-default\",\n                  )}\n                  style={{\n                    left: t.x + 1,\n                    top: t.y + 1,\n                    width: Math.max(0, t.w - 2),\n                    height: Math.max(0, t.h - 2),\n                    background: fill(t),\n                    color: pal.tileText,\n                    opacity: k * t.fade * (active && active !== t.id ? 0.7 : 1),\n                    transform: `scale(${0.92 + 0.08 * k})`,\n                    boxShadow:\n                      active === t.id\n                        ? `inset 0 0 0 2px ${theme === \"dark\" ? \"#fff\" : \"#111317\"}`\n                        : \"none\",\n                    transition: \"opacity 160ms, box-shadow 160ms\",\n                  }}\n                >\n                  {big && (\n                    <>\n                      <p className=\"truncate text-[12.5px] font-semibold\">\n                        {t.label}\n                      </p>\n                      <p className=\"mt-0.5 truncate text-[17px] font-semibold tracking-[-0.02em] tabular-nums\">\n                        {formatValue(t.value)}\n                      </p>\n                      {t.change !== undefined && (\n                        <p className=\"mt-0.5 text-[11px] font-medium tabular-nums opacity-80\">\n                          {formatChange(t.change)}\n                        </p>\n                      )}\n                    </>\n                  )}\n                  {mid && (\n                    <p className=\"truncate text-[11px] font-semibold\">\n                      {t.label}\n                    </p>\n                  )}\n                </div>\n              );\n            })}\n            {at && (\n              <div\n                className=\"pointer-events-none absolute z-10 w-[196px] rounded-xl px-3 py-2.5 text-[12px] shadow-xl\"\n                style={{\n                  left: tipLeft,\n                  top: tipTop,\n                  background: pal.tip,\n                  border: `1px solid ${pal.tipBorder}`,\n                  backdropFilter: \"blur(8px)\",\n                  color: pal.text,\n                }}\n              >\n                <p className=\"font-semibold\">\n                  {at.label}{\" \"}\n                  <span className=\"font-normal\" style={{ color: pal.sub }}>\n                    · {groups[at.g].label}\n                  </span>\n                </p>\n                {(\n                  [\n                    [\"Revenue\", formatValue(at.value)],\n                    [\n                      \"Share of region\",\n                      `${((at.value / groupTotal(at.g)) * 100).toFixed(1)}%`,\n                    ],\n                    [\n                      \"Share of total\",\n                      `${((at.value / grand) * 100).toFixed(1)}%`,\n                    ],\n                    ...(at.change !== undefined\n                      ? [[\"Growth\", formatChange(at.change)]]\n                      : []),\n                  ] as [string, string][]\n                ).map(([k2, v]) => (\n                  <div key={k2} className=\"mt-1 flex justify-between gap-3\">\n                    <span style={{ color: pal.sub }}>{k2}</span>\n                    <span className=\"font-semibold tabular-nums\">{v}</span>\n                  </div>\n                ))}\n                {focus === null && (\n                  <p\n                    className=\"mt-2 border-t pt-1.5 text-[11px]\"\n                    style={{ borderColor: pal.tipBorder, color: pal.sub }}\n                  >\n                    Click to zoom into {groups[at.g].label}\n                  </p>\n                )}\n              </div>\n            )}\n          </>\n        )}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}