{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-tiles",
  "title": "Chart tiles",
  "description": "What the charts drawn as nested boxes share: the tree a chart’s rows make, the part of it in view, its groups and tiles laid out by d3-hierarchy’s squarify with room for each group’s header, where a box comes from and goes to when the view zooms in or out, and whether a label fits its box; the same tree packed as nested circles by d3-hierarchy’s pack, the one move that zooms the packing to a part, the circle under the pointer, and whether a label fits a circle; and the same tree laid round a turn by d3-hierarchy’s partition, as rings from the part in view, with where each arc comes from and goes to. The Treemap, Circle packing and Sunburst charts draw on it.",
  "dependencies": [
    "d3-hierarchy"
  ],
  "devDependencies": [
    "@types/d3-hierarchy"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/chart-math.json"
  ],
  "files": [
    {
      "path": "registry/lib/chart-tiles.ts",
      "content": "import type { ChartConfig, ChartDatum, ReadingDirection } from '@/registry/lib/chart-math'\nimport { hierarchy, type HierarchyNode, pack, partition, treemap } from 'd3-hierarchy'\n\n/*\n * The tiles of a chart drawn as nested boxes sized by value, such as a\n * treemap: the tree its rows make, the part of it in view, the boxes\n * d3-hierarchy's squarify lays it out in, where a box comes from and goes to\n * when the view zooms in or out, and whether a label fits its box. Pure, so\n * the chart only draws.\n */\n\n/** A node of the tree: a row, and the rows under its `children`. */\ninterface TileNode {\n  /** Its path joined, unique in the tree: the root's is the empty string. */\n  key: string\n  /** The `index` values from the top down to it, as text. */\n  path: readonly string[]\n  /** Its own `index` value. */\n  name: unknown\n  datum: ChartDatum\n  /** Its own value, or its children's added up; never below zero. */\n  value: number\n  /** Whether it has no value to say: a row's that isn't a number, or every child's. */\n  missing: boolean\n  children: readonly TileNode[]\n}\n\n/** A box, as fractions of the plot from its physical left and its top. */\ninterface TileBox {\n  x0: number\n  y0: number\n  x1: number\n  y1: number\n}\n\n/** A tile in view: a node, the group it sits in, and its box. */\ninterface LaidTile {\n  key: string\n  node: TileNode\n  /** The group around it, or none for a tile that is a group of its own. */\n  group: TileNode | null\n  /** The top of the tree it is under: its path's first name, its key in the config. */\n  top: string\n  box: TileBox\n}\n\n/** A group in view: a node whose children are tiles, its box, and whether it has room for a header. */\ninterface LaidGroup {\n  key: string\n  node: TileNode\n  top: string\n  box: TileBox\n  header: boolean\n}\n\ninterface TileLayout {\n  view: TileNode\n  groups: readonly LaidGroup[]\n  tiles: readonly LaidTile[]\n}\n\n/** What separates the names of a path in a node's key. */\nconst PATH_SEPARATOR = '\\u001f'\n\n/** The room a group's header takes above its tiles, in px. */\nconst HEADER_HEIGHT = 20\n\n/** The least room a group keeps for its tiles under a header, in px, or it has none. */\nconst LEAST_UNDER_HEADER = 24\n\n/** The narrowest group that has a header, in px. */\nconst LEAST_HEADER_WIDTH = 48\n\n/** A label's room inside its tile, in px: its padding, and a line of the chart's text. */\nconst LABEL_PADDING = 6\nconst LABEL_LINE = 16\n\n/** The room between a header's name and its worth. */\nconst HEADER_SPACE = 8\n\n/** How near an edge, in px, a box counts as touching it. */\nconst EDGE = 1e-6\n\nfunction keyOf(path: readonly string[]) {\n  return path.join(PATH_SEPARATOR)\n}\n\n/** A value above zero, or zero for one missing, not a number, or below zero. */\nfunction positive(value: unknown) {\n  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0\n}\n\n/**\n * The tree `rows` make: each row a node, named by its `index` value, worth\n * its `dataKey` value, with the rows under its `children` inside it, which\n * it is then worth together. Rows that aren't objects are left out.\n */\nfunction tileTree(rows: readonly ChartDatum[], index: string, dataKey: string): TileNode {\n  const build = (datum: ChartDatum, path: readonly string[]): TileNode => {\n    const below = datum.children\n    const children = Array.isArray(below)\n      ? below\n          .filter(\n            (row): row is ChartDatum =>\n              typeof row === 'object' && row !== null && !Array.isArray(row),\n          )\n          .map((row) => build(row, [...path, String(row[index])]))\n      : []\n    return {\n      key: keyOf(path),\n      path,\n      name: datum[index],\n      datum,\n      value:\n        children.length > 0\n          ? children.reduce((sum, child) => sum + child.value, 0)\n          : positive(datum[dataKey]),\n      missing:\n        children.length > 0\n          ? children.every((child) => child.missing)\n          : !(typeof datum[dataKey] === 'number' && Number.isFinite(datum[dataKey])),\n      children,\n    }\n  }\n  return build({ children: rows }, [])\n}\n\n/**\n * The node `path` leads to, as far as the tree has it, that has children to\n * show: a path to a leaf, or past the tree's end, stops at the deepest node\n * on the way that has some.\n */\nfunction tileNodeAt(root: TileNode, path: readonly string[]): TileNode {\n  let node = root\n  for (const name of path) {\n    const next = node.children.find((child) => child.path.at(-1) === name)\n    if (!next || next.children.length === 0) break\n    node = next\n  }\n  return node\n}\n\n/** The nodes from the root down to `node`'s parent, which a way back out shows. */\nfunction tileAncestors(root: TileNode, node: TileNode): TileNode[] {\n  const out: TileNode[] = []\n  let at = root\n  for (const name of node.path) {\n    out.push(at)\n    const next = at.children.find((child) => child.path.at(-1) === name)\n    if (!next) break\n    at = next\n  }\n  return out\n}\n\n/** Biggest first; a tie keeps the order of the data. */\nfunction bySize(nodes: readonly TileNode[]) {\n  return nodes.toSorted((a, b) => b.value - a.value)\n}\n\n/**\n * The tiles `view` shows, in the order the keys step through them: its\n * children, biggest first, each the group of its own children, biggest\n * first, or a tile of its own when it has none. Tops in `hidden` are left\n * out at the root.\n */\nfunction viewTiles(\n  view: TileNode,\n  hidden: readonly string[] = [],\n): { node: TileNode; group: TileNode | null }[] {\n  const shown = view.children.filter(\n    (child) => view.path.length > 0 || !hidden.includes(child.path[0] ?? ''),\n  )\n  return bySize(shown).flatMap((group): { node: TileNode; group: TileNode | null }[] =>\n    group.children.length > 0\n      ? bySize(group.children).map((node) => ({ node, group }))\n      : [{ node: group, group: null }],\n  )\n}\n\n/**\n * Lays `nodes` out in a box `width` by `height` px with squarify, `gap` px\n * apart, biggest first. With a `shape` (width over height), they are laid\n * out in a box of that shape and the same area, then stretched to fit, so a\n * group zoomed into keeps the arrangement it had.\n */\nfunction squarify(\n  nodes: readonly TileNode[],\n  width: number,\n  height: number,\n  gap: number,\n  shape?: number,\n): { node: TileNode; x0: number; y0: number; x1: number; y1: number }[] {\n  const across = Math.max(0, width)\n  const down = Math.max(0, height)\n  const shaped =\n    shape !== undefined && Number.isFinite(shape) && shape > 0 && across * down > 0\n  const laidWidth = shaped ? Math.sqrt(across * down * shape) : across\n  const laidHeight = shaped ? Math.sqrt((across * down) / shape) : down\n  const root = hierarchy<{ node?: TileNode; nodes?: readonly TileNode[] }>(\n    { nodes },\n    (datum) => datum.nodes?.map((node) => ({ node })),\n  )\n    .sum((datum) => datum.node?.value ?? 0)\n    .sort((a, b) => (b.value ?? 0) - (a.value ?? 0))\n  const laid = treemap<{ node?: TileNode }>().size([laidWidth, laidHeight]).round(false)(\n    root as HierarchyNode<{ node?: TileNode }>,\n  )\n  const stretchX = laidWidth === 0 ? 0 : across / laidWidth\n  const stretchY = laidHeight === 0 ? 0 : down / laidHeight\n  // The gap goes in after the stretch, half on each side that meets another\n  // box, so it stays `gap` px both ways and the outer edges stay flush.\n  const half = gap / 2\n  const inset = (start: number, end: number, size: number) => ({\n    start: start > EDGE ? start + half : start,\n    end: end < size - EDGE ? end - half : end,\n  })\n  return (laid.children ?? []).map((child) => {\n    const x = inset(child.x0 * stretchX, child.x1 * stretchX, across)\n    const y = inset(child.y0 * stretchY, child.y1 * stretchY, down)\n    return {\n      node: child.data.node!,\n      x0: x.start,\n      y0: y.start,\n      x1: Math.max(x.start, x.end),\n      y1: Math.max(y.start, y.end),\n    }\n  })\n}\n\ntype TileLayoutOptions = {\n  width: number\n  height: number\n  groupGap: number\n  tileGap: number\n  direction: ReadingDirection\n  hidden?: readonly string[]\n  shape?: number\n}\n\n/**\n * The boxes of `view`'s groups and tiles in a plot `width` by `height` px:\n * the groups by their worth with `groupGap` px between them, a header above\n * the tiles of each group with the room for one, and the tiles inside with\n * `tileGap` px between them. Right to left mirrors it. Tops in `hidden` are\n * left out at the root. A `shape` lays the groups out as they sat in a box\n * of that shape (`viewShape`).\n */\nfunction tileLayout(\n  view: TileNode,\n  { width, height, groupGap, tileGap, direction, hidden = [], shape }: TileLayoutOptions,\n): TileLayout {\n  const shown = view.children.filter(\n    (child) => view.path.length > 0 || !hidden.includes(child.path[0] ?? ''),\n  )\n  const box = (x0: number, y0: number, x1: number, y1: number): TileBox => {\n    const left = width === 0 ? 0 : x0 / width\n    const right = width === 0 ? 0 : x1 / width\n    return {\n      x0: direction === 'rtl' ? 1 - right : left,\n      x1: direction === 'rtl' ? 1 - left : right,\n      y0: height === 0 ? 0 : y0 / height,\n      y1: height === 0 ? 0 : y1 / height,\n    }\n  }\n  const groups: LaidGroup[] = []\n  const tiles: LaidTile[] = []\n  for (const laid of squarify(shown, width, height, groupGap, shape)) {\n    const { node } = laid\n    const top = node.path[0] ?? ''\n    if (node.children.length === 0) {\n      tiles.push({\n        key: node.key,\n        node,\n        group: null,\n        top,\n        box: box(laid.x0, laid.y0, laid.x1, laid.y1),\n      })\n      continue\n    }\n    const header =\n      laid.y1 - laid.y0 >= HEADER_HEIGHT + LEAST_UNDER_HEADER &&\n      laid.x1 - laid.x0 >= LEAST_HEADER_WIDTH\n    const under = header ? HEADER_HEIGHT : 0\n    groups.push({\n      key: node.key,\n      node,\n      top,\n      box: box(laid.x0, laid.y0, laid.x1, laid.y1),\n      header,\n    })\n    for (const inner of squarify(\n      node.children,\n      laid.x1 - laid.x0,\n      laid.y1 - laid.y0 - under,\n      tileGap,\n    )) {\n      tiles.push({\n        key: inner.node.key,\n        node: inner.node,\n        group: node,\n        top,\n        box: box(\n          laid.x0 + inner.x0,\n          laid.y0 + under + inner.y0,\n          laid.x0 + inner.x1,\n          laid.y0 + under + inner.y1,\n        ),\n      })\n    }\n  }\n  return { view, groups, tiles }\n}\n\n/** `inner`, a box of the whole plot, drawn inside `frame` instead. */\n/**\n * The shape (width over height) the tiles of the view at `path` had in the\n * view above it, walking down from `root`, so zooming in keeps them where\n * they were, only bigger. None at the root, or for a path that isn't laid out.\n */\nfunction viewShape(\n  root: TileNode,\n  path: readonly string[],\n  options: Omit<TileLayoutOptions, 'shape'>,\n): number | undefined {\n  const view = tileNodeAt(root, path)\n  let node = root\n  let shape: number | undefined\n  for (const name of view.path) {\n    const layout = tileLayout(node, { ...options, shape })\n    const next = node.children.find((child) => child.path.at(-1) === name)\n    const group = layout.groups.find((laid) => laid.key === next?.key)\n    if (!next || !group) return undefined\n    const across = (group.box.x1 - group.box.x0) * options.width\n    const down =\n      (group.box.y1 - group.box.y0) * options.height - (group.header ? HEADER_HEIGHT : 0)\n    if (!(across > 0 && down > 0)) return undefined\n    shape = across / down\n    node = next\n  }\n  return shape\n}\n\nfunction boxWithin(inner: TileBox, frame: TileBox): TileBox {\n  const width = frame.x1 - frame.x0\n  const height = frame.y1 - frame.y0\n  return {\n    x0: frame.x0 + inner.x0 * width,\n    x1: frame.x0 + inner.x1 * width,\n    y0: frame.y0 + inner.y0 * height,\n    y1: frame.y0 + inner.y1 * height,\n  }\n}\n\n/**\n * `box` once `frame` is stretched to fill the plot, the reverse of\n * `boxWithin`, cut to the plot's edges, so a box pushed out of it lies\n * flat against the edge it went past.\n */\nfunction boxOutOf(box: TileBox, frame: TileBox): TileBox {\n  const width = frame.x1 - frame.x0\n  const height = frame.y1 - frame.y0\n  const clamp = (value: number) => Math.min(1, Math.max(0, value))\n  if (width <= 0 || height <= 0) return box\n  return {\n    x0: clamp((box.x0 - frame.x0) / width),\n    x1: clamp((box.x1 - frame.x0) / width),\n    y0: clamp((box.y0 - frame.y0) / height),\n    y1: clamp((box.y1 - frame.y0) / height),\n  }\n}\n\n/** A box with no size, at the middle of `box`: where a tile grows from and shrinks into. */\nfunction centreOf(box: TileBox): TileBox {\n  const x = (box.x0 + box.x1) / 2\n  const y = (box.y0 + box.y1) / 2\n  return { x0: x, x1: x, y0: y, y1: y }\n}\n\n/**\n * A top's colour: its own from the config, or the next of the chart's\n * colours for a top the config leaves out, whose name may not be a CSS\n * variable's.\n */\nfunction topColor(series: readonly string[], config: ChartConfig, top: string) {\n  const ramp = `var(--chart-${(Math.max(0, series.indexOf(top)) % 5) + 1})`\n  return config[top] ? `var(--color-${top}, ${ramp})` : ramp\n}\n\n/** Whether `path` starts with `start`, or is it. */\nfunction startsWith(path: readonly string[], start: readonly string[]) {\n  return start.length <= path.length && start.every((name, at) => path[at] === name)\n}\n\n/** The box `layout` shows for the node at `path`, or for its nearest ancestor it shows. */\nfunction shownBox(layout: TileLayout, path: readonly string[]): TileBox | null {\n  let best: { length: number; box: TileBox } | null = null\n  for (const shown of [...layout.groups, ...layout.tiles]) {\n    const length = shown.node.path.length\n    if (startsWith(path, shown.node.path) && (!best || length > best.length)) {\n      best = { length, box: shown.box }\n    }\n  }\n  return best?.box ?? null\n}\n\n/**\n * Where each box that arrives with `now` comes from, and where each box that\n * leaves with it goes, by key, after the view was `was`. Zooming in, what\n * arrives grows out of where the new view sat, and what leaves is pushed\n * past the plot's edges; zooming out, the reverse. Otherwise, what arrives\n * grows from its box's centre, and what leaves shrinks into it. A box in\n * both moves between them.\n */\nfunction tileMoves(\n  was: TileLayout | null,\n  now: TileLayout,\n): { from: Map<string, TileBox>; to: Map<string, TileBox> } {\n  const from = new Map<string, TileBox>()\n  const to = new Map<string, TileBox>()\n  if (!was) return { from, to }\n  const all = (layout: TileLayout) => [...layout.groups, ...layout.tiles]\n  const before = new Map(all(was).map((shown) => [shown.key, shown.box]))\n  const after = new Map(all(now).map((shown) => [shown.key, shown.box]))\n  const zoomedIn =\n    now.view.key !== was.view.key && startsWith(now.view.path, was.view.path)\n  const zoomedOut =\n    now.view.key !== was.view.key && startsWith(was.view.path, now.view.path)\n  // Zooming in, where the new view sat before; zooming out, where the old one sits now.\n  const frame = zoomedIn\n    ? shownBox(was, now.view.path)\n    : zoomedOut\n      ? shownBox(now, was.view.path)\n      : null\n  for (const [key, box] of after) {\n    if (before.has(key)) continue\n    from.set(\n      key,\n      !frame ? centreOf(box) : zoomedIn ? boxWithin(box, frame) : boxOutOf(box, frame),\n    )\n  }\n  for (const [key, box] of before) {\n    if (after.has(key)) continue\n    to.set(\n      key,\n      !frame ? centreOf(box) : zoomedIn ? boxOutOf(box, frame) : boxWithin(box, frame),\n    )\n  }\n  return { from, to }\n}\n\n/**\n * What a tile's label can show in a box `width` by `height` px: its name\n * and value on two lines, its name only, or nothing, never cut short.\n */\nfunction labelFit(\n  width: number,\n  height: number,\n  nameWidth: number,\n  valueWidth: number,\n  wanted: 'value' | 'name' | 'none',\n): 'value' | 'name' | 'none' {\n  if (wanted === 'none') return 'none'\n  const room = width - LABEL_PADDING * 2\n  if (\n    wanted === 'value' &&\n    room >= Math.max(nameWidth, valueWidth) &&\n    height >= LABEL_LINE * 2 + LABEL_PADDING * 2\n  ) {\n    return 'value'\n  }\n  if (room >= nameWidth && height >= LABEL_LINE + LABEL_PADDING * 2) return 'name'\n  return 'none'\n}\n\n/**\n * What a group's header can show across `width` px: its name and worth,\n * 8px apart, its name only, or nothing, never cut short.\n */\nfunction headerFit(\n  width: number,\n  nameWidth: number,\n  valueWidth: number,\n): 'value' | 'name' | 'none' {\n  const room = width - LABEL_PADDING * 2\n  if (room >= nameWidth + HEADER_SPACE + valueWidth) return 'value'\n  if (room >= nameWidth) return 'name'\n  return 'none'\n}\n\nfunction inBox(box: TileBox, x: number, y: number) {\n  return x >= box.x0 && x <= box.x1 && y >= box.y0 && y <= box.y1\n}\n\n/** How far a point is from a box, in px; none inside it. */\nfunction boxDistance(box: TileBox, x: number, y: number, width: number, height: number) {\n  const dx = Math.max(box.x0 - x, 0, x - box.x1) * width\n  const dy = Math.max(box.y0 - y, 0, y - box.y1) * height\n  return Math.hypot(dx, dy)\n}\n\n/**\n * What sits at `point`, in px from the plot's top left corner: a group's\n * header, or the tile under it, or the nearest within `reach` px, so a\n * pointer in the gap between tiles still finds one. A tile is its place in\n * `tiles`, where none (a tile leaving) can't be found.\n */\nfunction tileAt(\n  point: { x: number; y: number },\n  {\n    width,\n    height,\n    groups,\n    tiles,\n    reach,\n  }: {\n    width: number\n    height: number\n    groups: readonly LaidGroup[]\n    tiles: readonly ({ box: TileBox } | null)[]\n    reach: number\n  },\n): { tile: number } | { group: LaidGroup } | null {\n  if (width === 0 || height === 0) return null\n  const x = point.x / width\n  const y = point.y / height\n  const header = groups.find(\n    (group) =>\n      group.header && inBox(group.box, x, y) && y < group.box.y0 + HEADER_HEIGHT / height,\n  )\n  if (header) return { group: header }\n  let best: number | null = null\n  let nearest = reach\n  for (const [at, tile] of tiles.entries()) {\n    if (!tile) continue\n    const distance = boxDistance(tile.box, x, y, width, height)\n    if (distance <= nearest) {\n      best = at\n      nearest = distance\n    }\n  }\n  return best === null ? null : { tile: best }\n}\n\n/* Circles: the tree packed as nested circles, such as circle packing's. */\n\n/** A circle of the packing, in px from the plot's top left corner. */\ninterface PackedCircle {\n  key: string\n  node: TileNode\n  /** The top of the tree it is under: its path's first name, its key in the config. */\n  top: string\n  /** How deep it sits: 1 for a top. */\n  depth: number\n  x: number\n  y: number\n  r: number\n}\n\n/** The plot's inscribed circle, which the whole fills and the part in view is zoomed to fill. */\ninterface PackWindow {\n  x: number\n  y: number\n  r: number\n}\n\ninterface PackLayout {\n  window: PackWindow\n  /** Every node but the whole, depth first, a parent before its children, biggest first. */\n  circles: readonly PackedCircle[]\n  byKey: ReadonlyMap<string, PackedCircle>\n}\n\n/**\n * The tree packed as circles in a plot `width` by `height` px with d3's\n * pack, each leaf's area as its value, `padding` px between siblings and\n * inside a parent's edge, biggest first, the whole in the plot's inscribed\n * circle. Right to left mirrors it. Tops in `hidden` are left out, and the\n * rest take their room. Deterministic: d3's pack has no randomness.\n */\nfunction packLayout(\n  root: TileNode,\n  {\n    width,\n    height,\n    padding,\n    direction,\n    hidden = [],\n  }: {\n    width: number\n    height: number\n    padding: number\n    direction: ReadingDirection\n    hidden?: readonly string[]\n  },\n): PackLayout {\n  const side = Math.max(0, Math.min(width, height))\n  const window = { x: width / 2, y: height / 2, r: side / 2 }\n  const shown: TileNode = {\n    ...root,\n    children: root.children.filter((child) => !hidden.includes(child.path[0] ?? '')),\n  }\n  const tree = hierarchy(shown, (node) => node.children)\n    .sum((node) => (node.children.length > 0 ? 0 : node.value))\n    .sort((a, b) => (b.value ?? 0) - (a.value ?? 0))\n  const circles: PackedCircle[] = []\n  const place = (node: HierarchyNode<TileNode>, x: number, y: number, r: number) => {\n    if (node.depth === 0) return\n    circles.push({\n      key: node.data.key,\n      node: node.data,\n      top: node.data.path[0] ?? '',\n      depth: node.depth,\n      x: direction === 'rtl' ? width - x : x,\n      y,\n      r,\n    })\n  }\n  if ((tree.value ?? 0) > 0 && side > 0) {\n    const offsetX = (width - side) / 2\n    const offsetY = (height - side) / 2\n    pack<TileNode>()\n      .size([side, side])\n      .padding(padding)(tree)\n      .eachBefore((node) => place(node, node.x + offsetX, node.y + offsetY, node.r))\n  } else {\n    // With nothing to pack, every circle sits at the middle with no size, where it grows from.\n    tree.eachBefore((node) => place(node, window.x, window.y, 0))\n  }\n  return {\n    window,\n    circles,\n    byKey: new Map(circles.map((circle) => [circle.key, circle])),\n  }\n}\n\n/** How the packing is drawn: each point at `x + k * px`, `y + k * py`, one translate and scale of the whole layer. */\ninterface PackView {\n  k: number\n  x: number\n  y: number\n}\n\n/**\n * How the packing is drawn with `view` filling the window. The whole, or a\n * node not laid out or of no size, is drawn as it lies.\n */\nfunction packView(layout: PackLayout, view: TileNode): PackView {\n  const circle = layout.byKey.get(view.key)\n  if (!circle || circle.r <= 0 || layout.window.r <= 0) return { k: 1, x: 0, y: 0 }\n  const k = layout.window.r / circle.r\n  return { k, x: layout.window.x - k * circle.x, y: layout.window.y - k * circle.y }\n}\n\n/** Where a circle's centre is drawn under `view`, in px from the plot's top left corner. */\nfunction packPoint(circle: { x: number; y: number }, view: PackView) {\n  return { x: view.x + view.k * circle.x, y: view.y + view.k * circle.y }\n}\n\n/**\n * The key of the circle at `point`, in px from the plot's top left corner,\n * among the circles inside `view` as `shown` draws them: the deepest one\n * the point is in, a group when it falls between the group's own circles,\n * or else the nearest of the view's own children within `reach` px. None\n * outside the window, where nothing of the view is drawn.\n */\nfunction packAt(\n  point: { x: number; y: number },\n  layout: PackLayout,\n  view: TileNode,\n  shown: PackView,\n  reach: number,\n): string | null {\n  const { window } = layout\n  if (shown.k <= 0 || Math.hypot(point.x - window.x, point.y - window.y) > window.r)\n    return null\n  const x = (point.x - shown.x) / shown.k\n  const y = (point.y - shown.y) / shown.k\n  const inside = (circle: PackedCircle) =>\n    circle.r > 0 && Math.hypot(x - circle.x, y - circle.y) <= circle.r\n  const circlesOf = (node: TileNode) =>\n    node.children.flatMap((child) => layout.byKey.get(child.key) ?? [])\n  let at: PackedCircle | null = null\n  for (let node = view; ;) {\n    const next = circlesOf(node).find(inside)\n    if (!next) break\n    at = next\n    node = next.node\n  }\n  if (at) return at.key\n  let best: string | null = null\n  let nearest = reach\n  for (const circle of circlesOf(view)) {\n    if (circle.r <= 0) continue\n    const gap = (Math.hypot(x - circle.x, y - circle.y) - circle.r) * shown.k\n    // The first of two as near keeps it, so the bigger one wins.\n    if (gap <= reach && (best === null || gap < nearest)) {\n      best = circle.key\n      nearest = gap\n    }\n  }\n  return best\n}\n\n/** The room kept between a circle's edge and the corners of its label, in px. */\nconst CIRCLE_LABEL_INSET = 4\n\n/**\n * What a label centred on a circle `radius` px across can show: its name\n * and value on two lines, its name only, or nothing, the box's corners kept\n * inside the edge, never cut short.\n */\nfunction circleLabelFit(\n  radius: number,\n  nameWidth: number,\n  valueWidth: number,\n  wanted: 'value' | 'name' | 'none',\n): 'value' | 'name' | 'none' {\n  if (wanted === 'none') return 'none'\n  const room = radius - CIRCLE_LABEL_INSET\n  const fits = (width: number, lines: number) =>\n    room > 0 && Math.hypot(width / 2, (lines * LABEL_LINE) / 2) <= room\n  if (wanted === 'value' && fits(Math.max(nameWidth, valueWidth), 2)) return 'value'\n  if (fits(nameWidth, 1)) return 'name'\n  return 'none'\n}\n\n/*\n * Rings: a tree laid out as arcs round a centre, such as a sunburst's. Each\n * node takes its share of its parent's turn, by d3-hierarchy's partition,\n * and a ring for its depth below the part in view. Places are fractions, of\n * a turn clockwise from the top and of the room from the hole to the edge,\n * so a zoom or new data moves each arc by straight lines between two places.\n */\n\n/** A node's place round the whole: its share of the turn from the top, and its depth below the whole. */\ninterface RingNode {\n  key: string\n  node: TileNode\n  /** The top of the tree it is under: its path's first name, its key in the config. */\n  top: string\n  /** 1 for a top. */\n  depth: number\n  start: number\n  end: number\n}\n\n/**\n * Where an arc sits: `start` to `end` round the turn, clockwise from the\n * top, and `inner` to `outer` across the rings, as fractions of the room\n * from the hole to the edge.\n */\ninterface ArcPlace {\n  start: number\n  end: number\n  inner: number\n  outer: number\n}\n\n/** An arc in view: a node, its place, and its depth below the whole. */\ninterface RingArc extends ArcPlace {\n  key: string\n  node: TileNode\n  top: string\n  depth: number\n}\n\ninterface RingLayout {\n  /** The part in view, which the arcs ring. */\n  view: TileNode\n  /** How many rings the view shows. */\n  rings: number\n  /** The arcs in view, depth first: a parent, then its children clockwise. */\n  arcs: readonly RingArc[]\n  /** Every node's place round the whole, by key, the hidden tops' left out. */\n  places: ReadonlyMap<string, RingNode>\n}\n\n/** The most rings a chart of rings shows from the part in view. */\nconst RINGS = 3\n\n/**\n * Every node below `root`, but those under a top in `hidden`, laid round a\n * whole turn by d3's partition, depth first: a parent, then its children\n * clockwise, biggest first, or with `sort` false in the data's order.\n */\nfunction ringTree(\n  root: TileNode,\n  { hidden = [], sort = true }: { hidden?: readonly string[]; sort?: boolean } = {},\n): RingNode[] {\n  const tree = hierarchy<TileNode>(root, (node) =>\n    node.path.length === 0\n      ? node.children.filter((child) => !hidden.includes(child.path[0] ?? ''))\n      : node.children,\n  ).sum((node) => (node.children.length > 0 ? 0 : node.value))\n  // A stable sort, so a tie keeps the data's order.\n  if (sort) tree.sort((a, b) => (b.value ?? 0) - (a.value ?? 0))\n  const laid = partition<TileNode>().size([1, 1]).round(false)(tree)\n  const out: RingNode[] = []\n  laid.eachBefore((placed) => {\n    if (placed.depth === 0) return\n    out.push({\n      key: placed.data.key,\n      node: placed.data,\n      top: placed.data.path[0] ?? '',\n      depth: placed.depth,\n      // A whole worth nothing gives every node an empty share at the top.\n      start: Number.isFinite(placed.x0) ? placed.x0 : 0,\n      end: Number.isFinite(placed.x1) ? placed.x1 : 0,\n    })\n  })\n  return out\n}\n\nfunction clampUnit(value: number) {\n  return Math.min(1, Math.max(0, value))\n}\n\n/**\n * Where the node at `place` sits once `window`, a part's share of the turn\n * at `depth`, fills the turn with `rings` rings round it: a node outside the\n * window folds to the top, at its start or its end, and one above the\n * window's depth into the hole, one past the last ring onto the edge.\n */\nfunction placeIn(\n  place: Pick<RingNode, 'start' | 'end' | 'depth'>,\n  window: { start: number; end: number; depth: number },\n  rings: number,\n): ArcPlace {\n  const span = window.end - window.start\n  const turn = (at: number) => (span > 0 ? clampUnit((at - window.start) / span) : 0)\n  const ring = (depth: number) => clampUnit((depth - window.depth) / rings)\n  return {\n    start: turn(place.start),\n    end: turn(place.end),\n    inner: ring(place.depth - 1),\n    outer: ring(place.depth),\n  }\n}\n\n/** The window a part in view fills: its own share of the turn, or the whole turn for the whole. */\nfunction windowOf(layout: Pick<RingLayout, 'view' | 'places'>) {\n  const own = layout.places.get(layout.view.key)\n  return own ?? { start: 0, end: 1, depth: 0 }\n}\n\n/**\n * The arcs `view` shows, out of the places `ringTree` laid round the whole:\n * every node under it on up to `rings` rings, fewer where the tree under it\n * is shallower, so its rings fill the room.\n */\nfunction ringLayout(\n  view: TileNode,\n  places: readonly RingNode[],\n  rings: number = RINGS,\n): RingLayout {\n  const byKey = new Map(places.map((place) => [place.key, place]))\n  const depth = view.path.length\n  const under = places.filter(\n    (place) => place.depth > depth && startsWith(place.node.path, view.path),\n  )\n  const deepest = under.reduce((most, place) => Math.max(most, place.depth - depth), 0)\n  const count = Math.max(1, Math.min(rings, deepest))\n  const window = windowOf({ view, places: byKey })\n  const arcs = under\n    .filter((place) => place.depth - depth <= count)\n    .map((place) => ({\n      key: place.key,\n      node: place.node,\n      top: place.top,\n      depth: place.depth,\n      ...placeIn(place, window, count),\n    }))\n  return { view, rings: count, arcs, places: byKey }\n}\n\n/** An empty place at the middle of `place`'s turn: where an arc grows from and shrinks into. */\nfunction middleOf(place: ArcPlace): ArcPlace {\n  const middle = (place.start + place.end) / 2\n  return { ...place, start: middle, end: middle }\n}\n\n/**\n * Where an arc that arrives with a layout comes from, after `was`: where\n * its node sat under `was`'s view, so a zoom moves every arc as one\n * (zooming in, the deeper ring arrives from the edge, and zooming out the\n * parent's siblings unfold from the top); or for a node new to the data,\n * its own middle, which it grows from.\n */\nfunction arcFrom(arc: RingArc, was: RingLayout | null): ArcPlace {\n  const place = was?.places.get(arc.key)\n  return was && place ? placeIn(place, windowOf(was), was.rings) : middleOf(arc)\n}\n\n/**\n * Where an arc that leaves goes, in `now`: where its node sits under\n * `now`'s view (zooming in, the parent folds into the hole and its siblings\n * into the top); or for a node gone from the data, its own middle, which it\n * shrinks into.\n */\nfunction arcTo(arc: RingArc, now: RingLayout): ArcPlace {\n  const place = now.places.get(arc.key)\n  return place ? placeIn(place, windowOf(now), now.rings) : middleOf(arc)\n}\n\n/** The place `progress` of the way from `from` to `to`, in straight lines. */\nfunction placeBetween(from: ArcPlace, to: ArcPlace, progress: number): ArcPlace {\n  const at = (a: number, b: number) => a + (b - a) * progress\n  return {\n    start: at(from.start, to.start),\n    end: at(from.end, to.end),\n    inner: at(from.inner, to.inner),\n    outer: at(from.outer, to.outer),\n  }\n}\n\nexport {\n  type ArcPlace,\n  placeBetween,\n  RINGS,\n  type RingArc,\n  ringLayout,\n  type RingLayout,\n  arcFrom,\n  arcTo,\n  middleOf,\n  type RingNode,\n  ringTree,\n  boxOutOf,\n  centreOf,\n  boxWithin,\n  circleLabelFit,\n  HEADER_HEIGHT,\n  headerFit,\n  LABEL_PADDING,\n  type LaidGroup,\n  type LaidTile,\n  labelFit,\n  packAt,\n  type PackedCircle,\n  type PackLayout,\n  packLayout,\n  packPoint,\n  type PackView,\n  packView,\n  type PackWindow,\n  shownBox,\n  startsWith,\n  type TileBox,\n  tileAncestors,\n  tileAt,\n  type TileLayout,\n  tileLayout,\n  type TileLayoutOptions,\n  tileMoves,\n  type TileNode,\n  tileNodeAt,\n  topColor,\n  tileTree,\n  viewShape,\n  viewTiles,\n}\n",
      "type": "registry:lib",
      "target": "@lib/chart-tiles.ts"
    }
  ],
  "type": "registry:lib"
}