{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "treemap-chart",
  "type": "registry:component",
  "title": "Treemap Chart",
  "description": "A total, cut into the parts it is made of, sized by area.",
  "dependencies": [
    "@base-ui/react",
    "@tanstack/charts",
    "tailwind-variants"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "components/panelui/treemap-chart/index.tsx",
      "type": "registry:component",
      "target": "@components/panelui/treemap-chart/index.tsx",
      "content": "'use client';\n\n/**\n * TreemapChart — a total, cut into the parts it is made of, sized by area.\n *\n * ```tsx\n * <TreemapChart data={spend}>\n *   <TreemapChart.Header title=\"Spend\" value=\"$48,200\" />\n *   <TreemapChart.Tiles />\n *   <TreemapChart.Labels />\n *   <TreemapChart.Tooltip />\n * </TreemapChart>\n * ```\n *\n * ## The same parts as the app\n *\n * The parts and most of the props are the app library's TreemapChart. What differs\n * is what the web changes: a tile is read by hovering, a click pins the reading,\n * the arrow keys walk the tiles, and `Breakdown` lists them with exact values.\n *\n * ## The layout is ours, the drawing is not\n *\n * The squarified layout comes from the app, in `squarify.ts`, so both platforms\n * cut a total the same way. It works in pixels, so the marks get identity scales.\n *\n * ## One hue down the ranking\n *\n * The area already says which tile is bigger, and a treemap has more parts than\n * the theme has chart colours, so tiles share one colour that fades with rank. A\n * tile can still take its own `color`, drawn at full strength.\n *\n * ## The ink follows the tile\n *\n * A label is white or near-black depending on the tile under it, worked out in\n * CSS with a relative colour, so it holds for any colour and flips with the theme.\n */\nimport {\n  defineChart,\n  rect,\n  type ChartInteractionController,\n  type ChartFocusStrategy,\n  type ChartPoint,\n  type ChartTooltipContentContext,\n  type SceneNode,\n} from '@tanstack/charts';\nimport { motion } from '@tanstack/charts/motion';\nimport { Chart } from '@tanstack/charts/react/core';\nimport { scaleLinear } from '@tanstack/charts/scales/linear';\nimport { tooltip as chartTooltip } from '@tanstack/charts/tooltip';\nimport {\n  createContext,\n  forwardRef,\n  useCallback,\n  useContext,\n  useEffect,\n  useImperativeHandle,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type CSSProperties,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type ReactNode,\n} from 'react';\nimport { tv } from 'tailwind-variants';\nimport { mergeProps } from '@base-ui/react/merge-props';\nimport { useRender } from '@base-ui/react/use-render';\nimport type { ElementType as RenderElementType } from 'react';\nimport { fitTileLabel, LABEL_PADDING_X, LABEL_PADDING_Y, squarifyLayout, type TreemapRect } from './squarify';\n\nexport { squarifyLayout, type TreemapRect } from './squarify';\n\n/** Draws a part as another element, or composes it with a component: `render={<a href=\"/\" />}`. */\ntype RenderProp<Tag extends RenderElementType> = { render?: useRender.ComponentProps<Tag>['render'] };\n\nexport type TreemapChartStatus = 'loading' | 'ready';\n\n/** Which of the theme's roles a tile is drawn in. */\nexport type TreemapChartRole =\n  | 'primary'\n  | 'info'\n  | 'success'\n  | 'warning'\n  | 'destructive'\n  | 'chart-1'\n  | 'chart-2'\n  | 'chart-3'\n  | 'chart-4'\n  | 'chart-5';\n\n/** A role in the theme, or any CSS colour, such as a colour the user picked for a category. */\nexport type TreemapChartColor = TreemapChartRole | (string & {});\n\nconst ROLES: readonly string[] = [\n  'primary',\n  'info',\n  'success',\n  'warning',\n  'destructive',\n  'chart-1',\n  'chart-2',\n  'chart-3',\n  'chart-4',\n  'chart-5',\n];\n\nconst colorOf = (color: TreemapChartColor) => (ROLES.includes(color) ? `var(--${color})` : color);\n\nconst THEME = {\n  foreground: 'var(--foreground)',\n  muted: 'var(--muted-foreground)',\n  grid: 'var(--border)',\n  background: 'transparent',\n  palette: ['var(--chart-1)', 'var(--chart-2)', 'var(--chart-3)', 'var(--chart-4)', 'var(--chart-5)'],\n};\n\nconst treemapChartVariants = tv({\n  slots: {\n    root: 'w-full text-foreground @container',\n    layout:\n      'relative grid w-full grid-cols-1 @md:has-[[data-slot=treemap-chart-breakdown]]:grid-cols-[minmax(0,1fr)_11rem] @md:has-[[data-slot=treemap-chart-breakdown]]:gap-x-3',\n    plot: 'relative col-start-1 row-start-2 w-full cursor-pointer self-start',\n    chart:\n      'absolute! inset-0 touch-pan-y rounded-lg text-xs [--ts-chart-tooltip-background:var(--popover)] [--ts-chart-tooltip-border-radius:var(--radius-xl)] [--ts-chart-tooltip-border:1px_solid_var(--border)] [--ts-chart-tooltip-color:var(--popover-foreground)] [--ts-chart-tooltip-shadow:var(--shadow-lg)] [&_svg]:rounded-lg [&_svg]:outline-none [&_svg:focus-visible]:ring-2 [&_svg:focus-visible]:ring-ring',\n    labels: 'pointer-events-none relative col-start-1 row-start-2 w-full self-start overflow-hidden text-xs',\n    label:\n      'absolute overflow-hidden transition-opacity duration-150 motion-reduce:[animation:none!important]',\n    labelName: 'truncate font-semibold',\n    labelValue: 'truncate tabular-nums opacity-85',\n    skeleton: 'relative col-start-1 row-start-2 w-full self-start overflow-hidden rounded-md bg-muted',\n    sweep: 'absolute inset-y-0 left-0 w-2/5 motion-reduce:hidden',\n    legend: 'col-start-1 row-start-3 flex flex-wrap items-center gap-x-3 gap-y-1.5 pt-3 text-xs',\n    legendItem: 'flex max-w-full items-center gap-1.5 rounded-sm transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-ring',\n    legendName: 'truncate text-muted-foreground',\n    legendShare: 'font-medium tabular-nums',\n    swatch: 'size-2 shrink-0 rounded-[2px]',\n    breakdown: 'col-start-1 row-start-4 mt-3 w-full self-start text-xs @md:col-start-2 @md:row-start-2 @md:mt-0',\n    breakdownRow:\n      'grid h-7 w-full grid-cols-[0.5rem_minmax(0,1fr)_auto] items-center gap-1.5 border-t border-border text-left transition-opacity outline-none first:border-t-transparent focus-visible:ring-2 focus-visible:ring-ring',\n    breakdownName: 'truncate',\n    breakdownValue: 'flex gap-1.5 tabular-nums',\n    breakdownShare: 'min-w-7 text-right text-muted-foreground',\n    header: 'col-span-full row-start-1 flex items-start justify-between gap-3 pb-3',\n    headerText: 'flex min-w-0 flex-1 flex-col gap-0.5',\n    headerMuted: 'text-xs text-muted-foreground',\n    headerValue: 'text-xl font-bold tabular-nums tracking-tight',\n    headerTrailing: 'flex shrink flex-wrap items-center justify-end gap-x-3 gap-y-1 pt-1 text-xs text-muted-foreground',\n  },\n});\n\n/** How far the hue has faded by the smallest tile. */\nconst FADE = 0.45;\n\nconst ENTERING = '[data-slot=treemap-chart-plot][data-entering] .ts-chart__marks';\n\nconst KEYFRAMES = `@keyframes panelui-treemap-sweep{from{transform:translateX(-100%)}to{transform:translateX(250%)}}@keyframes panelui-treemap-label{from{opacity:0}to{opacity:1}}@keyframes panelui-treemap-tile{from{transform:scale(0);opacity:0}}@media (prefers-reduced-motion:no-preference){${ENTERING} rect{transform-box:fill-box;transform-origin:center;animation:panelui-treemap-tile var(--treemap-duration) cubic-bezier(.33,1,.68,1) backwards}}`;\n\n/** Each tile starts a stagger after the one before it. Each sits in a group of its own. */\nconst tileDelays = (count: number) =>\n  Array.from(\n    { length: count },\n    (_unused, index) => `${ENTERING}>g:nth-child(${index + 1}) rect{animation-delay:calc(var(--treemap-stagger)*${index})}`\n  ).join('');\n\nconst COMPACT = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 });\nconst COMPACT_SMALL = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 2 });\n\nconst EXACT = new Intl.NumberFormat('en');\n\n/** Below one, a single decimal would round most values down to nothing. */\nconst compactNumber = (value: number) => (Math.abs(value) < 1 ? COMPACT_SMALL : COMPACT).format(value);\n\n/** One part of the total. */\nexport interface TreemapDatum {\n  /** Name of the part, for the label, the readout and the legend. */\n  label: string;\n  /** Its size. Negatives are treated as zero, because an area cannot be less than none. */\n  value: number;\n  /** Keeps a tile's identity when the data changes, and when two parts share a label. Defaults to its row. */\n  id?: string;\n  /** A theme role or any CSS colour, drawn at full strength instead of the ramp. */\n  color?: TreemapChartColor;\n}\n\n/** One laid-out tile: its datum, its share of the total, and where it sits. */\nexport interface TreemapTile extends TreemapRect {\n  /** The datum's `id`, or its row in `data`. The gathered tile is `other`. */\n  id: string;\n  label: string;\n  value: number;\n  /** Its share of the whole chart, `0` to `1`. */\n  share: number;\n  /** The CSS colour of its hue, before the ramp. */\n  color: string;\n  /** How far along the ramp it is drawn, `0` to `1`. `1` where a colour was given. */\n  strength: number;\n  /** Its row in `data`, or `-1` for the gathered tile, which stands for several rows. */\n  sourceIndex: number;\n}\n\n/** A tile as the mark sees it: its box, in the pixels the identity scales pass through. */\ninterface TileRow {\n  index: number;\n  tile: TreemapTile;\n  x0: number;\n  x1: number;\n  y0: number;\n  y1: number;\n}\n\ntype TilePoint = ChartPoint<TileRow, number, number>;\n\n/**\n * A tile's colour as it looks over the card, with no alpha left in it. Swatches\n * use this because a dimmed row is an opacity group, and Chromium draws a colour\n * outside sRGB that has alpha inside one as olive.\n */\nconst tileOpaque = ({ color, strength }: Pick<TreemapTile, 'color' | 'strength'>) =>\n  `color-mix(in oklab, ${color} ${Math.round(strength * 100)}%, var(--background))`;\n\n/** The tile's colour as drawn, part-transparent down the ramp. */\nconst tileFill = ({ color, strength }: Pick<TreemapTile, 'color' | 'strength'>) =>\n  strength >= 1 ? color : `color-mix(in oklab, ${color} ${Math.round(strength * 100)}%, transparent)`;\n\n/**\n * White on a dark tile, near-black on a light one, judged against the tile as\n * drawn over the page. The multiplied lightness clamps to one or the other, and\n * 0.6 is about where the two have equal contrast.\n */\nconst tileInk = (tile: Pick<TreemapTile, 'color' | 'strength'>) => `oklch(from ${tileOpaque(tile)} calc((0.6 - l) * 1000) 0 0)`;\n\n/** The tile under the pointer. The nearest centre would often be the tile next door. */\nfunction tileUnderPointer(gap: number): ChartFocusStrategy<TileRow, number, number> {\n  return {\n    resolve(points, { x, y }) {\n      const reach = gap / 2;\n      const point = points.find(\n        ({ datum }) => x >= datum.x0 - reach && x <= datum.x1 + reach && y >= datum.y0 - reach && y <= datum.y1 + reach\n      );\n      return point ? [point] : [];\n    },\n    group: (_points, { point }) => [point],\n    navigation: (points) => [...points].sort((a, b) => a.datum.index - b.datum.index),\n  };\n}\n\nfunction pointsOf(nodes: readonly SceneNode[]): TilePoint[] {\n  return nodes.flatMap((node) => {\n    if (node.kind === 'group') return pointsOf(node.children);\n    const point = node.kind === 'rect' ? node.interaction?.point : undefined;\n    return point ? [point as TilePoint] : [];\n  });\n}\n\n/** What the parts have asked for. The readout's formatter is read when it opens, so a new one costs nothing. */\ninterface Slots {\n  tiles?: { dimOpacity: number };\n  tooltip?: { className: string | undefined; latest: { current: Pick<TreemapChartTooltipProps, 'formatValue'> } };\n}\n\ninterface TreemapChartContextValue {\n  tiles: readonly TreemapTile[];\n  total: number;\n  status: TreemapChartStatus;\n  aspectRatio: number;\n  hue: string;\n  animationDuration: number;\n  staggerDelay: number;\n  chartKey: string;\n  activeIndex: number;\n  setSlot: <K extends keyof Slots>(slot: K, value: Slots[K]) => void;\n  /** Reads a tile for as long as the pointer is on something naming it. `-1` goes back to what is pinned. */\n  preview: (index: number) => void;\n  /** Pins a tile's reading, or lets go of it if it is already pinned. */\n  press: (index: number) => void;\n}\n\nconst TreemapChartContext = createContext<TreemapChartContextValue | null>(null);\n\nfunction useChart(component: string): TreemapChartContextValue {\n  const context = useContext(TreemapChartContext);\n  if (!context) {\n    throw new Error(`${component} must be used within a <TreemapChart>`);\n  }\n  return context;\n}\n\n/** The tile being read, for something rendered inside the chart. A readout outside it takes `onActiveIndexChange`. */\nexport function useTreemapChart() {\n  const { tiles, total, activeIndex } = useChart('useTreemapChart');\n  return {\n    /** Index into the tiles **as laid out**, which is the sorted order. */\n    activeIndex,\n    activeTile: activeIndex >= 0 ? (tiles[activeIndex] ?? null) : null,\n    tiles,\n    total,\n  };\n}\n\n/** Hands a part's formatters to the root without a new function rebuilding the chart. */\nfunction useLatest<T>(value: T) {\n  const ref = useRef(value);\n  useEffect(() => {\n    ref.current = value;\n  });\n  return ref;\n}\n\nexport interface TreemapChartProps extends Omit<ComponentProps<'div'>, 'ref' | 'onSelect'> {\n  /** The parts of the total, in any order. Sorted by the chart unless told not to. */\n  data: readonly TreemapDatum[];\n  /** Width ÷ height of the box the tiles fill. */\n  aspectRatio?: number;\n  /** Pixels between one tile and the next. */\n  gap?: number;\n  /** Corner radius of a tile, in pixels. */\n  cornerRadius?: number;\n  /**\n   * How much wider than square-ish to lay the tiles out. `1` keeps the shapes\n   * closest to square, which are the easiest to compare. Raise it on a short\n   * chart, where a tile needs width for a name across it.\n   */\n  tileAspect?: number;\n  /**\n   * Sort the tiles largest first. The layout assumes a descending run, so the\n   * shapes suffer without it. Turn it off where the given order is the message.\n   */\n  sort?: boolean;\n  /**\n   * The most tiles to draw, counting the gathered one. Past it, the first tiles\n   * are kept, which are the largest unless `sort` is off, and the rest are gathered into one.\n   */\n  maxTiles?: number;\n  /** What the gathered tile is called. */\n  otherLabel?: string;\n  /** The ramp's hue: a theme role or any CSS colour. */\n  color?: TreemapChartColor;\n  /** Milliseconds for one tile to arrive. */\n  animationDuration?: number;\n  /** Milliseconds between one tile starting and the next. `0` for all at once. */\n  staggerDelay?: number;\n  /** `loading` holds the tiles back. Add a `TreemapChart.Skeleton` to stand in the box meanwhile. */\n  status?: TreemapChartStatus;\n  /** The tile being read, indexed as laid out. Leave unset to let the chart track it. */\n  activeIndex?: number;\n  /** Fires with the tile being read, and `-1`/`null` when there is none. Fires on hover as well as on a press. */\n  onActiveIndexChange?: (index: number, tile: TreemapTile | null) => void;\n  /** Fires when a tile is clicked or tapped, or Enter is pressed on it. For a tile that leads somewhere. */\n  onSelect?: (tile: TreemapTile) => void;\n  /** What a screen reader calls the chart. */\n  label?: string;\n  /** What a screen reader says for one tile. Defaults to its name, value and share. */\n  labelForTile?: (tile: TreemapTile) => string;\n}\n\n/** Imperative handle: re-run the entrance, for a \"replay\" control. */\nexport interface TreemapChartHandle {\n  replay: () => void;\n}\n\nconst TreemapChartRoot = forwardRef<TreemapChartHandle, TreemapChartProps & RenderProp<'div'>>(function TreemapChartRoot(\n  {\n    data,\n    aspectRatio = 1.4,\n    gap = 3,\n    cornerRadius = 6,\n    tileAspect = 1,\n    sort = true,\n    maxTiles,\n    otherLabel = 'Other',\n    color = 'chart-1',\n    animationDuration = 520,\n    staggerDelay = 26,\n    status = 'ready',\n    activeIndex: activeIndexProp,\n    onActiveIndexChange,\n    onSelect,\n    label,\n    labelForTile,\n    className,\n    children,\n    render,\n    ...props\n  },\n  ref\n) {\n  const slotClasses = treemapChartVariants();\n  const plotRef = useRef<HTMLDivElement>(null);\n  const [width, setWidth] = useState(0);\n  const [slots, setSlots] = useState<Slots>({});\n  const [reading, setReading] = useState(-1);\n  const [revision, setRevision] = useState(0);\n  const [askedParent, setAskedParent] = useState(0);\n  const interactionRef = useRef<ChartInteractionController<TileRow, number, number> | null>(null);\n  const pointsRef = useRef<readonly TilePoint[]>([]);\n\n  // The chart mounts once its width is known, because a resize ends the entrance.\n  useEffect(() => {\n    const node = plotRef.current;\n    if (!node) return;\n    const read = () => setWidth(node.clientWidth);\n    read();\n    const observer = new ResizeObserver(read);\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, []);\n\n  const setSlot = useCallback<TreemapChartContextValue['setSlot']>(\n    (slot, value) => setSlots((current) => ({ ...current, [slot]: value })),\n    []\n  );\n\n  useImperativeHandle(ref, () => ({ replay: () => setRevision((current) => current + 1) }), []);\n\n  // Kept apart from the geometry, so a resize does not re-run the sort and the gathering.\n  const parts = useMemo(() => {\n    const cleaned = data.map((datum, index) => ({\n      id: datum.id ?? String(index),\n      label: datum.label,\n      value: Number.isFinite(datum.value) ? Math.max(0, datum.value) : 0,\n      color: datum.color,\n      sourceIndex: index,\n    }));\n    const ordered = sort ? [...cleaned].sort((a, b) => b.value - a.value) : cleaned;\n    const limit = maxTiles && maxTiles > 0 ? Math.floor(maxTiles) : 0;\n    if (!limit || ordered.length <= limit) return ordered;\n    /*\n     * Gathered rather than dropped. Dropping the tail would rescale what is left,\n     * and every remaining tile would claim a larger share than it has.\n     */\n    const kept = ordered.slice(0, Math.max(1, limit - 1));\n    const tail = ordered.slice(Math.max(1, limit - 1)).reduce((sum, part) => sum + part.value, 0);\n    return tail > 0\n      ? [...kept, { id: 'other', label: otherLabel, value: tail, color: undefined, sourceIndex: -1 }]\n      : kept;\n  }, [data, sort, maxTiles, otherLabel]);\n\n  const total = useMemo(() => parts.reduce((sum, part) => sum + part.value, 0), [parts]);\n  const height = width / aspectRatio;\n\n  const tiles = useMemo<TreemapTile[]>(() => {\n    const rects = squarifyLayout(parts.map((part) => part.value), width, height, undefined, tileAspect);\n    const inset = Math.max(0, gap) / 2;\n    const last = Math.max(parts.length - 1, 1);\n    return parts.map((part, index) => {\n      const box = rects[index] ?? { x: 0, y: 0, width: 0, height: 0 };\n      return {\n        id: part.id,\n        label: part.label,\n        value: part.value,\n        share: total > 0 ? part.value / total : 0,\n        color: colorOf(part.color ?? color),\n        // Down the ranking rather than by value, so two tiles of nearly equal size can still be told apart.\n        strength: part.color ? 1 : 1 - (index / last) * FADE,\n        sourceIndex: part.sourceIndex,\n        x: box.x + inset,\n        y: box.y + inset,\n        width: Math.max(0, box.width - inset * 2),\n        height: Math.max(0, box.height - inset * 2),\n      };\n    });\n  }, [parts, width, height, tileAspect, gap, total, color]);\n\n  const hue = colorOf(color);\n  const loading = status === 'loading';\n  const { tiles: tilesSlot, tooltip } = slots;\n  const drawable = !loading && tilesSlot !== undefined && total > 0 && width > 0;\n\n  const definition = useMemo(() => {\n    const rows: TileRow[] = tiles.flatMap((tile, index) =>\n      tile.width > 0 && tile.height > 0\n        ? [{ index, tile, x0: tile.x, x1: tile.x + tile.width, y0: tile.y, y1: tile.y + tile.height }]\n        : []\n    );\n\n    const readout = tooltip\n      ? {\n          use: chartTooltip,\n          className: tooltip.className,\n          anchor: 'point' as const,\n          sticky: false,\n          content(_points: readonly TilePoint[], context: ChartTooltipContentContext) {\n            const tile = (context.primaryPoint?.datum as TileRow | undefined)?.tile;\n            if (!tile) return { title: '', rows: [] };\n            const format = tooltip.latest.current.formatValue;\n            return {\n              title: tile.label,\n              rows: [\n                {\n                  label: format ? format(tile.value, tile) : compactNumber(tile.value),\n                  value: `${Math.round(tile.share * 100)}%`,\n                  color: tileFill(tile),\n                },\n              ],\n            };\n          },\n        }\n      : undefined;\n\n    return defineChart({\n      theme: THEME,\n      // A mark per tile, because a mark takes one fill.\n      marks: rows.map((row) =>\n        rect([row], {\n          id: `tile-${row.tile.id}`,\n          key: () => row.tile.id,\n          x1: 'x0',\n          x2: 'x1',\n          y1: 'y0',\n          y2: 'y1',\n          inset: 0,\n          radius: cornerRadius,\n          fill: tileFill(row.tile),\n          states: [\n            {\n              when: { focus: 'unmatched' as const },\n              style: { fillOpacity: tilesSlot?.dimOpacity ?? 0.35 },\n              transition: { type: 'tween' as const, duration: 180, easing: 'ease-out' as const },\n            },\n          ],\n        })\n      ),\n      // The layout has already worked in pixels, so both scales hand them straight through.\n      scales: {\n        x: { scale: scaleLinear([0, width], [0, 1]), nice: false, axis: false as const, grid: false as const },\n        y: { scale: scaleLinear([height, 0], [0, 1]), nice: false, axis: false as const, grid: false as const },\n      },\n      guides: false,\n      margin: 0,\n      focusRing: false,\n      motion: { transition: { type: 'tween' as const, duration: 300, easing: 'ease-out' as const } },\n      keyboard: true,\n      pointer: true,\n      focus: tileUnderPointer(gap),\n      maxFocusDistance: Number.POSITIVE_INFINITY,\n      ...(readout ? { tooltip: readout } : {}),\n    });\n  }, [tiles, width, height, gap, cornerRadius, tilesSlot, tooltip]);\n\n  // Marks take their timing from the definition. This one is what the readout moves with.\n  const renderer = useMemo(() => motion({ transition: { type: 'tween', duration: 160, easing: 'ease-out' } }), []);\n\n  const latestTiles = useLatest(tiles);\n  const latestActive = useLatest(activeIndexProp);\n  const latestReport = useLatest(onActiveIndexChange);\n\n  const pointAt = (index: number) => pointsRef.current.find(({ datum }) => datum.index === index) ?? null;\n\n  /*\n   * The chart only pins a reading for a tooltip, and the rows of a breakdown have\n   * to stay put while the pointer travels to them. So the pin is held here: a\n   * hover previews, and leaving comes back to whatever is pinned.\n   */\n  const pinnedRef = useRef(-1);\n  const reportedRef = useRef(-1);\n  const reportedTile = useRef<TreemapTile | null>(null);\n\n  const onFocusChange = (point: TilePoint | null) => {\n    if (!point && pinnedRef.current >= 0) {\n      interactionRef.current?.setControlledFocus(pointAt(pinnedRef.current));\n      return;\n    }\n    const index = point ? point.datum.index : -1;\n    setReading(index);\n    if (reportedRef.current === index) return;\n    reportedRef.current = index;\n    reportedTile.current = latestTiles.current[index] ?? null;\n    if (index !== latestActive.current) latestReport.current?.(index, latestTiles.current[index] ?? null);\n    if (latestActive.current !== undefined) setAskedParent((count) => count + 1);\n  };\n\n  const pin = useCallback((index: number) => {\n    pinnedRef.current = index;\n    interactionRef.current?.setControlledFocus(index >= 0 ? pointAt(index) : null);\n  }, []);\n\n  // A readout outside the chart holds the tile it was given, so new data has to reach it even when the index stands still.\n  useEffect(() => {\n    const tile = tiles[reportedRef.current] ?? null;\n    const held = reportedTile.current;\n    reportedTile.current = tile;\n    if (held && !tile) {\n      reportedRef.current = -1;\n      setReading(-1);\n      pin(-1);\n      latestReport.current?.(-1, null);\n      return;\n    }\n    if (!tile || !held || (tile.id === held.id && tile.label === held.label && tile.value === held.value && tile.share === held.share)) return;\n    latestReport.current?.(reportedRef.current, tile);\n  }, [tiles, latestReport, pin]);\n\n  const preview = useCallback(\n    (index: number) => interactionRef.current?.setControlledFocus(pointAt(index >= 0 ? index : pinnedRef.current)),\n    []\n  );\n\n  const latestSelect = useLatest(onSelect);\n  const press = useCallback(\n    (index: number) => {\n      const tile = latestTiles.current[index];\n      if (tile) latestSelect.current?.(tile);\n      pin(index === pinnedRef.current ? -1 : index);\n    },\n    [latestSelect, latestTiles, pin]\n  );\n\n  const chartKey = `${revision}:${status}`;\n\n  /*\n   * The rect mark has no entrance of its own, so each tile grows out of its centre\n   * in CSS. From the centre because a treemap has no baseline to grow from. Only\n   * while a new chart arrives: moving a tile's node when data reorders would replay it.\n   */\n  const [settledKey, setSettledKey] = useState<string | null>(null);\n  const entranceLength = animationDuration + tiles.length * staggerDelay;\n  useEffect(() => {\n    if (!drawable) return;\n    const timer = setTimeout(() => setSettledKey(chartKey), entranceLength);\n    return () => clearTimeout(timer);\n  }, [chartKey, drawable, entranceLength]);\n  const drawnKey = useRef<string | null>(null);\n  const resetKey = useRef<string | null>(null);\n\n  /** Moves the chart to what the parent asked for. It has no points until it has drawn, so `onRender` calls this too. */\n  const applyActive = useCallback(() => {\n    const asked = latestActive.current;\n    if (asked === undefined || asked === reportedRef.current) return;\n    if (asked < 0 || pointAt(asked)) pin(asked);\n  }, [latestActive, pin]);\n\n  // Only a change the chart has not already reported is a request to move it.\n  useEffect(() => {\n    if (drawnKey.current === resetKey.current) applyActive();\n  }, [activeIndexProp, askedParent, applyActive]);\n\n  // A remounted chart says nothing about the focus it lost.\n  useEffect(() => {\n    setReading(-1);\n    pinnedRef.current = -1;\n    if (reportedRef.current !== -1) {\n      reportedRef.current = -1;\n      if (latestActive.current === undefined) latestReport.current?.(-1, null);\n    }\n    resetKey.current = chartKey;\n    if (drawnKey.current === chartKey) applyActive();\n  }, [chartKey, applyActive, latestActive, latestReport]);\n\n  const activeIndex = activeIndexProp ?? reading;\n\n  const context = useMemo<TreemapChartContextValue>(\n    () => ({\n      tiles,\n      total,\n      status,\n      aspectRatio,\n      hue,\n      animationDuration,\n      staggerDelay,\n      chartKey,\n      activeIndex,\n      setSlot,\n      preview,\n      press,\n    }),\n    [tiles, total, status, aspectRatio, hue, animationDuration, staggerDelay, chartKey, activeIndex, setSlot, preview, press]\n  );\n\n  const summary = label ?? `Treemap chart, ${tiles.length} ${tiles.length === 1 ? 'part' : 'parts'}`;\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'treemap-chart',\n        className: slotClasses.root({ className }),\n        // On the root, so it also clears a reading from a row of the breakdown.\n        onKeyDown: (event: ReactKeyboardEvent<HTMLDivElement>) => {\n          if (event.key === 'Escape') pin(-1);\n        },\n        children: (\n          <div className={slotClasses.layout()}>\n            <style>{KEYFRAMES + tileDelays(tiles.length)}</style>\n            {loading ? null : (\n              <ul aria-label={summary} className=\"sr-only\">\n                {tiles.map((tile) => (\n                  <li key={tile.id}>\n                    {labelForTile?.(tile) ?? `${tile.label}, ${tile.value}, ${Math.round(tile.share * 100)} percent`}\n                  </li>\n                ))}\n              </ul>\n            )}\n            <div\n              ref={plotRef}\n              data-slot=\"treemap-chart-plot\"\n              className={slotClasses.plot()}\n              data-entering={settledKey === chartKey ? undefined : ''}\n              style={\n                {\n                  aspectRatio,\n                  '--treemap-duration': `${animationDuration}ms`,\n                  '--treemap-stagger': `${staggerDelay}ms`,\n                } as CSSProperties\n              }\n              onClick={(event) => {\n                const point = interactionRef.current?.resolvePointer(event.clientX, event.clientY)?.point;\n                if (point) press((point.datum as TileRow).index);\n                else pin(-1);\n              }}\n              onKeyDown={(event) => {\n                if ((event.key === 'Enter' || event.key === ' ') && reading >= 0) {\n                  event.preventDefault();\n                  press(reading);\n                }\n              }}\n            >\n              {drawable ? (\n                <Chart\n                  // An entrance only plays on a chart's first paint, so tiles\n                  // arriving after a load, or a replay, are a new chart.\n                  key={chartKey}\n                  definition={definition}\n                  renderer={renderer}\n                  ariaLabel={summary}\n                  aspectRatio={aspectRatio}\n                  initialWidth={width}\n                  className={slotClasses.chart()}\n                  onFocusChange={onFocusChange}\n                  onRender={({ scene, interaction }) => {\n                    interactionRef.current = interaction;\n                    pointsRef.current = pointsOf(scene.nodes);\n                    drawnKey.current = chartKey;\n                    // A new definition repaints without the focus marks.\n                    if (pinnedRef.current >= 0) interaction.setControlledFocus(pointAt(pinnedRef.current));\n                    if (resetKey.current === chartKey) applyActive();\n                  }}\n                />\n              ) : null}\n            </div>\n            {children}\n          </div>\n        ),\n      },\n      props\n    ),\n  });\n\n  return <TreemapChartContext.Provider value={context}>{element}</TreemapChartContext.Provider>;\n});\nTreemapChartRoot.displayName = 'TreemapChart';\n\nexport interface TreemapChartTilesProps {\n  /** Opacity of the tiles that are not being read, once one is. */\n  dimOpacity?: number;\n}\n\n/**\n * Every tile. One part rather than one per datum, because a tile's box is decided\n * by every tile before it in its row. Draws nothing itself: it asks the root to.\n */\nfunction TreemapChartTiles({\n  dimOpacity = 0.35,\n}: TreemapChartTilesProps) {\n  const { setSlot } = useChart('TreemapChart.Tiles');\n  useEffect(() => {\n    setSlot('tiles', { dimOpacity });\n    return () => setSlot('tiles', undefined);\n  }, [dimOpacity, setSlot]);\n  return null;\n}\nTreemapChartTiles.displayName = 'TreemapChart.Tiles';\n\nexport interface TreemapChartSkeletonProps {\n  /** Milliseconds for one pass of the sweep. */\n  duration?: number;\n}\n\n/**\n * The box as one plain rectangle with a highlight travelling across it, shown\n * only while `status` is `loading`. Undivided on purpose: placeholder tiles would\n * be a made-up split, and a reader cannot tell an invented one from a real one.\n */\nfunction TreemapChartSkeleton({\n  duration = 1400,\n}: TreemapChartSkeletonProps) {\n  const { status, aspectRatio, hue } = useChart('TreemapChart.Skeleton');\n  const slots = treemapChartVariants();\n  if (status !== 'loading') return null;\n  return (\n    <div data-slot=\"treemap-chart-skeleton\" aria-hidden className={slots.skeleton()} style={{ aspectRatio }}>\n      <div\n        className={slots.sweep()}\n        style={{\n          background: `linear-gradient(90deg, transparent, color-mix(in oklab, ${hue} 25%, transparent), transparent)`,\n          animation: `panelui-treemap-sweep ${duration}ms linear infinite`,\n        }}\n      />\n    </div>\n  );\n}\nTreemapChartSkeleton.displayName = 'TreemapChart.Skeleton';\n\nexport interface TreemapChartLabelsProps {\n  /** Show each tile's value under its name. */\n  showValue?: boolean;\n  /** Show each tile's share of the total beside its value. */\n  showShare?: boolean;\n  /** Format the value. Defaults to a compact number. */\n  formatValue?: (value: number, tile: TreemapTile) => string;\n  className?: string;\n}\n\n/**\n * The name and reading on each tile that has room for them: stacked, then on one\n * line, then the name alone, then nothing. Tiles with no room are read through\n * `Tooltip` or `Breakdown`. Real text over the drawing, so it follows the theme's font.\n */\nfunction TreemapChartLabels({\n  showValue = true,\n  showShare = false,\n  formatValue,\n  className,\n}: TreemapChartLabelsProps) {\n  const { tiles, status, aspectRatio, animationDuration, staggerDelay, chartKey, activeIndex } =\n    useChart('TreemapChart.Labels');\n  const slots = treemapChartVariants();\n  if (status === 'loading' || !tiles.length) return null;\n\n  return (\n    <div data-slot=\"treemap-chart-labels\" aria-hidden className={slots.labels({ className })} style={{ aspectRatio }}>\n      {tiles.map((tile, index) => {\n        const percent = `${Math.round(tile.share * 100)}%`;\n        const value = showValue ? (formatValue ? formatValue(tile.value, tile) : compactNumber(tile.value)) : null;\n        const reading = value !== null && showShare ? `${value} · ${percent}` : (value ?? (showShare ? percent : null));\n        const fit = fitTileLabel(tile, tile.label, reading);\n        if (fit === 'none') return null;\n        const dimmed = activeIndex >= 0 && activeIndex !== index;\n        return (\n          <div\n            key={`${chartKey}:${tile.id}`}\n            className={slots.label()}\n            style={{\n              left: tile.x,\n              top: tile.y,\n              width: tile.width,\n              height: tile.height,\n              padding: `${LABEL_PADDING_Y}px ${LABEL_PADDING_X}px`,\n              color: tileInk(tile),\n              opacity: dimmed ? 0.45 : 1,\n              animation: `panelui-treemap-label ${animationDuration}ms ease-out ${index * staggerDelay}ms backwards`,\n            }}\n          >\n            <div className={fit === 'inline' ? 'flex items-baseline justify-between gap-1.5' : undefined}>\n              <div className={slots.labelName()}>{tile.label}</div>\n              {fit === 'name' ? null : <div className={slots.labelValue()}>{reading}</div>}\n            </div>\n          </div>\n        );\n      })}\n    </div>\n  );\n}\nTreemapChartLabels.displayName = 'TreemapChart.Labels';\n\nexport interface TreemapChartTooltipProps {\n  /** Format the value. Defaults to a compact number. */\n  formatValue?: (value: number, tile: TreemapTile) => string;\n  className?: string;\n}\n\n/** The readout for the tile being read. This is how the tiles too small to label are read. */\nfunction TreemapChartTooltip({ formatValue, className }: TreemapChartTooltipProps) {\n  const { setSlot } = useChart('TreemapChart.Tooltip');\n  const latest = useLatest({ formatValue });\n  useEffect(() => {\n    setSlot('tooltip', { className, latest });\n    return () => setSlot('tooltip', undefined);\n  }, [className, latest, setSlot]);\n  return null;\n}\nTreemapChartTooltip.displayName = 'TreemapChart.Tooltip';\n\n/** What a legend or breakdown row does: names its tile to the chart while it is pointed at, and pins it on a press. */\nfunction useRowProps(index: number) {\n  const { activeIndex, preview, press } = useChart('TreemapChart row');\n  return {\n    type: 'button' as const,\n    'aria-pressed': activeIndex === index,\n    onPointerEnter: () => preview(index),\n    onPointerLeave: () => preview(-1),\n    onFocus: () => preview(index),\n    onBlur: () => preview(-1),\n    onClick: () => press(index),\n    style: { opacity: activeIndex >= 0 && activeIndex !== index ? 0.4 : 1 },\n  };\n}\n\nfunction LegendItem({ tile, index, showShare }: { tile: TreemapTile; index: number; showShare: boolean }) {\n  const slots = treemapChartVariants();\n  return (\n    <button {...useRowProps(index)} className={slots.legendItem()}>\n      <span className={slots.swatch()} style={{ background: tileOpaque(tile) }} />\n      <span className={slots.legendName()}>{tile.label}</span>\n      {showShare ? <span className={slots.legendShare()}>{Math.round(tile.share * 100)}%</span> : null}\n    </button>\n  );\n}\n\nexport interface TreemapChartLegendProps extends ComponentProps<'div'> {\n  /** How many tiles to name before stopping. */\n  limit?: number;\n  /** Show each tile's share beside its name. */\n  showShare?: boolean;\n}\n\n/** A swatch and a name per tile, under the box. Pointing at one reads its tile, and pressing it pins the reading. */\nfunction TreemapChartLegend({\n  limit,\n  showShare = true,\n  className,\n  render,\n  ...props\n}: TreemapChartLegendProps & RenderProp<'div'>) {\n  const { tiles } = useChart('TreemapChart.Legend');\n  const slots = treemapChartVariants();\n  const shown = limit && limit > 0 ? tiles.slice(0, Math.floor(limit)) : tiles;\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'treemap-chart-legend',\n        className: slots.legend({ className }),\n        children: shown.map((tile, index) => (\n          <LegendItem key={tile.id} tile={tile} index={index} showShare={showShare} />\n        )),\n      },\n      props\n    ),\n  });\n  return tiles.length ? element : null;\n}\nTreemapChartLegend.displayName = 'TreemapChart.Legend';\n\nfunction BreakdownRow({\n  tile,\n  index,\n  value,\n  showShare,\n}: {\n  tile: TreemapTile;\n  index: number;\n  value: string;\n  showShare: boolean;\n}) {\n  const slots = treemapChartVariants();\n  return (\n    <button {...useRowProps(index)} className={slots.breakdownRow()}>\n      <span className={slots.swatch()} style={{ background: tileOpaque(tile) }} />\n      <span className={slots.breakdownName()}>{tile.label}</span>\n      <span className={slots.breakdownValue()}>\n        {value}\n        {showShare ? <span className={slots.breakdownShare()}>{Math.round(tile.share * 100)}%</span> : null}\n      </span>\n    </button>\n  );\n}\n\nexport interface TreemapChartBreakdownProps extends ComponentProps<'div'> {\n  /** How many tiles to list before stopping. */\n  limit?: number;\n  /** Show each tile's share beside its value. */\n  showShare?: boolean;\n  /** Format the value. Defaults to the full number. */\n  formatValue?: (value: number, tile: TreemapTile) => string;\n}\n\n/**\n * A table of every tile, largest first, with its exact value and share. It names\n * the tiles too small to label, and reading a row lights its tile without\n * covering anything. It sits beside the box from 448 pixels wide and under it below that.\n */\nfunction TreemapChartBreakdown({\n  limit,\n  showShare = true,\n  formatValue,\n  className,\n  render,\n  ...props\n}: TreemapChartBreakdownProps & RenderProp<'div'>) {\n  const { tiles, status } = useChart('TreemapChart.Breakdown');\n  const slots = treemapChartVariants();\n  const shown = limit && limit > 0 ? tiles.slice(0, Math.floor(limit)) : tiles;\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'treemap-chart-breakdown',\n        role: 'group',\n        'aria-label': 'Breakdown',\n        className: slots.breakdown({ className }),\n        children: shown.map((tile, index) => (\n          <BreakdownRow\n            key={tile.id}\n            tile={tile}\n            index={index}\n            value={formatValue ? formatValue(tile.value, tile) : EXACT.format(tile.value)}\n            showShare={showShare}\n          />\n        )),\n      },\n      props\n    ),\n  });\n  return status === 'loading' || !tiles.length ? null : element;\n}\nTreemapChartBreakdown.displayName = 'TreemapChart.Breakdown';\n\nexport interface TreemapChartHeaderProps extends Omit<ComponentProps<'div'>, 'title'> {\n  /** Small line above the value: what the total is of. */\n  title?: ReactNode;\n  /** The readout. The largest thing on the card, and the first thing read. */\n  value?: ReactNode;\n  /** One muted line under the value: a period, a comparison, a caveat. */\n  caption?: ReactNode;\n  /** Trailing slot: a control, a badge, a range picker. */\n  children?: ReactNode;\n}\n\n/**\n * The strip above the box. The value is not derived even though the chart knows\n * the total, because 48200 is a count, a currency or a rate depending on what was\n * counted. Pass it yourself, from `onActiveIndexChange` if it should follow the chart.\n */\nfunction TreemapChartHeader({\n  title,\n  value,\n  caption,\n  className,\n  children,\n  render,\n  ...props\n}: TreemapChartHeaderProps & RenderProp<'div'>) {\n  const slots = treemapChartVariants();\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'treemap-chart-header',\n        className: slots.header({ className }),\n        children: (\n          <>\n            <div className={slots.headerText()}>\n              {title ? <div className={slots.headerMuted()}>{title}</div> : null}\n              {value ? <div className={slots.headerValue()}>{value}</div> : null}\n              {caption ? <div className={slots.headerMuted()}>{caption}</div> : null}\n            </div>\n            {children ? <div className={slots.headerTrailing()}>{children}</div> : null}\n          </>\n        ),\n      },\n      props\n    ),\n  });\n}\nTreemapChartHeader.displayName = 'TreemapChart.Header';\n\nexport const TreemapChart = Object.assign(TreemapChartRoot, {\n  Header: TreemapChartHeader,\n  Tiles: TreemapChartTiles,\n  Skeleton: TreemapChartSkeleton,\n  Labels: TreemapChartLabels,\n  Tooltip: TreemapChartTooltip,\n  Legend: TreemapChartLegend,\n  Breakdown: TreemapChartBreakdown,\n});\n\n/* By name as well, for a Server Component, which cannot dot into a client\n   module. */\nexport {\n  TreemapChartHeader,\n  TreemapChartTiles,\n  TreemapChartSkeleton,\n  TreemapChartLabels,\n  TreemapChartTooltip,\n  TreemapChartLegend,\n  TreemapChartBreakdown,\n};\n"
    },
    {
      "path": "components/panelui/treemap-chart/squarify.ts",
      "type": "registry:component",
      "target": "@components/panelui/treemap-chart/squarify.ts",
      "content": "/** A tile's box inside the chart, in pixels. */\nexport interface TreemapRect {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n}\n\n/**\n * The aspect ratio the row test aims each tile at. The golden ratio rather than\n * 1, because aiming at a perfect square closes rows early and leaves one badly\n * shaped row at the end. Aiming slightly wide spreads that cost over all of them.\n */\nconst TARGET_RATIO = (1 + Math.sqrt(5)) / 2;\n\nfunction diceRow(\n  values: readonly number[],\n  from: number,\n  to: number,\n  sum: number,\n  out: TreemapRect[],\n  x0: number,\n  y0: number,\n  x1: number,\n  y1: number\n) {\n  const scale = sum ? (x1 - x0) / sum : 0;\n  let x = x0;\n  for (let i = from; i < to; i += 1) {\n    const width = values[i]! * scale;\n    out[i] = { x, y: y0, width, height: y1 - y0 };\n    x += width;\n  }\n}\n\nfunction sliceRow(\n  values: readonly number[],\n  from: number,\n  to: number,\n  sum: number,\n  out: TreemapRect[],\n  x0: number,\n  y0: number,\n  x1: number,\n  y1: number\n) {\n  const scale = sum ? (y1 - y0) / sum : 0;\n  let y = y0;\n  for (let i = from; i < to; i += 1) {\n    const height = values[i]! * scale;\n    out[i] = { x: x0, y, width: x1 - x0, height };\n    y += height;\n  }\n}\n\nfunction squarify(values: readonly number[], width: number, height: number, ratio: number): TreemapRect[] {\n  const count = values.length;\n  const out: TreemapRect[] = new Array(count);\n  let remaining = 0;\n  for (let i = 0; i < count; i += 1) remaining += values[i]!;\n\n  let x0 = 0;\n  let y0 = 0;\n  let start = 0;\n  let end = 0;\n\n  while (start < count) {\n    const dx = width - x0;\n    const dy = height - y0;\n    if (dx <= 0 || dy <= 0) break;\n\n    // A run of zeros takes no area, and dividing by one would break the row test.\n    let sum = 0;\n    do {\n      sum = values[end]!;\n      end += 1;\n    } while (!sum && end < count);\n\n    let smallest = sum;\n    let largest = sum;\n\n    // Folds what does not change inside the row into one factor, so the test is\n    // a couple of multiplications per tile.\n    const alpha = Math.max(dy / dx, dx / dy) / (remaining * ratio);\n    let beta = sum * sum * alpha;\n    let worst = Math.max(largest / beta, beta / smallest);\n\n    for (; end < count; end += 1) {\n      const value = values[end]!;\n      sum += value;\n      if (value < smallest) smallest = value;\n      if (value > largest) largest = value;\n      beta = sum * sum * alpha;\n      const next = Math.max(largest / beta, beta / smallest);\n      // The first tile that makes the row worse is put back for the next one.\n      if (next > worst) {\n        sum -= value;\n        break;\n      }\n      worst = next;\n    }\n\n    // Along the shorter side: dividing the long one gives thin tiles.\n    if (dx < dy) {\n      const edge = remaining ? y0 + (dy * sum) / remaining : height;\n      diceRow(values, start, end, sum, out, x0, y0, width, edge);\n      y0 = edge;\n    } else {\n      const edge = remaining ? x0 + (dx * sum) / remaining : width;\n      sliceRow(values, start, end, sum, out, x0, y0, edge, height);\n      x0 = edge;\n    }\n\n    remaining -= sum;\n    start = end;\n  }\n\n  // A box that ran out of room before the tiles did leaves holes in the array.\n  for (let i = 0; i < count; i += 1) {\n    if (!out[i]) out[i] = { x: x0, y: y0, width: 0, height: 0 };\n  }\n  return out;\n}\n\n/**\n * Squarified treemap layout: values in, rectangles out, in the same order.\n *\n * `tileAspect` stretches the result sideways. The row test runs in a narrower box\n * and the tiles are widened afterwards, so `2` aims at tiles twice as wide as\n * they would have been, which leaves room for a name across a short chart.\n *\n * @param values Tile sizes. Negative and non-finite values count as zero. Should be descending.\n * @param ratio The aspect ratio the row test aims at.\n * @param tileAspect How much wider than the row test's shape each tile is drawn.\n */\nexport function squarifyLayout(\n  values: readonly number[],\n  width: number,\n  height: number,\n  ratio: number = TARGET_RATIO,\n  tileAspect: number = 1\n): TreemapRect[] {\n  const clean = values.map((value) => (Number.isFinite(value) ? Math.max(0, value) : 0));\n  if (!clean.some((value) => value > 0) || width <= 0 || height <= 0) {\n    return clean.map(() => ({ x: 0, y: 0, width: 0, height: 0 }));\n  }\n  const stretch = tileAspect > 0 ? tileAspect : 1;\n  return squarify(clean, width / stretch, height, ratio).map((rect) => ({\n    ...rect,\n    x: rect.x * stretch,\n    width: rect.width * stretch,\n  }));\n}\n\n/** How a tile's text fits: two lines, one line, its name alone, or not at all. */\nexport type TileLabelFit = 'stacked' | 'inline' | 'name' | 'none';\n\nexport const LABEL_PADDING_X = 8;\nexport const LABEL_PADDING_Y = 6;\nexport const LABEL_LINE = 16;\n\nconst NAME_SIZE = 12;\nconst VALUE_SIZE = 12;\nconst CHAR_WIDTH = 0.56;\nconst INLINE_GAP = 6;\n\n// shortcut: an average character width rather than measuring, so an unusually wide name can still ellipsize; measure if that shows up.\nconst textWidth = (text: string, size: number) => text.length * size * CHAR_WIDTH;\n\n/**\n * Which text a tile has room for. The value goes before the name does, and a\n * name that would not fit is left off, because a name cut to its first letters\n * reads as a different word. Those tiles are read through the tooltip.\n */\nexport function fitTileLabel(rect: Pick<TreemapRect, 'width' | 'height'>, name: string, value: string | null): TileLabelFit {\n  const innerWidth = rect.width - LABEL_PADDING_X * 2;\n  const innerHeight = rect.height - LABEL_PADDING_Y * 2;\n  const nameWidth = textWidth(name, NAME_SIZE);\n  if (innerHeight < LABEL_LINE || nameWidth > innerWidth) return 'none';\n  if (value === null) return 'name';\n  const valueWidth = textWidth(value, VALUE_SIZE);\n  if (innerHeight >= LABEL_LINE * 2 && valueWidth <= innerWidth) return 'stacked';\n  return nameWidth + INLINE_GAP + valueWidth <= innerWidth ? 'inline' : 'name';\n}\n"
    }
  ]
}
