{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "treemap",
  "type": "registry:item",
  "title": "Treemap",
  "description": "Sizes as nested, near-square tiles; tap a group and the map zooms into it as its parts open out inside.",
  "categories": [
    "data"
  ],
  "dependencies": [
    "react-native-reanimated",
    "react-native-worklets"
  ],
  "registryDependencies": [
    "https://kinetik-ui.dev/r/kinetik-tokens.json",
    "https://kinetik-ui.dev/r/kinetik-motion.json"
  ],
  "files": [
    {
      "path": "src/components/kinetik/treemap.tsx",
      "type": "registry:file",
      "target": "~/components/kinetik/treemap.tsx",
      "content": "import { useEffect, useMemo, useState } from 'react';\nimport { Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from 'react-native';\nimport Animated, { useAnimatedStyle, useSharedValue, withSpring } from 'react-native-reanimated';\n\nimport { useReduceMotion } from '../../lib/kinetik/hooks/use-reduce-motion';\nimport { spring } from '../../lib/kinetik/motion/motion';\nimport { useKinetikTheme } from '../../lib/kinetik/tokens/theme';\nimport { withAlpha } from '../../lib/kinetik/tokens/tokens';\n\nexport type TreemapNode = {\n  key: string;\n  label: string;\n  /** Leaf size. Ignored when `children` is set; a parent's size is the sum of its children. */\n  value?: number;\n  children?: readonly TreemapNode[];\n};\n\nexport type TreemapProps = {\n  data: readonly TreemapNode[];\n  /** Height of the map. Defaults to 280. */\n  height?: number;\n  /** Formats sizes on tiles. Defaults to whole numbers. */\n  formatValue?: (value: number) => string;\n  /** Names the top level in the trail, e.g. \"All spending\". Defaults to 'All'. */\n  rootLabel?: string;\n  /** What the map shows, read first. */\n  accessibilityLabel: string;\n  testID?: string;\n  style?: StyleProp<ViewStyle>;\n};\n\nexport type Rect = { x: number; y: number; w: number; h: number };\n\nconst GAP = 3;\n\nexport function nodeValue(node: TreemapNode): number {\n  return node.children\n    ? node.children.reduce((a, c) => a + nodeValue(c), 0)\n    : Math.max(0, node.value ?? 0);\n}\n\n/** Squarified treemap layout (Bruls, Huizing and van Wijk): tiles as close to square as it can. */\nexport function squarify(values: readonly number[], rect: Rect): Rect[] {\n  const out = new Array<Rect>(values.length);\n  const total = values.reduce((a, b) => a + b, 0);\n  if (total <= 0 || rect.w <= 0 || rect.h <= 0) {\n    values.forEach((_, i) => (out[i] = { x: rect.x, y: rect.y, w: 0, h: 0 }));\n    return out;\n  }\n  const order = values\n    .map((v, i) => ({ i, a: (v / total) * rect.w * rect.h }))\n    .sort((p, q) => q.a - p.a);\n  let { x, y, w, h } = rect;\n\n  const worst = (row: number[], side: number) => {\n    const s = row.reduce((a, b) => a + b, 0);\n    const max = Math.max(...row);\n    const min = Math.min(...row);\n    return Math.max((side * side * max) / (s * s), (s * s) / (side * side * min));\n  };\n  const place = (row: { i: number; a: number }[]) => {\n    const s = row.reduce((acc, r) => acc + 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\n  let row: { i: number; a: number }[] = [];\n  for (const item of order) {\n    if (item.a <= 0) {\n      out[item.i] = { x, y, w: 0, h: 0 };\n      continue;\n    }\n    const side = Math.min(w, h);\n    const areas = row.map((r) => r.a);\n    if (row.length === 0 || worst([...areas, item.a], side) <= worst(areas, 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\n/** Maps a rect inside `from` to the same place inside `to`. */\nfunction remap(r: Rect, from: Rect, to: Rect): Rect {\n  const sx = to.w / (from.w || 1);\n  const sy = to.h / (from.h || 1);\n  return { x: to.x + (r.x - from.x) * sx, y: to.y + (r.y - from.y) * sy, w: r.w * sx, h: r.h * sy };\n}\n\n/**\n * Sizes as nested tiles, each as square as it can be. Tap a tile with parts\n * and the map zooms into it: the tile grows to fill the frame while its parts\n * open out inside. The trail above zooms back out the same way.\n */\nexport function Treemap({\n  data,\n  height = 280,\n  formatValue = (v) => String(Math.round(v)),\n  rootLabel = 'All',\n  accessibilityLabel,\n  testID,\n  style,\n}: TreemapProps) {\n  const { colors, font, radius, space } = useKinetikTheme();\n  const reduced = useReduceMotion();\n  const [width, setWidth] = useState(0);\n  // The drilled path, and where the last zoom started from, so new tiles can grow out of it.\n  const [path, setPath] = useState<TreemapNode[]>([]);\n  const [origin, setOrigin] = useState<{ rect: Rect; zoomIn: boolean } | null>(null);\n  const frame: Rect = { x: 0, y: 0, w: width, h: height };\n\n  const nodes = useMemo(\n    () => (path.length ? (path[path.length - 1]!.children ?? []) : data),\n    [path, data],\n  );\n  const total = nodes.reduce((a, n) => a + nodeValue(n), 0);\n  const rects = useMemo(\n    () => squarify(nodes.map(nodeValue), { x: 0, y: 0, w: width, h: height }),\n    [nodes, width, height],\n  );\n  // Shades by rank: the biggest tile is solid azure, the smallest a pale wash.\n  const rank = useMemo(() => {\n    const sorted = nodes.map((n, i) => ({ i, v: nodeValue(n) })).sort((a, b) => b.v - a.v);\n    const r = new Array<number>(nodes.length);\n    sorted.forEach((s, k) => (r[s.i] = nodes.length > 1 ? k / (nodes.length - 1) : 0));\n    return r;\n  }, [nodes]);\n\n  const zoomInto = (node: TreemapNode, rect: Rect) => {\n    setOrigin({ rect, zoomIn: true });\n    setPath((p) => [...p, node]);\n  };\n  const zoomTo = (depth: number) => {\n    if (depth >= path.length) return;\n    // The tile we leave becomes small again inside its parent's layout.\n    const parentNodes = depth === 0 ? data : (path[depth - 1]!.children ?? []);\n    const child = path[depth]!;\n    const parentRects = squarify(parentNodes.map(nodeValue), frame);\n    const at = parentNodes.findIndex((n) => n.key === child.key);\n    setOrigin({ rect: parentRects[at] ?? frame, zoomIn: false });\n    setPath((p) => p.slice(0, depth));\n  };\n\n  const trail = [rootLabel, ...path.map((p) => p.label)];\n\n  return (\n    <View testID={testID} style={[{ gap: space[2] }, style]}>\n      <View style={styles.trail} accessibilityRole=\"toolbar\" accessibilityLabel=\"Treemap level\">\n        {trail.map((label, depth) => {\n          const current = depth === trail.length - 1;\n          return (\n            <View key={`${depth}-${label}`} style={styles.crumb}>\n              {depth > 0 ? (\n                <Text style={{ color: colors.textSubtle, fontSize: font.size.sm }}>›</Text>\n              ) : null}\n              <Pressable\n                disabled={current}\n                onPress={() => zoomTo(depth)}\n                accessibilityRole=\"button\"\n                accessibilityLabel={current ? `${label}, current level` : `Back to ${label}`}\n                style={styles.crumbHit}\n              >\n                <Text\n                  style={{\n                    color: current ? colors.text : colors.azure,\n                    fontSize: font.size.sm,\n                    fontWeight: current ? font.weight.semibold : font.weight.medium,\n                  }}\n                >\n                  {label}\n                </Text>\n              </Pressable>\n            </View>\n          );\n        })}\n      </View>\n\n      <View\n        accessibilityLabel={accessibilityLabel}\n        onLayout={(e) => setWidth(e.nativeEvent.layout.width)}\n        style={[styles.frame, { height, borderRadius: radius.lg }]}\n      >\n        {width > 0\n          ? nodes.map((node, i) => {\n              const to = rects[i]!;\n              // New tiles start where the zoom left them: inside the tapped tile, or\n              // spread wide around the tile we are leaving.\n              const from = origin\n                ? origin.zoomIn\n                  ? remap(to, frame, origin.rect)\n                  : remap(to, origin.rect, frame)\n                : to;\n              const value = nodeValue(node);\n              const share = total > 0 ? value / total : 0;\n              const strength = 1 - rank[i]! * 0.7;\n              return (\n                <Tile\n                  key={`${path.length}-${node.key}`}\n                  from={from}\n                  to={to}\n                  reduced={reduced}\n                  background={withAlpha(colors.azure, strength)}\n                  ink={strength > 0.55 ? colors.onAzure : colors.text}\n                  label={node.label}\n                  value={formatValue(value)}\n                  share={share}\n                  hasParts={Boolean(node.children?.length)}\n                  radius={radius.sm}\n                  onPress={node.children?.length ? () => zoomInto(node, to) : undefined}\n                />\n              );\n            })\n          : null}\n      </View>\n    </View>\n  );\n}\n\ntype TileProps = {\n  from: Rect;\n  to: Rect;\n  reduced: boolean;\n  background: string;\n  ink: string;\n  label: string;\n  value: string;\n  share: number;\n  hasParts: boolean;\n  radius: number;\n  onPress?: () => void;\n};\n\nfunction Tile({\n  from,\n  to,\n  reduced,\n  background,\n  ink,\n  label,\n  value,\n  share,\n  hasParts,\n  radius,\n  onPress,\n}: TileProps) {\n  const { font } = useKinetikTheme();\n  const x = useSharedValue(from.x);\n  const y = useSharedValue(from.y);\n  const w = useSharedValue(from.w);\n  const h = useSharedValue(from.h);\n  const fade = useSharedValue(reduced ? 1 : 0);\n\n  useEffect(() => {\n    const cfg = spring('smooth', reduced);\n    x.set(withSpring(to.x, cfg));\n    y.set(withSpring(to.y, cfg));\n    w.set(withSpring(to.w, cfg));\n    h.set(withSpring(to.h, cfg));\n    fade.set(withSpring(1, cfg));\n  }, [to.x, to.y, to.w, to.h, reduced, x, y, w, h, fade]);\n\n  const style = useAnimatedStyle(() => ({\n    left: x.get() + GAP / 2,\n    top: y.get() + GAP / 2,\n    width: Math.max(0, w.get() - GAP),\n    height: Math.max(0, h.get() - GAP),\n    opacity: fade.get(),\n  }));\n\n  const roomy = to.w > 64 && to.h > 44;\n  const percent = `${Math.round(share * 100)}%`;\n  const name = `${label}, ${value}, ${percent}${hasParts ? ', has parts' : ''}`;\n  const content = roomy ? (\n    <>\n      <Text\n        numberOfLines={1}\n        style={{ color: ink, fontSize: font.size.sm, fontWeight: font.weight.semibold }}\n      >\n        {label}\n      </Text>\n      <Text\n        numberOfLines={1}\n        style={{ color: ink, opacity: 0.8, fontSize: font.size.xs, fontVariant: ['tabular-nums'] }}\n      >\n        {value} · {percent}\n      </Text>\n    </>\n  ) : null;\n\n  return (\n    <Animated.View\n      style={[styles.tile, { backgroundColor: background, borderRadius: radius }, style]}\n    >\n      {onPress ? (\n        <Pressable\n          onPress={onPress}\n          accessibilityRole=\"button\"\n          accessibilityLabel={name}\n          accessibilityHint=\"Zooms in\"\n          style={styles.press}\n        >\n          {content}\n        </Pressable>\n      ) : (\n        // Leaves only show their size, so they are text, not a control.\n        <View accessible accessibilityRole=\"text\" accessibilityLabel={name} style={styles.press}>\n          {content}\n        </View>\n      )}\n    </Animated.View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  trail: { flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center', minHeight: 24 },\n  // 44 pt tall to the finger; the negative margin keeps the trail compact.\n  crumbHit: { minHeight: 44, justifyContent: 'center', marginVertical: -10 },\n  crumb: { flexDirection: 'row', alignItems: 'center', gap: 6, marginRight: 6 },\n  frame: { overflow: 'hidden' },\n  tile: { position: 'absolute', overflow: 'hidden' },\n  press: { flex: 1, padding: 8, gap: 2 },\n});\n"
    }
  ],
  "meta": {
    "version": "1.0.0",
    "kind": "component",
    "platforms": [
      "ios",
      "android",
      "web"
    ],
    "category": "data",
    "web": "live",
    "perf": {
      "budget": "Plain views laid out with a squarified algorithm in JS; each tile springs four values while zooming. Nothing runs at rest.",
      "measurements": [
        {
          "device": "Pixel 9 emulator, API 35",
          "kind": "emulator",
          "date": "2026-10-13",
          "build": "release",
          "frameMs": 17,
          "p90Ms": 22,
          "baselineMs": 20,
          "jankyPercent": 2.88,
          "atRest": "idle",
          "memoryMb": 145
        }
      ]
    },
    "a11y": {
      "reducedMotion": "Levels change in place, without the zoom.",
      "screenReader": "Every tile reads its label, size and share; groups are buttons that say they have parts. The trail above has a Back to button for each level.",
      "touchTarget": "Tiles are as big as their share; the trail's buttons are 44 pt tall. Keep small slices out of a tap-only flow."
    },
    "requires": "React Native New Architecture (Reanimated 4)",
    "guide": "## Usage\n\n```tsx\nimport { Treemap } from '@/components/kinetik/treemap';\n\n<Treemap\n  accessibilityLabel=\"Trip spending\"\n  rootLabel=\"All spending\"\n  data={[\n    {\n      key: 'stays',\n      label: 'Stays',\n      children: [\n        { key: 'flat', label: 'Lisbon flat', value: 920 },\n        { key: 'cabin', label: 'Lake cabin', value: 640 },\n      ],\n    },\n    { key: 'tours', label: 'Tours', value: 380 },\n  ]}\n  formatValue={(v) => `€${v}`}\n/>;\n```\n\nLeaves take a `value`; groups take `children` and are sized by their sum. Nesting can go as deep as you like; each level is one tap.\n\n## When to use\n\n- Seeing which parts of a whole are big at a glance: spending, storage, sales by region.\n- Hierarchies people want to explore a level at a time.\n\n## When not to use\n\n- Comparing similar sizes precisely. Areas are hard to compare; use Bar Chart.\n- Many tiny parts. Tiles too small for a label are drawn without one.\n\n## Notes\n\n- Tiles are laid out with the squarified algorithm, so they stay as close to square as the sizes allow. `squarify` and `nodeValue` are exported.\n- Tapping a group zooms in: the tapped tile grows to fill the frame while its parts open out inside it. The trail above zooms back out the same way.\n- Tiles are shaded by rank, from solid azure for the biggest to a pale wash for the smallest.\n- With reduced motion levels change in place.\n"
  },
  "docs": "Prefer `npx kinetik-ui add treemap`: it installs dependencies with expo install, so versions match your Expo SDK."
}
