{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "treemap",
  "title": "Treemap",
  "description": "Squarified treemap whose tinted tiles fade in largest first and spring to a new layout when values change, with labels only where they fit, a tooltip and arrow-key tiles.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/charts/treemap.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { motion, useReducedMotion } from \"motion/react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens, spring as springs, ease as easing } from \"@/lib/goodui-motion\"\n\nexport type TreemapItem = {\n  /** Defaults to the label. */\n  key?: string\n  label: string\n  value: number\n  /** Any CSS color. Defaults to the theme chart colors by size order (--chart-1 … --chart-5, then lighter tints). */\n  color?: string\n}\n\nexport type TreemapLabels = {\n  summary: (name: string, count: number, total: string) => string\n  /** Announced for the active tile. */\n  item: (label: string, value: string, share: string) => string\n  columnLabel: string\n  columnValue: string\n  columnShare: string\n  noData: string\n}\nconst DEFAULT_LABELS: TreemapLabels = {\n  summary: (name, count, total) => `${name ? name + \": \" : \"\"}${count} items, total ${total}`,\n  item: (label, value, share) => `${label}: ${value}, ${share}`,\n  columnLabel: \"Label\",\n  columnValue: \"Value\",\n  columnShare: \"Share\",\n  noData: \"No data\",\n}\n\nexport type TreemapProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n  data: TreemapItem[]\n  /** Chart name for screen readers and the table caption. */\n  title?: React.ReactNode\n  /** Height in px. The width follows the container. */\n  height?: number\n  /** Surface gap between tiles in px. */\n  gap?: number\n  radius?: number\n  /** Print each tile's value under its label when there is room. */\n  showValues?: boolean\n  /** Print each tile's share instead of (or next to) the value. */\n  showShare?: boolean\n  format?: Intl.NumberFormatOptions\n  locale?: string\n  formatValue?: (value: number) => string\n  /** Seconds the layout takes to settle in; tiles stagger by 40 ms. */\n  duration?: number\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<TreemapLabels>\n}\n\nfunction useReduce() {\n  const prefers = useReducedMotion()\n  const [mounted, setMounted] = React.useState(false)\n  React.useEffect(() => setMounted(true), [])\n  return mounted && !!prefers\n}\n\nfunction useInView(ref: React.RefObject<Element | null>, threshold = 0.2) {\n  const [inView, setInView] = React.useState(false)\n  React.useEffect(() => {\n    const el = ref.current\n    if (!el || inView) return\n    if (typeof IntersectionObserver === \"undefined\") {\n      setInView(true)\n      return\n    }\n    const io = new IntersectionObserver(\n      ([e]) => {\n        if (e?.isIntersecting) {\n          setInView(true)\n          io.disconnect()\n        }\n      },\n      { threshold },\n    )\n    io.observe(el)\n    return () => io.disconnect()\n  }, [ref, inView, threshold])\n  return inView\n}\n\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState<number | null>(null)\n  React.useLayoutEffect(() => {\n    const el = ref.current\n    if (!el) return\n    // A hidden parent (display:none) measures 0: keep the last real width instead of collapsing the chart.\n    const measure = () => {\n      const w = Math.round(el.clientWidth)\n      if (w > 0) setWidth(Math.max(120, w))\n    }\n    measure()\n    const ro = new ResizeObserver(measure)\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [ref])\n  return width\n}\n\ntype Rect = { x: number; y: number; w: number; h: number }\n\n/** Squarified treemap (Bruls, Huizing, van Wijk): rows are laid along the shorter side while the worst aspect ratio keeps improving. */\nfunction squarify(values: number[], rect: Rect): Rect[] {\n  const total = values.reduce((s, v) => s + v, 0)\n  const out: Rect[] = values.map(() => ({ x: rect.x, y: rect.y, w: 0, h: 0 }))\n  if (total <= 0 || rect.w <= 0 || rect.h <= 0) return out\n  const areas = values.map((v) => (v / total) * rect.w * rect.h)\n  let { x, y, w, h } = rect\n  let i = 0\n  while (i < areas.length) {\n    const vertical = w >= h\n    const side = vertical ? h : w\n    let count = 0\n    let sum = 0\n    let best = Infinity\n    let lo = Infinity\n    let hi = 0\n    for (let j = i; j < areas.length; j++) {\n      const a = areas[j] ?? 0\n      const s = sum + a\n      const mn = Math.min(lo, a)\n      const mx = Math.max(hi, a)\n      const worst = Math.max((side * side * mx) / (s * s), (s * s) / (side * side * mn))\n      if (count > 0 && worst > best) break\n      count++\n      sum = s\n      lo = mn\n      hi = mx\n      best = worst\n    }\n    if (vertical) {\n      const rw = side > 0 ? sum / side : 0\n      let yy = y\n      for (let j = i; j < i + count; j++) {\n        const rh = rw > 0 ? (areas[j] ?? 0) / rw : 0\n        out[j] = { x, y: yy, w: rw, h: rh }\n        yy += rh\n      }\n      x += rw\n      w -= rw\n    } else {\n      const rh = side > 0 ? sum / side : 0\n      let xx = x\n      for (let j = i; j < i + count; j++) {\n        const rw = rh > 0 ? (areas[j] ?? 0) / rh : 0\n        out[j] = { x: xx, y, w: rw, h: rh }\n        xx += rw\n      }\n      y += rh\n      h -= rh\n    }\n    i += count\n  }\n  return out\n}\n\n/** Squarified treemap whose tiles spring to a new layout when values change, with labels that only show where they fit, hover and arrow-key tooltips. */\nexport function Treemap({\n  data,\n  title,\n  height = 240,\n  gap = 3,\n  radius = 6,\n  showValues = true,\n  showShare = false,\n  format,\n  locale = \"en-US\",\n  formatValue,\n  duration = 0.8,\n  labels,\n  className,\n  \"aria-label\": ariaLabel,\n  ...props\n}: TreemapProps) {\n  const l = useLabels(\"treemap\", DEFAULT_LABELS, labels)\n  const reduce = useReduce()\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const plotRef = React.useRef<HTMLDivElement>(null)\n  const inView = useInView(rootRef)\n  const width = useWidth(plotRef)\n  const [active, setActive] = React.useState<string | null>(null)\n  const fmt = React.useMemo(() => formatValue ?? ((v: number) => new Intl.NumberFormat(locale, format).format(v)), [formatValue, locale, format])\n  const pct = React.useMemo(() => new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 0 }), [locale])\n\n  const W = width ?? 0\n  const items = data\n    .map((d, i) => ({ ...d, key: d.key ?? d.label, index: i }))\n    .filter((d) => d.value > 0)\n    .sort((a, b) => b.value - a.value)\n  const total = items.reduce((s, d) => s + d.value, 0)\n  const rects = squarify(\n    items.map((d) => d.value),\n    { x: -gap / 2, y: -gap / 2, w: W + gap, h: height + gap },\n  )\n  const tiles = items.map((d, i) => {\n    const r = rects[i] ?? { x: 0, y: 0, w: 0, h: 0 }\n    const base = `var(--chart-${(i % 5) + 1})`\n    const color = d.color ?? (i < 5 ? base : `color-mix(in oklab, ${base} ${Math.max(35, 75 - Math.floor(i / 5) * 20)}%, var(--background))`)\n    return { ...d, color, share: total > 0 ? d.value / total : 0, x: r.x + gap / 2, y: r.y + gap / 2, w: Math.max(0, r.w - gap), h: Math.max(0, r.h - gap) }\n  })\n  const name = typeof title === \"string\" ? title : \"\"\n  const summary = ariaLabel ?? (tiles.length ? l.summary(name, tiles.length, fmt(total)) : l.noData)\n  const act = active !== null ? tiles.find((t) => t.key === active) : undefined\n  const announce = act ? l.item(act.label, fmt(act.value), pct.format(act.share)) : \"\"\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (!tiles.length) return\n    if ([\"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", \"ArrowDown\"].includes(e.key)) {\n      e.preventDefault()\n      const dir = e.key === \"ArrowLeft\" || e.key === \"ArrowUp\" ? -1 : 1\n      const i = tiles.findIndex((t) => t.key === active)\n      setActive(tiles[(i + dir + tiles.length) % tiles.length]?.key ?? null)\n    } else if (e.key === \"Home\" || e.key === \"End\") {\n      e.preventDefault()\n      setActive((e.key === \"Home\" ? tiles[0] : tiles[tiles.length - 1])?.key ?? null)\n    } else if (e.key === \"Escape\") setActive(null)\n  }\n\n  const ready = inView || reduce\n  // A container resize re-packs the tiles at once; only data changes animate.\n  const widthRef = React.useRef(W)\n  const resized = widthRef.current !== W\n  widthRef.current = W\n  const spring = reduce || resized ? { duration: 0 } : springs.morph\n  const tipX = act ? act.x + act.w / 2 : 0\n  const tipY = act ? act.y : 0\n  const tipRight = tipX > W * 0.55\n  const tipBelow = tipY < 40\n\n  return (\n    <div ref={rootRef} className={cn(\"pc-treemap flex w-full min-w-0 flex-col gap-2\", className)} {...props}>\n      <GooduiTokens />\n      <div\n        ref={plotRef}\n        role=\"group\"\n        aria-roledescription=\"treemap\"\n        aria-label={summary}\n        tabIndex={0}\n        onKeyDown={onKeyDown}\n        onFocus={() => setActive((k) => k ?? (tiles[0]?.key ?? null))}\n        onBlur={() => setActive(null)}\n        onPointerLeave={() => setActive(null)}\n        className=\"relative w-full rounded-md outline-none focus-visible:ring-3 focus-visible:ring-ring/50\"\n        style={{ height }}\n      >\n        {width !== null && tiles.length > 0 && (\n          <svg width={W} height={height} viewBox={`0 0 ${W} ${height}`} className=\"absolute inset-0\" aria-hidden=\"true\">\n            {tiles.map((t, i) => {\n              const isActive = active === t.key\n              const label = t.w >= t.label.length * 6.6 + 16 && t.h >= 26\n              const second = label && t.h >= 46 && (showValues || showShare)\n              const secondText = [showValues ? fmt(t.value) : null, showShare ? pct.format(t.share) : null].filter(Boolean).join(\" · \")\n              return (\n                <motion.g\n                  key={t.key}\n                  initial={false}\n                  animate={{ x: t.x, y: t.y, opacity: ready ? 1 : 0, scale: ready ? 1 : 0.85 }}\n                  transition={{ x: spring, y: spring, opacity: reduce ? { duration: 0 } : { duration: 0.3, delay: i * 0.04 }, scale: reduce ? { duration: 0 } : { duration, delay: i * 0.04, ease: easing.outExpo } }}\n                  className=\"cursor-pointer\"\n                  onPointerEnter={() => setActive(t.key)}\n                >\n                  <motion.rect\n                    rx={radius}\n                    initial={false}\n                    animate={{ width: Math.max(0, t.w), height: Math.max(0, t.h) }}\n                    transition={{ width: spring, height: spring }}\n                    style={{ fill: `color-mix(in oklab, ${t.color} ${isActive ? 34 : 22}%, var(--card))`, transition: reduce ? undefined : \"fill .2s\" }}\n                    className={cn(isActive && \"stroke-foreground/40\")}\n                    strokeWidth={isActive ? 1 : 0}\n                  />\n                  <motion.rect y={0} height={3} rx={1.5} initial={false} animate={{ width: Math.max(0, t.w - radius * 2) }} transition={{ width: spring }} x={radius} style={{ fill: t.color }} />\n                  {label && (\n                    <text x={9} y={20} className=\"fill-foreground text-[12px] font-medium\">\n                      {t.label}\n                    </text>\n                  )}\n                  {second && (\n                    <text x={9} y={36} className=\"fill-muted-foreground text-[11px] tabular-nums\">\n                      {secondText}\n                    </text>\n                  )}\n                </motion.g>\n              )\n            })}\n          </svg>\n        )}\n        {width !== null && tiles.length === 0 && <div className=\"absolute inset-0 grid place-items-center text-sm text-muted-foreground\">{l.noData}</div>}\n        {act && (\n          <div\n            className=\"pointer-events-none absolute z-10 flex flex-col gap-0.5 rounded-md border bg-popover px-2.5 py-1.5 text-xs whitespace-nowrap text-popover-foreground shadow-[var(--pc-e2)]\"\n            style={{ left: tipX, top: tipY, transform: `translate(${tipRight ? \"calc(-100% - 10px)\" : \"10px\"}, ${tipBelow ? \"8px\" : \"calc(-100% - 6px)\"})` }}\n          >\n            <span className=\"flex items-center gap-1.5 text-muted-foreground\">\n              <span className=\"inline-block size-2 rounded-[2px]\" style={{ background: act.color }} />\n              {act.label}\n            </span>\n            <span className=\"font-semibold tabular-nums\">\n              {fmt(act.value)} <span className=\"font-normal text-muted-foreground\">· {pct.format(act.share)}</span>\n            </span>\n          </div>\n        )}\n        <span className=\"sr-only\" aria-live=\"polite\">\n          {announce}\n        </span>\n      </div>\n      {tiles.length > 0 && (\n        <div className=\"sr-only\">\n          <table>\n          <caption>{summary}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">{l.columnLabel}</th>\n              <th scope=\"col\">{l.columnValue}</th>\n              <th scope=\"col\">{l.columnShare}</th>\n            </tr>\n          </thead>\n          <tbody>\n            {tiles.map((t) => (\n              <tr key={t.key}>\n                <th scope=\"row\">{t.label}</th>\n                <td>{fmt(t.value)}</td>\n                <td>{pct.format(t.share)}</td>\n              </tr>\n            ))}\n          </tbody>\n        </table>\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/treemap.tsx"
    }
  ],
  "categories": [
    "components",
    "charts"
  ],
  "type": "registry:component"
}