{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "treemap-chart",
  "title": "Treemap chart",
  "description": "A whole as nested tiles, each as large as its value: groups with a header and their tiles inside, coloured by group or by a colour of your own, with each tile’s name and value written on it where they fit. A press on a group zooms into it until it fills the chart, and a path above it, or Escape, zooms back out. The tile under the pointer or the keys stays bright while the rest step back, and new data moves every tile from where it is.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/chart.json",
    "https://kinoui.com/r/chart-core.json",
    "https://kinoui.com/r/chart-root.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/chart-tiles.json",
    "https://kinoui.com/r/chart-tree-path.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/placeholder.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/treemap-chart.tsx",
      "content": "'use client'\n\nimport {\n  type CategoryChartProps,\n  type EntrancePhase,\n  figureProps,\n  IndexActive,\n  pickedName,\n  ShareTooltipContent,\n  useChartActive,\n  useChartLife,\n  useChartLoad,\n  useChartPick,\n  useIndexFocus,\n  useLeavingItems,\n} from '@/registry/lib/chart-base'\nimport type { ChartConfig, ChartDatum } from '@/registry/lib/chart-math'\nimport {\n  ChartFrame,\n  type ChartRootValue,\n  drawingSize,\n  forcedSeriesColor,\n  isMeasured,\n  labelOnClassName,\n  patternImage,\n  plotLayerClassName,\n  type PlotPoint,\n  stepBackInkClassName,\n  swatchClassName,\n  useChartRootValue,\n} from '@/registry/lib/chart-root'\nimport {\n  centreOf,\n  headerFit,\n  LABEL_PADDING,\n  labelFit,\n  type LaidTile,\n  tileAt,\n  type TileBox,\n  type TileLayout,\n  tileLayout,\n  tileMoves,\n  type TileNode,\n  tileTree,\n  topColor,\n  viewShape,\n  viewTiles,\n} from '@/registry/lib/chart-tiles'\nimport {\n  TreeZoomContext,\n  TreeZoomPath,\n  useTreeZoomRoot,\n} from '@/registry/lib/chart-tree-path'\nimport { treeItem, type TreeStop, treeReader } from '@/registry/lib/chart-tree-reader'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport {\n  placeholderBreatheClassName,\n  placeholderFillClassName,\n} from '@/registry/lib/placeholder'\nimport { type ComponentProps, type CSSProperties, memo, useState } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The Treemap chart: a whole as nested tiles, each as large as its value. A\n * row's `children` are its tiles, so the chart shows the groups of the part\n * in view, each with a header and its tiles inside, coloured by the top of\n * the tree they are under. A press on a group zooms into it until it fills\n * the chart, and the way back out, Escape, or the path above the chart zoom\n * out again. The tile under the pointer or the keys stays bright while the\n * rest step back, and new data moves every tile from where it is. Each tile\n * is a layer as large as the plot, cut to its box, so moving and resizing\n * it is one property that turns back from wherever it is.\n */\n\ninterface TreemapChartProps extends Omit<\n  CategoryChartProps,\n  | 'domain'\n  | 'tickCount'\n  | 'tickValues'\n  | 'allowDecimals'\n  | 'ordered'\n  | 'selected'\n  | 'defaultSelected'\n  | 'onSelectedChange'\n  | 'color'\n> {\n  /** The key of each row's value in the data. A row with `children` is worth them added up. */\n  dataKey: string\n  /** What the values are, such as \"Cost\": the tooltip's and the data table's word for them. */\n  valueLabel?: string\n  /** The part zoomed into, as the `index` values from the top down to it; `[]`, the whole, by default. */\n  zoom?: string[]\n  defaultZoom?: string[]\n  onZoomChange?: (zoom: string[]) => void\n  /** What each tile writes on itself, where it has the room: its name and value, its name, or nothing. */\n  labels?: 'value' | 'name' | 'none'\n  /** A tile's own colour, such as one for its value, in place of its group's; `undefined` keeps the group's. */\n  color?: (row: ChartDatum, index: number) => string | undefined\n  /**\n   * How the tiles arrive the first time the chart comes into view: growing\n   * from their centres, or simply there, the default, since a page that\n   * loads doesn't animate into place.\n   */\n  entrance?: 'draw' | 'none'\n}\n\nconst treemapChartKeys = [\n  'dataKey',\n  'valueLabel',\n  'zoom',\n  'defaultZoom',\n  'onZoomChange',\n  'labels',\n  'color',\n  'entrance',\n]\n\n/** The room between two groups, on top of the room between two tiles, in px. */\nconst GROUP_GAP = 4\n\n/** How far from a tile, in px, the pointer still lights it: across the room between groups. */\nconst NEAR_TILE = 8\n\n/** A tile the chart draws: a stop in view, or one leaving, which keeps its last place. */\ntype TreemapStop = TreeStop & { leaving: boolean }\n\n/**\n * The chart's root: the tree from the rows, the part of it in view, and its\n * tiles laid out in the plot, with the frame its path, legend and tooltip\n * draw in.\n */\nfunction TreemapChart(props: TreemapChartProps) {\n  const {\n    data,\n    index,\n    dataKey,\n    config,\n    valueLabel,\n    labels = 'value',\n    color,\n    entrance = 'none',\n    description,\n    empty,\n    className,\n    ref,\n  } = props\n  const tree = tileTree(data, index, dataKey)\n  const { state, groups, hidden, view, nameOf, valueOf, zoomTo } = useTreeZoomRoot(\n    props,\n    tree,\n    { entrance: entrance !== 'none' },\n  )\n  const { messages: words, valueText, locale, direction, moves } = state\n  /** A tile's name as the table and a screen reader give it: its group's label for a top. */\n  const stopName = (name: unknown) => {\n    if (props.categoryFormat) return props.categoryFormat(name)\n    const named = groups[String(name)]?.label\n    return typeof named === 'string' ? named : String(name)\n  }\n\n  // The tiles in view, in the order the keys step through them, but those of a hidden group.\n  const load = useChartLoad(props)\n  const inView = load.placeholder || load.failed ? [] : viewTiles(view)\n  const stops: TreeStop[] = inView\n    .filter(({ node }) => !hidden.includes(node.path[0] ?? ''))\n    .map(({ node }, at) => ({\n      id: node.key,\n      name: stopName(node.name),\n      value: node.value,\n      datum: node.datum,\n      index: at,\n    }))\n  const life = useChartLife(\n    props,\n    state,\n    load,\n    {\n      rows: inView.length,\n      shown: state.series.filter((key) => !hidden.includes(key)).length,\n      drawn: stops.length,\n    },\n    { entrance: entrance !== 'none', cascade: null },\n  )\n  const { status, phase, entered } = life\n  // Its props leave out `selected`, so nothing is picked; a press opens or does nothing.\n  const pick = useChartPick({}, stops.map(stopId))\n  // Every tile that arrives or leaves fades, in full and reduced motion alike, so the chart\n  // waits on that before letting one go.\n  const tiles = useLeavingItems(moves, stops, stopId)\n\n  const size = drawingSize(state.plotSize)\n  const layoutOptions = {\n    width: size.width,\n    height: size.height,\n    groupGap: GROUP_GAP,\n    tileGap: 0,\n    direction,\n    hidden,\n  }\n  // Zoomed in, the tiles keep the arrangement they had in their group, only bigger.\n  const layout = tileLayout(view, {\n    ...layoutOptions,\n    shape: viewShape(tree, view.path, layoutOptions),\n  })\n  // The layout shown before this one, kept while what left it finishes leaving.\n  const signature = layoutSignature(layout)\n  const [held, setHeld] = useState<{\n    signature: string\n    now: TileLayout\n    was: TileLayout | null\n  }>({ signature, now: layout, was: null })\n  if (held.signature !== signature) setHeld({ signature, now: layout, was: held.now })\n  const was = held.signature === signature ? held.was : held.now\n\n  const tileOf = (key: string) =>\n    layout.tiles.find((tile) => tile.key === key) ??\n    was?.tiles.find((tile) => tile.key === key) ??\n    null\n  const shownTiles = stops.map((stop) => tileOf(stop.id))\n  const viewTotal = layout.tiles.reduce((sum, tile) => sum + tile.node.value, 0)\n  const percent = numberFormatter(locale, {\n    style: 'percent',\n    maximumFractionDigits: 1,\n  })\n  const shareOf = (tile: LaidTile | null) =>\n    !tile || viewTotal === 0 ? 0 : tile.node.value / viewTotal\n  const label = valueLabel ?? words.value\n  const groupText = (tile: LaidTile | null) => (tile?.group ? nameOf(tile.group) : '')\n  const tileText = (tile: LaidTile | null) => (tile ? nameOf(tile.node) : '')\n  const anyGroup = layout.tiles.some((tile) => tile.group)\n  const colorOf = (stop: TreeStop, top: string) =>\n    tileColor(state.series, config, top, stop, color)\n\n  /** The tile at a point of the plot, or the nearest one in reach, or the header of a group there. */\n  const under = (point: PlotPoint) =>\n    tileAt(point, {\n      width: point.width,\n      height: point.height,\n      groups: layout.groups,\n      tiles: shownTiles,\n      reach: NEAR_TILE,\n    })\n  const zoomInto = (group: TileNode | null | undefined) =>\n    group && group.children.length > 0 ? () => zoomTo(group.path) : null\n\n  const reader = treeReader({\n    stops,\n    direction,\n    hit: (point) => {\n      const found = under(point)\n      if (!found) return null\n      return 'tile' in found\n        ? { kind: 'stop', index: found.tile }\n        : { kind: 'group', key: found.group.key }\n    },\n    openAt: (point) => {\n      const found = under(point)\n      if (!found) return null\n      return 'group' in found\n        ? zoomInto(found.group.node)\n        : zoomInto(shownTiles[found.tile]?.group)\n    },\n    open: (stop) => zoomInto(shownTiles[stop.index]?.group),\n    back: view.path.length > 0 ? () => zoomTo(view.path.slice(0, -1)) : null,\n    // The tooltip sits above the middle of its tile's top edge.\n    anchor: (stop) => {\n      const tile = shownTiles[stop.index]\n      if (!tile) return null\n      return {\n        x: (tile.box.x0 + tile.box.x1) / 2,\n        y: tile.box.y0,\n        side: 'top',\n      }\n    },\n    words: {\n      describe: (stop) => {\n        const tile = shownTiles[stop.index] ?? null\n        const name = pickedName(stop.name, pick.picked === stop.id, words)\n        if (!tile) return `${name}: `\n        const value = `${label} ${valueOf(tile.node)}, ${percent.format(shareOf(tile))}`\n        return `${name}: ${tile.group ? `${groupText(tile)}, ${value}` : value}`\n      },\n      table: {\n        header: words.category,\n        columns: [...(anyGroup ? [words.group] : []), label, words.share],\n        rows: stops.map((stop) => {\n          const tile = shownTiles[stop.index] ?? null\n          return {\n            key: stop.id,\n            name: stop.name,\n            cells: [\n              ...(anyGroup ? [groupText(tile)] : []),\n              tile ? valueOf(tile.node) : words.noValue,\n              percent.format(shareOf(tile)),\n            ],\n          }\n        }),\n        footer: [\n          ...(anyGroup ? [''] : []),\n          valueText(viewTotal),\n          percent.format(viewTotal === 0 ? 0 : 1),\n        ],\n      },\n      tooltip: (stop) => {\n        const tile = shownTiles[stop.index]\n        if (!tile) return null\n        const slot = state.series.indexOf(tile.top)\n        return (\n          <ShareTooltipContent\n            chart={state}\n            category={treeItem(stop)}\n            name={tile.group ? `${groupText(tile)} / ${tileText(tile)}` : tileText(tile)}\n            rows={[\n              {\n                label: null,\n                value: valueOf(tile.node),\n                share: percent.format(shareOf(tile)),\n              },\n            ]}\n            swatch={\n              <span\n                aria-hidden\n                className={cn(swatchClassName, forcedSeriesColor(slot === -1 ? 0 : slot))}\n                style={{ '--swatch': colorOf(stop, tile.top) } as CSSProperties}\n              />\n            }\n          />\n        )\n      },\n    },\n  })\n  const root: ChartRootValue = {\n    ...state,\n    status,\n    reader,\n    markerOf: () => null,\n    selectable: pick.selectable,\n    picked: pick.picked === null ? null : { kind: 'node', id: pick.picked },\n    togglePicked: (target) => {\n      if (target.kind === 'node' && reader.holds(target)) pick.toggle(target.id)\n    },\n  }\n  const { focusProps, toldRef } = useIndexFocus(reader.items, props)\n\n  const moved = tileMoves(was, layout)\n  return (\n    <TreeZoomContext value={{ tree, view, zoomTo, nameOf }}>\n      <ChartFrame\n        root={root}\n        focus={focusProps}\n        ref={ref}\n        slot='treemap-chart'\n        description={description}\n        empty={empty}\n        measuring={false}\n        inset={0}\n        data-orientation='vertical'\n        className={className}\n        {...figureProps(props, treemapChartKeys)}\n      >\n        <IndexActive items={reader.items} active={props} toldRef={toldRef}>\n          <TreemapTiles\n            layout={layout}\n            was={was}\n            moves={moved}\n            tiles={tiles}\n            stops={stops}\n            shownTiles={shownTiles}\n            labels={labels}\n            phase={phase}\n            entered={entered}\n            colorOf={colorOf}\n            nameOf={nameOf}\n          />\n          {props.children}\n          {load.placeholder && <TreemapPlaceholder />}\n        </IndexActive>\n      </ChartFrame>\n    </TreeZoomContext>\n  )\n}\n\nfunction stopId(stop: TreeStop) {\n  return stop.id\n}\n\n/** What tells one layout from another: the view, and every box, to a tenth of a px at 1000px. */\nfunction layoutSignature(layout: TileLayout) {\n  const boxes = [...layout.groups, ...layout.tiles]\n    .map(({ key, box }) =>\n      [key, box.x0, box.y0, box.x1, box.y1].map((part) =>\n        typeof part === 'number' ? part.toFixed(4) : part,\n      ),\n    )\n    .join('|')\n  return `${layout.view.key}#${boxes}`\n}\n\n/** A tile's colour: its own from `color`, or its top's. */\nfunction tileColor(\n  series: readonly string[],\n  config: ChartConfig,\n  top: string,\n  stop: TreeStop,\n  color: TreemapChartProps['color'],\n) {\n  return color?.(stop.datum, stop.index) || topColor(series, config, top)\n}\n\n/**\n * A box as the `clip-path` of a layer as large as the plot, which must be a\n * size container: inset by half the room between tiles on each side, its\n * corners rounded by `--treemap-chart-radius`, never past a quarter of its\n * smaller side and never quite square, so a move between boxes stays one\n * transition (as a bar's, `barClipPath`).\n */\nfunction tileClip(box: TileBox): string {\n  const half = 'var(--treemap-chart-gap, 2px) / 2'\n  // A quarter of the smaller side at most, so a small tile stays a tile, never a pill.\n  const across = round((box.x1 - box.x0) * 25)\n  const down = round((box.y1 - box.y0) * 25)\n  const radius = `max(0.01px, min(var(--treemap-chart-radius, var(--control-radius-xs)), ${across}cqw - ${half}, ${down}cqh - ${half}))`\n  return `inset(calc(${round(box.y0 * 100)}cqh + ${half}) calc(${round((1 - box.x1) * 100)}cqw + ${half}) calc(${round((1 - box.y1) * 100)}cqh + ${half}) calc(${round(box.x0 * 100)}cqw + ${half}) round ${radius})`\n}\n\n/** Where a box's label sits: its reading start corner, from the plot's start. */\nfunction labelAt(box: TileBox, direction: 'ltr' | 'rtl') {\n  const x = direction === 'rtl' ? box.x1 - 1 : box.x0\n  return `${round(x * 100)}cqw ${round(box.y0 * 100)}cqh`\n}\n\n/** A fraction written to four decimals, enough for a plot thousands of px long. */\nfunction round(value: number): number {\n  return Math.round(value * 10_000) / 10_000\n}\n\n/**\n * Every tile, in its group's colour, stepping back while another is lit or\n * another group is brought forward, with its label written on it where it\n * fits. A tile that arrives grows from where the move says, and one that\n * leaves goes to where it says, then fades.\n */\nfunction TreemapTiles({\n  layout,\n  was,\n  moves,\n  tiles,\n  stops,\n  shownTiles,\n  labels,\n  phase,\n  entered,\n  colorOf,\n  nameOf,\n}: {\n  layout: TileLayout\n  was: TileLayout | null\n  moves: ReturnType<typeof tileMoves>\n  /** Every tile to draw, the leaving ones too. */\n  tiles: readonly TreemapStop[]\n  /** The tiles in view, in the order the keys step through them. */\n  stops: readonly TreeStop[]\n  shownTiles: readonly (LaidTile | null)[]\n  labels: 'value' | 'name' | 'none'\n  phase: EntrancePhase\n  entered: boolean\n  colorOf: (stop: TreeStop, top: string) => string\n  nameOf: (node: TileNode) => string\n}) {\n  const chart = useChartRootValue()\n  const { spotlit } = useChartActive()\n  // Squarify follows the plot's shape, so until it is measured there is no layout to draw:\n  // a guess would rearrange itself once the page is running.\n  if (chart.status === 'empty' || !isMeasured(chart.plotSize)) return null\n  const size = drawingSize(chart.plotSize)\n  const lit = spotlit === null ? null : (stops[spotlit]?.id ?? null)\n  const stack = stackOrder(layout, was)\n  return (\n    <div\n      data-slot='treemap-chart-tiles'\n      aria-hidden\n      className={cn(plotLayerClassName, 'z-10')}\n    >\n      <TreemapHeaders\n        layout={layout}\n        was={was}\n        moves={moves}\n        nameOf={nameOf}\n        stack={stack}\n        stops={stops}\n        shownTiles={shownTiles}\n        entered={entered}\n      />\n      {tiles.map((stop) => {\n        const key = stop.id\n        const tile =\n          (stop.leaving ? null : shownTiles[stop.index]) ??\n          layout.tiles.find((one) => one.key === key) ??\n          was?.tiles.find((one) => one.key === key)\n        if (!tile) return null\n        const top = tile.top\n        const to = stop.leaving ? (moves.to.get(key) ?? centreOf(tile.box)) : tile.box\n        const shown = phase === 'waiting' ? centreOf(tile.box) : to\n        // A label drawn for the first time on a tile that stays starts where the tile was.\n        const from =\n          moves.from.get(key) ??\n          was?.tiles.find((one) => one.key === key)?.box ??\n          tile.box\n        const width = (tile.box.x1 - tile.box.x0) * size.width\n        const height = (tile.box.y1 - tile.box.y0) * size.height\n        const name = nameOf(tile.node)\n        const value = chart.valueText(tile.node.value)\n        const fit = labelFit(\n          width,\n          height,\n          chart.textWidth(name),\n          chart.textWidth(value),\n          labels,\n        )\n        const dim =\n          (lit !== null && lit !== key) ||\n          (chart.emphasis !== null &&\n            chart.emphasis !== top &&\n            chart.emphasis !== tile.group?.key)\n        const slot = chart.series.indexOf(top)\n        return (\n          <TreemapTile\n            key={key}\n            layer={stack(tile.group?.key ?? tile.key)}\n            clip={tileClip(shown)}\n            from={tileClip(from)}\n            labelAt={labelAt(shown, chart.direction)}\n            labelFrom={labelAt(from, chart.direction)}\n            color={colorOf(stop, top)}\n            image={\n              slot === -1 ? undefined : patternImage(chart.patternOf(top)) || undefined\n            }\n            forced={forcedSeriesColor(slot === -1 ? 0 : slot)}\n            dim={dim}\n            leaving={stop.leaving}\n            waiting={phase === 'waiting'}\n            entering={phase === 'entering'}\n            name={fit === 'none' ? null : name}\n            value={fit === 'value' ? value : null}\n          />\n        )\n      })}\n    </div>\n  )\n}\n\n/**\n * One tile, and its label. Memoised, so a pointer moving between tiles\n * redraws only the ones it lights or dims.\n */\nconst TreemapTile = memo(function TreemapTile({\n  layer,\n  clip,\n  from,\n  labelAt: at,\n  labelFrom,\n  color,\n  image,\n  forced,\n  dim,\n  leaving,\n  waiting,\n  entering,\n  name,\n  value,\n}: {\n  /** Where it stacks: above every group before its own, below its header. */\n  layer: number\n  clip: string\n  from: string\n  labelAt: string\n  labelFrom: string\n  color: string\n  image: string | undefined\n  forced: string | undefined\n  dim: boolean\n  leaving: boolean\n  /** Before the entrance, out of sight at its centre. */\n  waiting: boolean\n  entering: boolean\n  /** The name written on the tile, or none where it doesn't fit. */\n  name: string | null\n  value: string | null\n}) {\n  // A tile that has never had room for its words draws no label at all, so a\n  // chart of hundreds of small tiles styles only the elements it shows.\n  const [labelled, setLabelled] = useState(name !== null)\n  if (name !== null && !labelled) setLabelled(true)\n  return (\n    <div\n      data-slot='treemap-chart-tile'\n      data-dim={dim ? '' : undefined}\n      data-leaving={leaving ? '' : undefined}\n      data-waiting={waiting ? '' : undefined}\n      data-entering={entering ? '' : undefined}\n      className={cn(\n        'absolute inset-0 [clip-path:var(--tile-clip)] bg-(--mark-ink) transition-none duration-(--motion-layout-duration) ease-[var(--motion-layout-fade-easing),var(--motion-layout-easing),var(--motion-layout-fade-easing)] group-data-mounted/chart:transition-[background-color,clip-path,opacity] group-data-mounted/chart:starting:[clip-path:var(--tile-from)] group-data-mounted/chart:starting:opacity-0 data-entering:duration-(--motion-draw-duration) data-entering:ease-[var(--motion-draw-fade-easing),var(--motion-draw-easing),var(--motion-draw-fade-easing)] data-waiting:opacity-0 data-leaving:opacity-0 data-leaving:duration-(--motion-exit-duration) data-leaving:ease-[var(--motion-exit-fade-easing),var(--motion-exit-easing),var(--motion-exit-fade-easing)] motion-reduce:group-data-mounted/chart:transition-[background-color,opacity] motion-reduce:ease-(--motion-layout-fade-easing) motion-reduce:data-entering:ease-(--motion-draw-fade-easing) motion-reduce:data-leaving:ease-(--motion-exit-fade-easing)',\n        stepBackInkClassName,\n        forced,\n      )}\n      style={\n        {\n          zIndex: layer,\n          '--mark-color': color,\n          // Variables, not `clipPath`, so the class's starting shape isn't overruled by an inline style.\n          '--tile-clip': clip,\n          '--tile-from': from,\n          backgroundImage: image,\n        } as CSSProperties\n      }\n    >\n      {labelled && (\n        <span\n          className='absolute top-0 start-0 size-0 [translate:var(--label-at)] transition-none duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-mounted/chart:transition-[translate] group-data-mounted/chart:starting:[translate:var(--label-from)] in-data-entering:duration-(--motion-draw-duration) in-data-entering:ease-(--motion-draw-easing) in-data-leaving:duration-(--motion-exit-duration) in-data-leaving:ease-(--motion-exit-easing) motion-reduce:group-data-mounted/chart:transition-none'\n          style={{ '--label-at': at, '--label-from': labelFrom } as CSSProperties}\n        >\n          <span\n            data-off={name === null ? '' : undefined}\n            className={cn(\n              'absolute top-0 start-0 flex flex-col items-start leading-4 whitespace-nowrap transition-none group-data-mounted/chart:transition-opacity duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing) data-off:opacity-0',\n              labelOnClassName,\n            )}\n            style={\n              {\n                '--label-on': color,\n                // Inside the room between tiles, so the words line up with their group's header.\n                margin: `calc(var(--treemap-chart-gap, 2px) / 2 + ${LABEL_PADDING}px)`,\n              } as CSSProperties\n            }\n          >\n            {/* A label that no longer fits keeps its words while it fades. */}\n            <HeldText className='font-medium'>{name}</HeldText>\n            <HeldText className='tabular-nums'>{value}</HeldText>\n          </span>\n        </span>\n      )}\n    </div>\n  )\n})\n\n/** Text that keeps what it last said while it goes, so a label fading out keeps its words. */\nfunction HeldText({\n  className,\n  children,\n}: {\n  className: string\n  children: string | null\n}) {\n  const [last, setLast] = useState(children)\n  if (children !== null && children !== last) setLast(children)\n  if (last === null) return null\n  return (\n    // A value with a unit reads in its own order whatever the page's direction.\n    <span\n      dir='auto'\n      data-off={children === null ? '' : undefined}\n      className={cn(\n        className,\n        'transition-none group-data-mounted/chart:transition-opacity duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing) data-off:opacity-0',\n      )}\n    >\n      {last}\n    </span>\n  )\n}\n\n/**\n * Each group's header above its tiles: its name and its worth, where they\n * fit, cut to the group's box as it moves, so a group that leaves takes its\n * header with it.\n */\nfunction TreemapHeaders({\n  layout,\n  was,\n  moves,\n  nameOf,\n  stack,\n  stops,\n  shownTiles,\n  entered,\n}: {\n  layout: TileLayout\n  was: TileLayout | null\n  moves: ReturnType<typeof tileMoves>\n  nameOf: (node: TileNode) => string\n  stack: (key: string) => number\n  stops: readonly TreeStop[]\n  shownTiles: readonly (LaidTile | null)[]\n  entered: boolean\n}) {\n  const chart = useChartRootValue()\n  const { spotlit } = useChartActive()\n  // Until the tiles arrive, their headers wait with them.\n  if (chart.status !== 'ready' || !entered) return null\n  const size = drawingSize(chart.plotSize)\n  const now = new Set(layout.groups.map((group) => group.key))\n  const leaving = (was?.groups ?? []).filter((group) => !now.has(group.key))\n  const litGroup =\n    spotlit !== null && stops[spotlit] ? (shownTiles[spotlit]?.group?.key ?? null) : null\n  return (\n    <>\n      {[...layout.groups, ...leaving].map((group) => {\n        const gone = !now.has(group.key)\n        const box = gone ? (moves.to.get(group.key) ?? group.box) : group.box\n        const from = moves.from.get(group.key) ?? group.box\n        const name = nameOf(group.node)\n        const value = chart.valueText(group.node.value)\n        const fit = group.header\n          ? headerFit(\n              (group.box.x1 - group.box.x0) * size.width,\n              chart.textWidth(name),\n              chart.textWidth(value),\n            )\n          : 'none'\n        const quiet =\n          (litGroup !== null && litGroup !== group.key) ||\n          (chart.emphasis !== null &&\n            chart.emphasis !== group.key &&\n            chart.emphasis !== group.top)\n        return (\n          <TreemapHeader\n            key={group.key}\n            layer={stack(group.key) + 1}\n            clip={headerClip(box)}\n            from={headerClip(from)}\n            at={labelAt(box, chart.direction)}\n            labelFrom={labelAt(from, chart.direction)}\n            leaving={gone}\n            quiet={quiet}\n            name={fit === 'none' ? null : name}\n            value={fit === 'value' ? value : null}\n          />\n        )\n      })}\n    </>\n  )\n}\n\n/**\n * Where each group stacks among the tiles, by its key, so the order never\n * changes as groups come and go: a group's header just above its own tiles,\n * and the next group's tiles above both, so a header moving with its group\n * never shows over another's tiles. Even numbers; a header takes the odd one\n * above.\n */\nfunction stackOrder(layout: TileLayout, was: TileLayout | null) {\n  const keys = new Set<string>()\n  for (const shown of [layout, was]) {\n    for (const group of shown?.groups ?? []) keys.add(group.key)\n    for (const tile of shown?.tiles ?? []) if (!tile.group) keys.add(tile.key)\n  }\n  const order = new Map([...keys].sort().map((key, at) => [key, at * 2]))\n  return (key: string) => order.get(key) ?? 0\n}\n\n/** A group's whole box, as a header's `clip-path`, square, so its words are cut where the group's tiles are. */\nfunction headerClip(box: TileBox) {\n  return tileClip(box).replace(/ round .*\\)$/, ' round 0.01px)')\n}\n\nconst TreemapHeader = memo(function TreemapHeader({\n  layer,\n  clip,\n  from,\n  at,\n  labelFrom,\n  leaving,\n  quiet,\n  name,\n  value,\n}: {\n  layer: number\n  clip: string\n  from: string\n  at: string\n  labelFrom: string\n  leaving: boolean\n  quiet: boolean\n  name: string | null\n  value: string | null\n}) {\n  return (\n    <div\n      data-leaving={leaving ? '' : undefined}\n      className='absolute inset-0 [clip-path:var(--header-clip)] transition-none duration-(--motion-layout-duration) ease-[var(--motion-layout-easing),var(--motion-layout-fade-easing)] group-data-mounted/chart:transition-[clip-path,opacity] group-data-mounted/chart:starting:[clip-path:var(--header-from)] group-data-mounted/chart:starting:opacity-0 data-leaving:opacity-0 data-leaving:duration-(--motion-exit-duration) data-leaving:ease-[var(--motion-exit-easing),var(--motion-exit-fade-easing)] motion-reduce:group-data-mounted/chart:transition-opacity motion-reduce:ease-(--motion-layout-fade-easing)'\n      style={\n        {\n          zIndex: layer,\n          '--header-clip': clip,\n          '--header-from': from,\n        } as CSSProperties\n      }\n    >\n      <span\n        className='absolute top-0 start-0 size-0 [translate:var(--label-at)] transition-none duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-mounted/chart:transition-[translate] group-data-mounted/chart:starting:[translate:var(--label-from)] in-data-leaving:duration-(--motion-exit-duration) in-data-leaving:ease-(--motion-exit-easing) motion-reduce:group-data-mounted/chart:transition-none'\n        style={{ '--label-at': at, '--label-from': labelFrom } as CSSProperties}\n      >\n        <span\n          data-quiet={quiet ? '' : undefined}\n          // In line with the labels of the tiles below it.\n          style={{\n            paddingInline: `calc(var(--treemap-chart-gap, 2px) / 2 + ${LABEL_PADDING}px)`,\n          }}\n          className='text-foreground data-quiet:text-muted-foreground absolute top-0 start-0 flex h-5 items-center gap-2 leading-4 whitespace-nowrap transition-colors duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing) forced-colors:text-[CanvasText]'\n        >\n          <HeldText className='font-medium'>{name}</HeldText>\n          <HeldText className='text-muted-foreground tabular-nums'>{value}</HeldText>\n        </span>\n      </span>\n    </div>\n  )\n})\n\n/** The tiles in the placeholder's tint, breathing slowly, while the data loads. */\nfunction TreemapPlaceholder() {\n  const chart = useChartRootValue()\n  if (!isMeasured(chart.plotSize)) return null\n  const size = drawingSize(chart.plotSize)\n  const layout = tileLayout(PLACEHOLDER_TREE, {\n    width: size.width,\n    height: size.height,\n    groupGap: GROUP_GAP,\n    tileGap: 0,\n    direction: chart.direction,\n  })\n  return (\n    <div\n      data-slot='treemap-chart-placeholder'\n      aria-hidden\n      className={cn(plotLayerClassName, 'z-10', placeholderBreatheClassName)}\n    >\n      {layout.tiles.map((tile) => (\n        <div\n          key={tile.key}\n          className={cn('absolute inset-0', placeholderFillClassName)}\n          style={{ clipPath: tileClip(tile.box) }}\n        />\n      ))}\n    </div>\n  )\n}\n\n/** The shape the placeholder's tiles take: a few of falling size, as most treemaps have. */\nconst PLACEHOLDER_TREE = tileTree(\n  [34, 22, 16, 11, 8, 5, 4].map((value, at) => ({ name: String(at), value })),\n  'name',\n  'value',\n)\n\n/**\n * The way back out: the path of the parts above the one in view, the whole\n * first, each a button that zooms out to it, above the plot.\n */\nfunction TreemapPath(props: ComponentProps<'nav'>) {\n  return <TreeZoomPath slot='treemap-chart-path' {...props} />\n}\n\nexport { labelAt, TreemapChart, type TreemapChartProps, TreemapPath, tileClip }\n",
      "type": "registry:component",
      "target": "@components/kino/treemap-chart.tsx"
    }
  ],
  "type": "registry:component"
}