{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sankey-chart",
  "type": "registry:component",
  "title": "Sankey Chart",
  "description": "Where a quantity came from and where it ended up, as ribbons between stages.",
  "dependencies": [
    "@base-ui/react",
    "@tanstack/charts",
    "tailwind-variants"
  ],
  "registryDependencies": [],
  "cssVars": {
    "light": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    },
    "dark": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    }
  },
  "files": [
    {
      "path": "components/panelui/sankey-chart/index.tsx",
      "type": "registry:component",
      "target": "@components/panelui/sankey-chart/index.tsx",
      "content": "'use client';\n\n/**\n * SankeyChart — where a quantity came from and where it ended up.\n *\n * ```tsx\n * <SankeyChart nodes={stages} links={flows}>\n *   <SankeyChart.Links />\n *   <SankeyChart.Nodes />\n *   <SankeyChart.Labels />\n *   <SankeyChart.Breakdown />\n * </SankeyChart>\n * ```\n *\n * ## The same parts as the app\n *\n * The parts and their props are the app library's SankeyChart, so a chart\n * written for one reads the same in the other. What differs is what the web\n * changes: a colour is named by the theme's role, a stage or a ribbon is read by\n * hovering, tapping or the arrow keys, and a click pins the reading.\n *\n * ## Grey until it is read\n *\n * A ribbon's thickness is its value, and at rest that is all it says: the\n * ribbons are one quiet colour, so the bars carry the colour and the shape of\n * the flow reads first. Reading a stage colours its whole route, every stage\n * before and after it, because a route is the question this chart exists for.\n *\n * ## The route is the focus group\n *\n * A focus group is normally the points that share an x. Here the focus strategy\n * returns the route instead, so the coloured ribbons and the faded bars are the\n * chart's own focus states and reading a stage rebuilds nothing.\n *\n * ## The layout is ours, the drawing is the chart's\n *\n * Bad rows are dropped and counted rather than thrown, because flow data is\n * usually joined from somewhere nobody in the room owns. `collapse`, a pinned\n * node `value` and a vertical flow all happen in the layout, so it runs before\n * the chart and the marks draw its pixels, through scales that change nothing.\n *\n * ## A ribbon is a filled shape\n *\n * A stroke has one thickness from end to end. `targetRows` needs a ribbon to\n * narrow into its row, so each one is drawn as its two edges and the space\n * between them.\n */\nimport {\n  createMark,\n  defineChart,\n  rect,\n  text,\n  whenFocused,\n  type ChartFocusStrategy,\n  type ChartInteractionController,\n  type ChartMotionContext,\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 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 { sankeyLayout, transposeLayout, type SankeyAlign, type SankeyCollapse, type SankeyLayout } from './sankey-layout';\n\nexport type { SankeyAlign, SankeyCollapse } from './sankey-layout';\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 SankeyChartStatus = 'loading' | 'ready';\nexport type SankeyOrientation = 'horizontal' | 'vertical';\n\n/** Which of the theme's roles a node or a ribbon is drawn in. */\nexport type SankeyChartColor =\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\nexport interface SankeyNode {\n  /** Stable key the links name. Must be unique; a repeat is ignored. */\n  id: string;\n  /** Name drawn beside the bar. Defaults to the id. */\n  label?: string;\n  /** The bar's colour: a theme role or any CSS colour. Defaults to its place in the palette. */\n  color?: SankeyChartColor | (string & {});\n  /** Set to `false` to draw no bar. The node keeps its place and can still be read. */\n  bar?: boolean;\n  /**\n   * Pins what passes through the node, for a stage that loses some of what it\n   * received to somewhere the links do not describe. Left unset the node is\n   * worth the larger of what arrives and what leaves.\n   */\n  value?: number;\n}\n\nexport interface SankeyLink {\n  /** `id` of the node it leaves. */\n  source: string;\n  /** `id` of the node it reaches. */\n  target: string;\n  /** How much travels. Zero, negative and non-finite rows are dropped. */\n  value: number;\n  /** Its colour, a theme role or any CSS colour, instead of the source node's. */\n  color?: SankeyChartColor | (string & {});\n  /** With `SankeyChart.Links gradient`, the opacity it fades between, from its source to its target. */\n  opacity?: readonly [number, number];\n}\n\n/** Rows beside the chart for the last column's ribbons to end on, in pixels. */\nexport interface SankeyRowGrid {\n  /** Where the first row starts, under a table's header. */\n  top: number;\n  /** How tall each row is. */\n  height: number;\n  /** How much of its thickness a ribbon keeps at the row. Defaults to `0.4`. */\n  taper?: number;\n  /** The thinnest a ribbon gets at the row. Defaults to `3`. */\n  minThickness?: number;\n}\n\n/** Where a node of the last column sits across the flow, in pixels. */\nexport interface SankeyTargetLayout {\n  id: string;\n  y: number;\n  y0: number;\n  y1: number;\n}\n\nconst COLOR_VAR: Record<SankeyChartColor, string> = {\n  primary: 'var(--primary)',\n  info: 'var(--info)',\n  success: 'var(--success)',\n  warning: 'var(--warning)',\n  destructive: 'var(--destructive)',\n  'chart-1': 'var(--chart-1)',\n  'chart-2': 'var(--chart-2)',\n  'chart-3': 'var(--chart-3)',\n  'chart-4': 'var(--chart-4)',\n  'chart-5': 'var(--chart-5)',\n};\n\nconst resolveColor = (color: string): string =>\n  Object.hasOwn(COLOR_VAR, color) ? COLOR_VAR[color as SankeyChartColor] : color;\n\nconst PALETTE = ['var(--chart-1)', 'var(--chart-2)', 'var(--chart-3)', 'var(--chart-4)', 'var(--chart-5)'];\n\nconst THEME = {\n  foreground: 'var(--foreground)',\n  muted: 'var(--muted-foreground)',\n  grid: 'var(--border)',\n  background: 'transparent',\n  palette: PALETTE,\n};\n\n// The labels are placed in pixels already mirrored, so the svg's own direction must not flip their anchors.\nconst sankeyChartVariants = tv({\n  slots: {\n    root: 'relative grid w-full grid-cols-1 text-foreground',\n    plot: \"relative col-start-1 row-start-2 w-full [&_.sankey-ribbon]:transition-opacity data-dimmed:[&_.sankey-ribbon]:opacity-25\",\n    chart:\n      'absolute! inset-0 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]:[direction:ltr] [&_svg]:rounded-lg [&_svg]:outline-none [&_svg:focus-visible]:ring-2 [&_svg:focus-visible]:ring-ring',\n    header: 'col-start-1 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    breakdown: 'col-start-1 row-start-3 mt-3 border-t pt-3 text-[0.8125rem] leading-5 outline-none',\n    breakdownSides: 'grid grid-cols-2 gap-x-4 sm:gap-x-6',\n    breakdownSide: 'flex min-w-0 flex-col gap-0.5',\n    breakdownTitle: 'pb-0.5 text-xs text-muted-foreground',\n    breakdownRow:\n      'flex w-full min-w-0 cursor-pointer items-center gap-2 rounded-md py-0.5 text-start outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring',\n    breakdownPlaceholder: 'text-muted-foreground',\n    swatch: 'size-2 shrink-0 rounded-full',\n    rowLabel: 'min-w-0 flex-1 truncate text-muted-foreground',\n    rowValue: 'tabular-nums',\n    rowShare: 'hidden w-9 text-end sm:block tabular-nums text-muted-foreground',\n    legend: 'col-start-1 row-start-4 flex flex-wrap items-center gap-x-3 gap-y-1.5 pt-3 text-xs',\n    legendItem:\n      'flex max-w-full cursor-pointer items-center gap-1.5 rounded-md outline-none transition-opacity focus-visible:ring-2 focus-visible:ring-ring data-dimmed:opacity-40',\n    legendLabel: 'truncate text-muted-foreground',\n    legendShare: 'font-medium tabular-nums',\n  },\n});\n\nconst DEFAULT_HEIGHT = 240;\n\n/** How much depth one stage of a vertical flow is given when nothing says. */\nconst VERTICAL_STAGE = 104;\n\nconst DEFAULT_NODE_WIDTH = 10;\nconst DEFAULT_NODE_PADDING = 14;\nconst DEFAULT_ITERATIONS = 6;\n\n/** Exactly half puts both control points on the centre line, so a ribbon's two halves mirror. */\nconst DEFAULT_CURVE = 0.5;\n\nconst DEFAULT_DURATION = 620;\nconst DEFAULT_STAGGER = 110;\n\nconst LABEL_GAP = 7;\n\n/** One line of a name, as a box, so two names on thin neighbouring bars cannot run together. */\nconst LABEL_LINE = 18;\n\n/** An estimate, because measuring every name means a render to find out where to render them. */\nconst nameWidth = (name: string) => name.length * 7 + 8;\n\n/** Columns the placeholder suggests while there is no data to count. */\nconst SKELETON_COLUMNS = 3;\n\nconst NODES_MARK = 'sankey-nodes';\nconst LINKS_MARK = 'sankey-links';\nconst DEFAULT_TAPER = 0.4;\nconst DEFAULT_MIN_THICKNESS = 3;\nconst RIBBON_SAMPLES = 12;\nconst gradientId = (row: LinkRow) => row.key.replace(':', '-');\n\nconst COMPACT = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 });\nconst compactNumber = (value: number) => COMPACT.format(value);\n\n/** A bar, in the chart's pixels. */\ninterface NodeRow {\n  kind: 'node';\n  key: string;\n  id: string;\n  name: string;\n  value: number;\n  layer: number;\n  color: string;\n  /** `false` keeps the node readable with nothing painted. */\n  bar: boolean;\n  /** It ends on a row beside the chart, which carries its name. */\n  onRow: boolean;\n  x0: number;\n  x1: number;\n  y0: number;\n  y1: number;\n}\n\ntype Span = readonly [number, number];\n\n/** A ribbon, in the chart's pixels: its two edges, along the flow and across it. */\ninterface LinkRow {\n  kind: 'link';\n  key: string;\n  input: number;\n  source: string;\n  target: string;\n  value: number;\n  layer: number;\n  color: string;\n  /** Where the ribbon's gradient ends: the target's colour, or its own when it was given one. */\n  endColor: string;\n  fade?: readonly [number, number];\n  from: number;\n  to: number;\n  start: Span;\n  end: Span;\n}\n\n/** A name, or the figure under it, placed beside its bar. */\ninterface LabelRow {\n  key: string;\n  node: NodeRow;\n  text: string;\n  x: number;\n  y: number;\n  anchor: 'start' | 'end';\n  muted: boolean;\n}\n\ntype Row = NodeRow | LinkRow | LabelRow;\ntype RowPoint = ChartPoint<Row, number, number>;\n\nconst barFill = (row: NodeRow) => (row.bar ? row.color : 'transparent');\nconst isNode = (row: Row): row is NodeRow => 'kind' in row && row.kind === 'node';\nconst isLink = (row: Row): row is LinkRow => 'kind' in row && row.kind === 'link';\n\n/** What is being read, by the keys its rows carry. */\ntype Reading = { kind: 'node'; id: string } | { kind: 'link'; key: string } | null;\n\n/** One end of a stream meeting the node being read. */\nexport interface SankeyChartFlow {\n  /** The node at the other end. */\n  id: string;\n  /** Its name, already resolved. */\n  label: string;\n  /** What travels between the two. */\n  value: number;\n  /** That value as a fraction of the node's total, `0` to `1`. */\n  share: number;\n  /** The other node's colour, for a swatch beside its name. */\n  color: string;\n}\n\n/** A ribbon's two ends and the value between them, for a reading of one ribbon. */\nexport interface SankeyChartActiveLink {\n  source: SankeyChartFlow;\n  target: SankeyChartFlow;\n  value: number;\n}\n\nconst cubic = (a: number, b: number, c: number, d: number, t: number) => {\n  const u = 1 - t;\n  return u * u * u * a + 3 * u * u * t * b + 3 * u * t * t * c + t * t * t * d;\n};\n\n/** A ribbon's outline. Both edges bend alike, so its control points reach along the flow only. */\nfunction ribbonPath({ from, to, start, end }: LinkRow, vertical: boolean, reach: number): string {\n  const run = (to - from) * reach;\n  const at = (along: number, across: number) => (vertical ? `${across},${along}` : `${along},${across}`);\n  return (\n    `M${at(from, start[0])}C${at(from + run, start[0])} ${at(to - run, end[0])} ${at(to, end[0])}` +\n    `L${at(to, end[1])}C${at(to - run, end[1])} ${at(from + run, start[1])} ${at(from, start[1])}Z`\n  );\n}\n\nfunction ribbonOutline({ from, to, start, end }: LinkRow, vertical: boolean, reach: number): (readonly [number, number])[] {\n  const run = (to - from) * reach;\n  const steps = Array.from({ length: RIBBON_SAMPLES + 1 }, (_unused, step) => step / RIBBON_SAMPLES);\n  const edge = (side: 0 | 1) =>\n    steps.map((t): readonly [number, number] => {\n      const along = cubic(from, from + run, to - run, to, t);\n      const across = cubic(start[side], start[side], end[side], end[side], t);\n      return vertical ? [across, along] : [along, across];\n    });\n  return [...edge(0), ...edge(1).reverse()];\n}\n\n/** How far a point is inside a ribbon, negative within it, or `Infinity` past its ends. */\nfunction ribbonGap(row: LinkRow, x: number, y: number, vertical: boolean, reach: number): number {\n  const { from, to, start, end } = row;\n  const [along, across] = vertical ? [y, x] : [x, y];\n  if (along < Math.min(from, to) || along > Math.max(from, to)) return Infinity;\n  const run = (to - from) * reach;\n  let low = 0;\n  let high = 1;\n  for (let step = 0; step < 16; step += 1) {\n    const t = (low + high) / 2;\n    const reached = cubic(from, from + run, to - run, to, t);\n    if (to > from ? reached < along : reached > along) low = t;\n    else high = t;\n  }\n  const t = (low + high) / 2;\n  const first = cubic(start[0], start[0], end[0], end[0], t);\n  const second = cubic(start[1], start[1], end[1], end[1], t);\n  return Math.abs(across - (first + second) / 2) - Math.abs(second - first) / 2;\n}\n\n/** The ribbons, drawn from pixels the layout already worked out. */\nfunction ribbonMark(\n  rows: readonly LinkRow[],\n  options: {\n    id: string;\n    vertical: boolean;\n    reach: number;\n    fill: (row: LinkRow) => string;\n    fillOpacity?: (row: LinkRow) => number;\n    className?: string;\n    still?: boolean;\n  }\n) {\n  const { id, vertical, reach, fill, fillOpacity, className, still } = options;\n  return createMark<LinkRow, number, number>(\n    () => ({\n      id,\n      channels: {},\n      render: () => {\n        const points = rows.map((row, datumIndex) => {\n          const key = `${id}:${row.key}`;\n          const [along, across] = [(row.from + row.to) / 2, (row.start[0] + row.start[1] + row.end[0] + row.end[1]) / 4];\n          return {\n            key,\n            markId: id,\n            group: null,\n            groupLabel: id,\n            datum: row,\n            datumIndex,\n            xValue: row.to,\n            yValue: row.value,\n            x: vertical ? across : along,\n            y: vertical ? along : across,\n            color: row.color,\n          };\n        });\n        return {\n          nodes: [\n            {\n              kind: 'group' as const,\n              key: id,\n              className: 'ts-chart__link',\n              ariaHidden: true,\n              children: rows.map((row, index) => ({\n                kind: 'area' as const,\n                key: `${id}:${row.key}`,\n                ...(className ? { className } : {}),\n                path: ribbonPath(row, vertical, reach),\n                points: ribbonOutline(row, vertical, reach),\n                interaction: { point: points[index]!, affinity: 'geometry' as const },\n                style: { fill: fill(row), fillOpacity: fillOpacity?.(row) },\n              })),\n            },\n          ],\n          points,\n        };\n      },\n    }),\n    still ? false : undefined\n  );\n}\n\n/** The nodes and ribbons before and after one reading, by key. */\nfunction routeOf(reading: Reading, links: readonly LinkRow[]): Set<string> {\n  const route = new Set<string>();\n  // A node reached by many paths is walked once, or the cost grows with the paths.\n  const seen = { forward: new Set<string>(), backward: new Set<string>() };\n  const walk = (id: string, forward: boolean) => {\n    const visited = forward ? seen.forward : seen.backward;\n    if (visited.has(id)) return;\n    visited.add(id);\n    route.add(`node:${id}`);\n    for (const row of links) {\n      if ((forward ? row.source : row.target) !== id) continue;\n      route.add(row.key);\n      walk(forward ? row.target : row.source, forward);\n    }\n  };\n  if (reading?.kind === 'node') {\n    walk(reading.id, true);\n    walk(reading.id, false);\n  } else if (reading?.kind === 'link') {\n    const row = links.find(({ key }) => key === reading.key);\n    if (row) {\n      route.add(row.key);\n      walk(row.source, false);\n      walk(row.target, true);\n    }\n  }\n  return route;\n}\n\nconst readingOf = (row: Row | undefined): Reading => {\n  if (!row) return null;\n  if (isNode(row)) return { kind: 'node', id: row.id };\n  if (isLink(row)) return { kind: 'link', key: row.key };\n  return null;\n};\n\nconst rowKey = (row: Row) => (isNode(row) || isLink(row) ? row.key : `node:${row.node.id}`);\n\n/**\n * Bars first, then ribbons, by what is actually under the pointer. The nearest\n * point would be a ribbon's midpoint, which a pointer on the same ribbon's end\n * is further from than it is from the bar next door.\n */\nfunction routeFocus(links: readonly LinkRow[], vertical: boolean, reach: number, barsReadable: boolean): ChartFocusStrategy<Row, number, number> {\n  let cachedFor = '';\n  let cached = new Set<string>();\n  const routeFor = (row: Row) => {\n    const key = rowKey(row);\n    if (key !== cachedFor) {\n      cachedFor = key;\n      cached = routeOf(readingOf(row), links);\n    }\n    return cached;\n  };\n\n  const group = (points: readonly RowPoint[], point: RowPoint) => {\n    const route = routeFor(point.datum);\n    // The primary point goes first, because the chart reads it from the group's head.\n    return [point, ...points.filter((other) => other !== point && route.has(rowKey(other.datum)))];\n  };\n\n  return {\n    resolve(points, { x, y }) {\n      const bar = !barsReadable ? undefined : points.find(({ datum }) => isNode(datum) && x >= datum.x0 - 3 && x <= datum.x1 + 3 && y >= datum.y0 - 3 && y <= datum.y1 + 3);\n      if (bar) return group(points, bar);\n      let nearest: RowPoint | undefined;\n      let nearestGap = Infinity;\n      for (const point of points) {\n        if (!isLink(point.datum)) continue;\n        const gap = ribbonGap(point.datum, x, y, vertical, reach);\n        if (gap <= 0 && gap < nearestGap) {\n          nearest = point;\n          nearestGap = gap;\n        }\n      }\n      return nearest ? group(points, nearest) : [];\n    },\n    group: (points, { point }) => group(points, point),\n    // The bars are enough to walk: from each one the breakdown names its ribbons.\n    navigation: (points) => {\n      if (!barsReadable) return points.filter(({ datum }) => isLink(datum));\n      const bars = points.filter(({ datum }) => isNode(datum));\n      return bars.sort((a, b) => {\n        const [left, right] = [a.datum as NodeRow, b.datum as NodeRow];\n        return left.layer - right.layer || left.y0 - right.y0 || left.x0 - right.x0;\n      });\n    },\n  };\n}\n\n/** Which names fit: the larger stage keeps its name where two would collide. */\nfunction placeLabels(\n  nodes: readonly NodeRow[],\n  { width, height, vertical, rtl, showValue, minHeight, format }: {\n    width: number;\n    height: number;\n    vertical: boolean;\n    rtl: boolean;\n    showValue: boolean;\n    minHeight: number;\n    format: (value: number, node: NodeRow) => string;\n  }\n): LabelRow[] {\n  const placed: { left: number; right: number; top: number; bottom: number }[] = [];\n  const rows: LabelRow[] = [];\n  const lines = showValue ? 2 : 1;\n  for (const node of [...nodes].sort((a, b) => b.value - a.value)) {\n    const size = vertical ? node.x1 - node.x0 : node.y1 - node.y0;\n    if (size < minHeight) continue;\n    const boxWidth = nameWidth(node.name);\n    const boxHeight = LABEL_LINE * lines;\n    const inward = rtl ? node.x0 > 0 : node.x1 >= width - 1;\n    const x = vertical ? node.x0 : inward ? node.x0 - LABEL_GAP : node.x1 + LABEL_GAP;\n    const anchor = !vertical && inward ? 'end' : 'start';\n    // A vertical flow's last stage has nothing under it, so its name goes above the bar.\n    const below = node.y1 + boxHeight + 3 <= height;\n    const top = vertical ? (below ? node.y1 + 3 : node.y0 - boxHeight - 3) : (node.y0 + node.y1) / 2 - boxHeight / 2;\n    const left = anchor === 'end' ? x - boxWidth : x;\n    const box = { left, right: left + boxWidth, top, bottom: top + boxHeight };\n    if (placed.some((other) => box.left < other.right && box.right > other.left && box.top < other.bottom && box.bottom > other.top)) {\n      continue;\n    }\n    placed.push(box);\n    rows.push({ key: `${node.id}:name`, node, text: node.name, x, y: top + LABEL_LINE / 2, anchor, muted: false });\n    if (showValue) {\n      rows.push({ key: `${node.id}:value`, node, text: format(node.value, node), x, y: top + LABEL_LINE * 1.5, anchor, muted: true });\n    }\n  }\n  return rows;\n}\n\nfunction pointsOf(nodes: readonly SceneNode[], found: RowPoint[] = []): RowPoint[] {\n  for (const node of nodes) {\n    if (node.kind === 'group') {\n      pointsOf(node.children, found);\n      continue;\n    }\n    const point = 'interaction' in node ? (node.interaction?.point as RowPoint | undefined) : undefined;\n    if (point && (isNode(point.datum) || isLink(point.datum))) found.push(point);\n  }\n  return found;\n}\n\n/** What the parts have asked for. Formatters are read through `latest`, so a new one costs nothing. */\ninterface Slots {\n  links?: { gradient: boolean; opacity: number; activeOpacity: number };\n  nodes?: { radius: number; dimOpacity: number; interactive: boolean };\n  labels?: { showValue: boolean; minHeight: number; latest: { current: Pick<SankeyChartLabelsProps, 'formatValue'> } };\n  tooltip?: { className: string | undefined; latest: { current: Pick<SankeyChartTooltipProps, 'formatValue'> } };\n  skeleton?: true;\n}\n\ninterface SankeyChartContextValue {\n  rows: { nodes: readonly NodeRow[]; links: readonly LinkRow[] };\n  reading: Reading;\n  status: SankeyChartStatus;\n  select: (id: string | null) => void;\n  setSlot: <K extends keyof Slots>(slot: K, value: Slots[K]) => void;\n}\n\nconst SankeyChartContext = createContext<SankeyChartContextValue | null>(null);\n\nfunction useChart(component: string): SankeyChartContextValue {\n  const context = useContext(SankeyChartContext);\n  if (!context) {\n    throw new Error(`${component} must be used within a <SankeyChart>`);\n  }\n  return context;\n}\n\n/** What is being read and what runs through it, for something rendered inside the chart. */\nexport function useSankeyChart() {\n  const { rows, reading } = useChart('useSankeyChart');\n\n  return useMemo(() => {\n    const nodeById = new Map(rows.nodes.map((node) => [node.id, node]));\n    const flow = (id: string, value: number, total: number): SankeyChartFlow => {\n      const other = nodeById.get(id);\n      return {\n        id,\n        label: other?.name ?? id,\n        value,\n        // Against what passes through the node rather than against the side's own\n        // total, so in and out are read on one scale.\n        share: total > 0 ? value / total : 0,\n        color: other?.color ?? PALETTE[0]!,\n      };\n    };\n    const placed = reading?.kind === 'node' ? nodeById.get(reading.id) : undefined;\n    const ribbon = reading?.kind === 'link' ? rows.links.find(({ key }) => key === reading.key) : undefined;\n    const largestFirst = (a: SankeyChartFlow, b: SankeyChartFlow) => b.value - a.value;\n    const outer = (stages: readonly NodeRow[]) => {\n      const total = stages.reduce((sum, { value }) => sum + value, 0);\n      return stages.map(({ id, value }) => flow(id, value, total)).sort(largestFirst);\n    };\n\n    return {\n      /** The node being read, or `null` while nothing is, or a ribbon is. */\n      activeId: placed?.id ?? null,\n      /** Its name. */\n      activeLabel: placed?.name ?? null,\n      /** What passes through it: what the bar's height is drawn from. */\n      activeValue: placed?.value ?? 0,\n      /** The ribbon being read, or `null`. */\n      activeLink: ribbon\n        ? ({\n            source: flow(ribbon.source, ribbon.value, nodeById.get(ribbon.source)?.value ?? 0),\n            target: flow(ribbon.target, ribbon.value, nodeById.get(ribbon.target)?.value ?? 0),\n            value: ribbon.value,\n          } satisfies SankeyChartActiveLink)\n        : null,\n      /** Where it came from, largest first. */\n      sources: placed\n        ? rows.links.filter(({ target }) => target === placed.id).map((row) => flow(row.source, row.value, placed.value)).sort(largestFirst)\n        : ([] as SankeyChartFlow[]),\n      /** Where it went, largest first. */\n      targets: placed\n        ? rows.links.filter(({ source }) => source === placed.id).map((row) => flow(row.target, row.value, placed.value)).sort(largestFirst)\n        : ([] as SankeyChartFlow[]),\n      /** The stages nothing arrives at, largest first, each as a share of them all. */\n      starts: outer(rows.nodes.filter(({ id }) => !rows.links.some(({ target }) => target === id))),\n      /** The stages nothing leaves, largest first, each as a share of them all. */\n      ends: outer(rows.nodes.filter(({ id }) => !rows.links.some(({ source }) => source === id))),\n    };\n  }, [rows, reading]);\n}\n\nexport interface SankeyChartProps extends Omit<ComponentProps<'div'>, 'ref'> {\n  /** The stages. Order does not decide position; the links do. */\n  nodes: readonly SankeyNode[];\n  /** What travels between them. */\n  links: readonly SankeyLink[];\n  /**\n   * How tall the diagram is drawn, in pixels. Under `orientation=\"vertical\"` it\n   * is the length of the flow, and left unset it is worked out from how many\n   * stages the flow needs.\n   */\n  height?: number;\n  /** How thick a node's bar is, in pixels. */\n  nodeWidth?: number;\n  /** The most space between two nodes in a column, in pixels. A crowded column gives it up first. */\n  nodePadding?: number;\n  /** `horizontal` runs the flow across, `vertical` from the top down, which suits a narrow screen. */\n  orientation?: SankeyOrientation;\n  /**\n   * Folds each column's smallest nodes into one bucket. `maxPerColumn` caps how\n   * many a column keeps, the bucket included; `minShare` folds anything under\n   * that fraction of its column; `label` names the bucket, `Other` by default.\n   */\n  collapse?: SankeyCollapse;\n  /** Which column a node goes in where the flow leaves a choice. */\n  align?: SankeyAlign;\n  /** Relaxation rounds spent untangling the ribbons. */\n  iterations?: number;\n  /** How far a ribbon bends, `0` for a straight diagonal and `0.5` for an S. */\n  curve?: number;\n  /** Milliseconds for one column to draw itself. */\n  animationDuration?: number;\n  /** Milliseconds between one column starting and the next. */\n  staggerDelay?: number;\n  /** `loading` holds the data back. Add `SankeyChart.Skeleton` for a shape to stand in meanwhile. */\n  status?: SankeyChartStatus;\n  /** Selected node. Leave unset to let the chart track it. */\n  activeId?: string | null;\n  /** Fires with the id of the node being read, and `null` when none is. */\n  onActiveIdChange?: (id: string | null) => void;\n  /**\n   * Ends the last column's ribbons on rows beside the chart, such as a table's,\n   * in the order those nodes were given, with no bars or names of their own.\n   * Set `height` to fit the rows, and keep each row to one line, because a taller\n   * row moves those below it off their ribbons. A horizontal flow only.\n   */\n  targetRows?: SankeyRowGrid;\n  /** Fires with where the last column landed, and again when that moves. */\n  onLayout?: (targets: readonly SankeyTargetLayout[]) => void;\n  /**\n   * Fires with how many link rows could not be drawn: ones naming a node that is\n   * not there, carrying nothing, or closing a loop. `0` after a clean render.\n   */\n  onDropLinks?: (count: number) => void;\n  /** What a screen reader calls the chart. */\n  label?: string;\n  /** What a screen reader says for one ribbon. Defaults to \"source to target, value\". */\n  labelForLink?: (link: SankeyLink, index: number) => string;\n}\n\n/** Imperative handle: re-run the entrance, for a \"replay\" control. */\nexport interface SankeyChartHandle {\n  replay: () => void;\n}\n\nconst SankeyChartRoot = forwardRef<SankeyChartHandle, SankeyChartProps & RenderProp<'div'>>(function SankeyChartRoot(\n  {\n    nodes,\n    links,\n    height: heightProp,\n    nodeWidth = DEFAULT_NODE_WIDTH,\n    nodePadding = DEFAULT_NODE_PADDING,\n    orientation = 'horizontal',\n    collapse,\n    align = 'justify',\n    iterations = DEFAULT_ITERATIONS,\n    curve = DEFAULT_CURVE,\n    animationDuration = DEFAULT_DURATION,\n    staggerDelay = DEFAULT_STAGGER,\n    status = 'ready',\n    activeId,\n    targetRows,\n    onLayout,\n    onActiveIdChange,\n    onDropLinks,\n    label,\n    labelForLink,\n    className,\n    children,\n    render,\n    ...props\n  },\n  ref\n) {\n  const slotClasses = sankeyChartVariants();\n  const plotRef = useRef<HTMLDivElement>(null);\n  const [size, setSize] = useState({ width: 0, rtl: false });\n  const [slots, setSlots] = useState<Slots>({});\n  const [reading, setReading] = useState<Reading>(null);\n  const [revision, setRevision] = useState(0);\n  const interactionRef = useRef<ChartInteractionController<Row, number, number> | null>(null);\n  const pointsRef = useRef<RowPoint[]>([]);\n\n  const width = size.width;\n  const vertical = orientation === 'vertical';\n  const loading = status === 'loading';\n\n  // The chart mounts once its width is known: a resize ends the entrance before it is seen.\n  useEffect(() => {\n    const node = plotRef.current;\n    if (!node) return;\n    const read = () => {\n      const next = { width: node.clientWidth, rtl: getComputedStyle(node).direction === 'rtl' };\n      setSize((current) => (current.width === next.width && current.rtl === next.rtl ? current : next));\n    };\n    read();\n    const observer = new ResizeObserver(read);\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, []);\n\n  const setSlot = useCallback<SankeyChartContextValue['setSlot']>(\n    (slot, value) => setSlots((current) => ({ ...current, [slot]: value })),\n    []\n  );\n\n  useImperativeHandle(ref, () => ({ replay: () => setRevision((current) => current + 1) }), []);\n\n  const options = { nodeWidth, nodePadding, align, iterations, collapse };\n\n  // The column count falls out of the links alone, so no rounds are spent on it.\n  const stages = useMemo(() => {\n    if (!vertical || heightProp !== undefined) return 0;\n    return sankeyLayout(nodes as SankeyNode[], links as SankeyLink[], { ...options, width: 1000, height: 1000, iterations: 0 }).columns;\n  }, [vertical, heightProp, nodes, links, nodeWidth, nodePadding, align, collapse]);\n\n  const height = heightProp ?? (vertical ? Math.max(DEFAULT_HEIGHT, stages * VERTICAL_STAGE) : DEFAULT_HEIGHT);\n\n  const layout = useMemo<SankeyLayout>(() => {\n    const solved = sankeyLayout(nodes as SankeyNode[], links as SankeyLink[], {\n      ...options,\n      width: vertical ? height : width,\n      height: vertical ? width : height,\n    });\n    return vertical ? transposeLayout(solved) : solved;\n  }, [nodes, links, width, height, nodeWidth, nodePadding, align, iterations, collapse, vertical]);\n\n  const dropped = layout.dropped;\n  // Nothing is laid out until the width is known, so that first zero says nothing.\n  const measured = width > 0;\n  useEffect(() => {\n    if (measured) onDropLinks?.(dropped);\n  }, [dropped, onDropLinks, measured]);\n\n  const rows = useMemo(() => {\n    // A flow reads from where it starts, which is the right-hand edge in a\n    // right-to-left page. A vertical flow starts at the top in every script.\n    const mirror = size.rtl && !vertical;\n    const onRows = targetRows && !vertical ? targetRows : undefined;\n    const rowOf = new Map<number, number>();\n    if (onRows) {\n      layout.nodes.forEach((node, index) => {\n        if (node.layer === layout.columns - 1) rowOf.set(index, rowOf.size);\n      });\n    }\n    const rowCentre = (row: number) => (onRows ? onRows.top + onRows.height * (row + 0.5) : 0);\n\n    // A source's ribbons leave it in the order of the rows they reach, or they would cross.\n    const leaving = new Map<number, Span>();\n    const ending = new Map<number, Span>();\n    if (onRows) {\n      const reachOf = (target: number) => {\n        const row = rowOf.get(target);\n        const node = layout.nodes[target];\n        return row === undefined ? ((node?.y0 ?? 0) + (node?.y1 ?? 0)) / 2 : rowCentre(row);\n      };\n      for (const [index, node] of layout.nodes.entries()) {\n        let cursor = node.y0;\n        const out = layout.links.filter(({ source }) => source === index).sort((a, b) => reachOf(a.target) - reachOf(b.target) || a.y0 - b.y0);\n        for (const link of out) {\n          leaving.set(link.index, [cursor, cursor + link.width]);\n          cursor += link.width;\n        }\n      }\n      for (const [target, row] of rowOf) {\n        const into = layout.links.filter((link) => link.target === target).sort((a, b) => (leaving.get(a.index)?.[0] ?? 0) - (leaving.get(b.index)?.[0] ?? 0));\n        const thickness = into.map((link) => Math.max(link.width * (onRows.taper ?? DEFAULT_TAPER), onRows.minThickness ?? DEFAULT_MIN_THICKNESS));\n        let cursor = rowCentre(row) - thickness.reduce((sum, value) => sum + value, 0) / 2;\n        into.forEach((link, position) => {\n          const end = cursor + (thickness[position] ?? 0);\n          ending.set(link.index, [cursor, end]);\n          cursor = end;\n        });\n      }\n    }\n\n    const nodeRows = layout.nodes.map((node, index): NodeRow => {\n      const input = nodes[node.index];\n      const row = rowOf.get(index);\n      const spans = row === undefined ? [] : layout.links.flatMap((link) => (link.target === index ? (ending.get(link.index) ?? []) : []));\n      return {\n        kind: 'node',\n        key: `node:${node.id}`,\n        id: node.id,\n        // A bucket's id can carry a suffix to keep it unique, so its name is the one asked for.\n        name: node.collapsed ? (collapse?.label ?? 'Other') : (input?.label ?? node.id),\n        value: node.value,\n        layer: node.layer,\n        // The node's place in the data rather than its column: a colour per\n        // column would say the column means something, and it does not.\n        color: input?.color ? resolveColor(input.color) : PALETTE[index % PALETTE.length]!,\n        bar: input?.bar !== false && row === undefined,\n        onRow: row !== undefined,\n        x0: mirror ? width - node.x1 : node.x0,\n        x1: mirror ? width - node.x0 : node.x1,\n        y0: spans.length ? Math.min(...spans) : node.y0,\n        y1: spans.length ? Math.max(...spans) : node.y1,\n      };\n    });\n    const linkRows = layout.links.flatMap((link): LinkRow[] => {\n      const source = nodeRows[link.source];\n      const target = nodeRows[link.target];\n      if (!source || !target) return [];\n      const input = links[link.input];\n      const color = input?.color ? resolveColor(input.color) : source.color;\n      const half = link.width / 2;\n      const [from, to] = vertical\n        ? [source.y1, target.y0]\n        : mirror\n          ? [source.x0, target.onRow ? target.x0 : target.x1]\n          : [source.x1, target.onRow ? target.x1 : target.x0];\n      return [\n        {\n          kind: 'link',\n          key: `link:${link.index}`,\n          input: link.input,\n          source: source.id,\n          target: target.id,\n          value: link.value,\n          layer: source.layer,\n          color,\n          endColor: input?.color ? color : target.color,\n          ...(input?.opacity ? { fade: input.opacity } : {}),\n          from,\n          to,\n          start: leaving.get(link.index) ?? [link.y0 - half, link.y0 + half],\n          end: ending.get(link.index) ?? [link.y1 - half, link.y1 + half],\n        },\n      ];\n    });\n    const targets = nodeRows\n      .filter(({ layer }) => layer === layout.columns - 1)\n      .map((node): SankeyTargetLayout => {\n        const [y0, y1] = vertical ? [node.x0, node.x1] : [node.y0, node.y1];\n        return { id: node.id, y: (y0 + y1) / 2, y0, y1 };\n      });\n    return { nodes: nodeRows, links: linkRows, targets };\n  }, [layout, nodes, links, collapse?.label, width, vertical, size.rtl, targetRows?.top, targetRows?.height, targetRows?.taper, targetRows?.minThickness]);\n\n  // By what the positions say, because a parent's inline data makes new rows every render.\n  const reportedLayout = useRef('');\n  const latestOnLayout = useLatest(onLayout);\n  useEffect(() => {\n    const signature = JSON.stringify(rows.targets);\n    if (signature === reportedLayout.current || width === 0) return;\n    reportedLayout.current = signature;\n    latestOnLayout.current?.(rows.targets);\n  }, [rows.targets, width, latestOnLayout]);\n\n  const { links: linksSlot, nodes: nodesSlot, labels: labelsSlot, tooltip, skeleton } = slots;\n\n  // Only what is added to a drawn chart fades in, so a new chart draws its marks empty first.\n  const chartKey = `${revision}:${status}`;\n  const [enteredKey, setEnteredKey] = useState<string | null>(null);\n  const entering = !loading && enteredKey !== chartKey;\n\n  const definition = useMemo(() => {\n    const ribbon = { vertical, reach: curve };\n    const shown = entering ? { nodes: [], links: [] } : rows;\n\n    const fade = { type: 'tween' as const, duration: 120, easing: 'ease-out' as const };\n\n    const marks = loading\n      ? skeleton\n        ? skeletonMarks(width, height, vertical, nodeWidth, curve)\n        : []\n      : [\n          ...(linksSlot\n            ? [\n                ribbonMark(shown.links, {\n                  ...ribbon,\n                  id: LINKS_MARK,\n                  className: 'sankey-ribbon',\n                  fill: linksSlot.gradient ? (row) => `url(#${gradientId(row)})` : () => 'var(--foreground)',\n                  fillOpacity: (row) => (linksSlot.gradient && row.fade ? 1 : linksSlot.opacity),\n                }),\n                whenFocused(\n                  ribbonMark(rows.links, {\n                    ...ribbon,\n                    id: `${LINKS_MARK}-route`,\n                    fill: linksSlot.gradient ? (row) => `url(#${gradientId(row)})` : (row) => row.color,\n                    fillOpacity: () => linksSlot.activeOpacity,\n                  }),\n                  { match: 'group' }\n                ),\n              ]\n            : []),\n          ...(nodesSlot\n            ? [\n                // A rect takes one fill, so the bars are one mark per colour.\n                ...[...new Set(rows.nodes.map(barFill))].map((fill, index) =>\n                  rect(shown.nodes.filter((row) => barFill(row) === fill), {\n                    id: `${NODES_MARK}-${index}`,\n                    x1: (row: NodeRow) => row.x0,\n                    x2: (row: NodeRow) => row.x1,\n                    y1: (row: NodeRow) => row.y0,\n                    y2: (row: NodeRow) => row.y1,\n                    key: (row: NodeRow) => row.key,\n                    fill,\n                    radius: nodesSlot.radius,\n                    states: [{ when: { focus: 'unmatched' as const }, style: { opacity: nodesSlot.dimOpacity }, transition: fade }],\n                  })\n                ),\n              ]\n            : []),\n          ...(labelsSlot\n            ? [\n                text(\n                  placeLabels(shown.nodes.filter(({ onRow }) => !onRow), {\n                    width,\n                    height,\n                    vertical,\n                    rtl: size.rtl && !vertical,\n                    showValue: labelsSlot.showValue,\n                    minHeight: labelsSlot.minHeight,\n                    format: (value, node) => labelsSlot.latest.current.formatValue?.(value, node.id) ?? compactNumber(value),\n                  }),\n                  {\n                    id: 'sankey-labels',\n                    x: (row: LabelRow) => row.x,\n                    y: (row: LabelRow) => row.y,\n                    text: (row: LabelRow) => row.text,\n                    key: (row: LabelRow) => row.key,\n                    anchor: (row: LabelRow) => row.anchor,\n                    fill: (row: LabelRow) => (row.muted ? 'var(--muted-foreground)' : 'var(--foreground)'),\n                    fontWeight: 500,\n                    states: [{ when: { focus: 'unmatched' as const }, style: { opacity: 0.3 }, transition: fade }],\n                  }\n                ),\n              ]\n            : []),\n        ];\n\n    const interactive = !loading && (linksSlot !== undefined || (nodesSlot !== undefined && nodesSlot.interactive));\n    const readout = tooltip\n      ? {\n          use: chartTooltip,\n          className: tooltip.className,\n          anchor: 'point' as const,\n          sticky: false,\n          content(_points: readonly RowPoint[], context: ChartTooltipContentContext) {\n            const format = tooltip.latest.current.formatValue ?? compactNumber;\n            const row = context.primaryPoint?.datum as Row | undefined;\n            const nameOf = (id: string) => rows.nodes.find((node) => node.id === id)?.name ?? id;\n            if (row && isLink(row)) {\n              return {\n                title: `${nameOf(row.source)} to ${nameOf(row.target)}`,\n                rows: [{ label: 'Value', value: format(row.value), color: row.color }],\n              };\n            }\n            if (!row || !isNode(row)) return { title: '', rows: [] };\n            const side = (rowsOf: LinkRow[], other: (link: LinkRow) => string) =>\n              rowsOf.map((link) => ({\n                label: nameOf(other(link)),\n                value: format(link.value),\n                color: rows.nodes.find((node) => node.id === other(link))?.color ?? row.color,\n              }));\n            return {\n              title: `${row.name}, ${format(row.value)}`,\n              rows: [\n                ...side(rows.links.filter(({ target }) => target === row.id), (link) => link.source),\n                ...side(rows.links.filter(({ source }) => source === row.id), (link) => link.target),\n              ],\n            };\n          },\n        }\n      : undefined;\n\n    return defineChart({\n      theme: THEME,\n      marks,\n      gradients: linksSlot?.gradient\n        ? rows.links.map((row) => ({\n            id: gradientId(row),\n            // From where the flow starts, which is the right-hand edge in a right-to-left page.\n            ...(vertical\n              ? { x1: 0, y1: 0, x2: 0, y2: 1 }\n              : row.from > row.to\n                ? { x1: 1, y1: 0, x2: 0, y2: 0 }\n                : { x1: 0, y1: 0, x2: 1, y2: 0 }),\n            stops: [\n              { offset: 0, color: row.color, ...(row.fade ? { opacity: row.fade[0] } : {}) },\n              { offset: 1, color: row.endColor, ...(row.fade ? { opacity: row.fade[1] } : {}) },\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: (context: ChartMotionContext<Row>) => {\n        if (context.phase !== 'enter') {\n          return { transition: { type: 'tween' as const, duration: 300, easing: 'ease-out' as const } };\n        }\n        const datum = context.datum;\n        const layer = datum === undefined ? 0 : isNode(datum) || isLink(datum) ? datum.layer : datum.node.layer;\n        return {\n          delay: layer * staggerDelay,\n          transition: { type: 'tween' as const, duration: animationDuration, easing: 'ease-out' as const },\n        };\n      },\n      keyboard: interactive,\n      pointer: interactive,\n      focus: interactive ? routeFocus(rows.links, vertical, curve, nodesSlot?.interactive ?? false) : false,\n      maxFocusDistance: Number.POSITIVE_INFINITY,\n      ...(interactive && readout ? { tooltip: readout } : {}),\n    });\n  }, [rows, width, height, vertical, curve, loading, entering, nodeWidth, animationDuration, staggerDelay, size.rtl, linksSlot, nodesSlot, labelsSlot, tooltip, skeleton]);\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 reportedId = useRef<string | null>(null);\n  const latestActiveId = useLatest(activeId);\n  const [askedParent, setAskedParent] = useState(0);\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<RowPoint | null>(null);\n  const focusedRef = useRef<RowPoint | null>(null);\n\n  const onFocusChange = (point: RowPoint | null) => {\n    if (!point && pinnedRef.current) {\n      interactionRef.current?.setControlledFocus(pinnedRef.current);\n      return;\n    }\n    focusedRef.current = point;\n    const next = readingOf(point?.datum);\n    setReading((current) => (JSON.stringify(current) === JSON.stringify(next) ? current : next));\n    const id = next?.kind === 'node' ? next.id : null;\n    if (reportedId.current !== id) {\n      reportedId.current = id;\n      if (id !== latestActiveId.current) onActiveIdChange?.(id);\n      if (latestActiveId.current !== undefined) setAskedParent((count) => count + 1);\n    }\n  };\n\n  const pin = useCallback((point: RowPoint | null) => {\n    pinnedRef.current = point;\n    interactionRef.current?.setControlledFocus(point);\n  }, []);\n\n  const select = useCallback(\n    (id: string | null) => pin(id === null ? null : (pointsRef.current.find(({ datum }) => isNode(datum) && datum.id === id) ?? null)),\n    [pin]\n  );\n\n  // A new definition, from a resize or new data, repaints without the focus marks.\n  useEffect(() => {\n    if (pinnedRef.current) interactionRef.current?.setControlledFocus(pinnedRef.current);\n  }, [definition]);\n\n  // The chart has no points until it has drawn, so a request can have to wait for them.\n  const pendingId = useRef<string | null>(null);\n  const request = useCallback(\n    (id: string | null) => {\n      const known = pointsRef.current.some(({ datum }) => isNode(datum) && datum.id === id);\n      pendingId.current = id !== null && !known ? id : null;\n      select(id);\n    },\n    [select]\n  );\n\n  // Only a change the chart has not already reported is a request to move it.\n  useEffect(() => {\n    if (activeId === undefined || activeId === reportedId.current) return;\n    request(activeId);\n  }, [activeId, request]);\n\n  // A parent that kept its `activeId` has turned the change down, so the chart goes back to it.\n  useEffect(() => {\n    const id = latestActiveId.current;\n    if (id !== undefined && id !== (reading?.kind === 'node' ? reading.id : null)) request(id);\n    // Only once a change has been offered: `reading` moving by itself is that change.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [askedParent]);\n\n  const drawnKey = useRef<string | null>(null);\n  const resetKey = useRef<string | null>(null);\n\n  // A remounted chart says nothing about the focus it lost.\n  useEffect(() => {\n    setReading(null);\n    reportedId.current = null;\n    pinnedRef.current = null;\n    focusedRef.current = null;\n    // A new chart can draw before this runs or after it, and clearing the\n    // reading has to come first, so whichever is second applies the request.\n    resetKey.current = chartKey;\n    const id = latestActiveId.current ?? null;\n    if (drawnKey.current === chartKey) request(id);\n    else pendingId.current = id;\n  }, [chartKey, latestActiveId, request]);\n\n  const context = useMemo<SankeyChartContextValue>(\n    () => ({ rows, reading, status, select, setSlot }),\n    [rows, reading, status, select, setSlot]\n  );\n\n  const summary = label ?? `Sankey chart, ${rows.nodes.length} ${rows.nodes.length === 1 ? 'stage' : 'stages'}`;\n  const nameOf = (id: string) => rows.nodes.find((node) => node.id === id)?.name ?? id;\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'sankey-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(null);\n        },\n        children: (\n          <>\n            {loading ? null : (\n              <ul aria-label={summary} className=\"sr-only\">\n                {rows.links.map((row) => {\n                  const input = links[row.input];\n                  return (\n                    <li key={row.key}>\n                      {(input && labelForLink?.(input, row.input)) ??\n                        `${nameOf(row.source)} to ${nameOf(row.target)}, ${row.value}`}\n                    </li>\n                  );\n                })}\n              </ul>\n            )}\n            <div\n              ref={plotRef}\n              data-slot=\"sankey-chart-plot\"\n              data-dimmed={linksSlot?.gradient && reading ? '' : undefined}\n              className={slotClasses.plot()}\n              style={{ height }}\n              onClick={(event) => {\n                const point = interactionRef.current?.resolvePointer(event.clientX, event.clientY)?.point ?? null;\n                pin(point && point.key === pinnedRef.current?.key ? null : point);\n              }}\n              onKeyDown={(event) => {\n                if ((event.key === 'Enter' || event.key === ' ') && focusedRef.current) {\n                  event.preventDefault();\n                  pin(focusedRef.current.key === pinnedRef.current?.key ? null : focusedRef.current);\n                }\n              }}\n            >\n              {width > 0 ? (\n                <Chart\n                  // An entrance only plays on a chart's first paint, so the flow\n                  // arriving after a load, or a replay, is a new chart.\n                  key={chartKey}\n                  definition={definition}\n                  renderer={renderer}\n                  ariaLabel={summary}\n                  height={height}\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                    setEnteredKey(chartKey);\n                    const pending = pendingId.current;\n                    // Only once it can land: asking for a node that is not there clears the pin.\n                    if (pending !== null && resetKey.current === chartKey && pointsRef.current.some(({ datum }) => isNode(datum) && datum.id === pending)) request(pending);\n                  }}\n                />\n              ) : null}\n            </div>\n            {children}\n          </>\n        ),\n      },\n      props\n    ),\n  });\n\n  return <SankeyChartContext.Provider value={context}>{element}</SankeyChartContext.Provider>;\n});\nSankeyChartRoot.displayName = 'SankeyChart';\n\n/**\n * The waiting shape: plain equal bars and ribbons. Varied thicknesses would be\n * an invented routing, and nobody can tell one from a real one until it changes.\n */\nfunction skeletonMarks(width: number, height: number, vertical: boolean, bar: number, reach: number) {\n  const along = vertical ? height : width;\n  const cross = vertical ? width : height;\n  const step = (along - bar) / Math.max(SKELETON_COLUMNS - 1, 1);\n  const flip = <T,>(a: T, b: T): [T, T] => (vertical ? [b, a] : [a, b]);\n  const blank = { value: 0, layer: 0, color: 'var(--muted)', endColor: 'var(--muted)', bar: true, onRow: false };\n  const bars = Array.from({ length: SKELETON_COLUMNS }, (_unused, column): NodeRow => {\n    const [x0, y0] = flip(column * step, cross / 6);\n    const [x1, y1] = flip(column * step + bar, (cross * 5) / 6);\n    return { ...blank, kind: 'node', key: `bar-${column}`, id: `bar-${column}`, name: '', x0, y0, x1, y1 };\n  });\n  const lane = cross / 6;\n  const ribbons = Array.from({ length: SKELETON_COLUMNS - 1 }, (_unused, column) =>\n    [cross / 3, (cross * 2) / 3].map((at, index): LinkRow => {\n      const edges: Span = [at - lane / 2, at + lane / 2];\n      return {\n        ...blank,\n        kind: 'link',\n        key: `ribbon-${column}-${index}`,\n        input: -1,\n        source: '',\n        target: '',\n        from: column * step + bar,\n        to: (column + 1) * step,\n        start: edges,\n        end: edges,\n      };\n    })\n  ).flat();\n  return [\n    ribbonMark(ribbons, { id: 'sankey-skeleton-links', vertical, reach, fill: () => 'var(--muted)', still: true }),\n    rect(bars, {\n      id: 'sankey-skeleton-nodes',\n      x1: (row: NodeRow) => row.x0,\n      x2: (row: NodeRow) => row.x1,\n      y1: (row: NodeRow) => row.y0,\n      y2: (row: NodeRow) => row.y1,\n      key: (row: NodeRow) => row.key,\n      fill: 'var(--muted)',\n      radius: 3,\n      motion: false,\n    }),\n  ];\n}\n\nfunction useLatest<T>(value: T) {\n  const [latest] = useState(() => ({ current: value }));\n  useEffect(() => {\n    latest.current = value;\n  });\n  return latest;\n}\n\nexport interface SankeyChartLinksProps {\n  /** Blend each ribbon from its source's colour to its target's, at rest as well as on a route. */\n  gradient?: boolean;\n  /** A ribbon's opacity at rest. Defaults to `0.09`, or `0.45` with `gradient`. */\n  opacity?: number;\n  /** A ribbon's opacity on the route being read. Defaults to `0.42`, or `0.8` with `gradient`. */\n  activeOpacity?: number;\n}\n\n/**\n * The ribbons. Grey at rest, and in their source's colour on the route being\n * read. With `gradient` they keep their colours at rest, and a reading dims the rest.\n */\nfunction SankeyChartLinks({ gradient = false, opacity = gradient ? 0.45 : 0.09, activeOpacity = gradient ? 0.8 : 0.42 }: SankeyChartLinksProps) {\n  const { setSlot } = useChart('SankeyChart.Links');\n  useEffect(() => {\n    setSlot('links', { gradient, opacity, activeOpacity });\n    return () => setSlot('links', undefined);\n  }, [gradient, opacity, activeOpacity, setSlot]);\n  return null;\n}\nSankeyChartLinks.displayName = 'SankeyChart.Links';\n\nexport interface SankeyChartNodesProps {\n  /** Corner radius on a node's bar, in pixels. */\n  radius?: number;\n  /** A bar's opacity when it is off the route being read. */\n  dimOpacity?: number;\n  /** Whether hovering or pressing a bar reads its node. */\n  interactive?: boolean;\n}\n\n/** The bars the ribbons run between, drawn over them so a node keeps a clean edge. */\nfunction SankeyChartNodes({ radius = 3, dimOpacity = 0.25, interactive = true }: SankeyChartNodesProps) {\n  const { setSlot } = useChart('SankeyChart.Nodes');\n  useEffect(() => {\n    setSlot('nodes', { radius, dimOpacity, interactive });\n    return () => setSlot('nodes', undefined);\n  }, [radius, dimOpacity, interactive, setSlot]);\n  return null;\n}\nSankeyChartNodes.displayName = 'SankeyChart.Nodes';\n\nexport interface SankeyChartLabelsProps {\n  /** Format the figure under a name. Defaults to a compact number. */\n  formatValue?: (value: number, id: string) => string;\n  /** Show the figure under the name. */\n  showValue?: boolean;\n  /** Hide the name on a bar shorter than this, in pixels. */\n  minHeight?: number;\n}\n\n/**\n * The names, beside the bars. The last column's read inwards, so the names stay\n * inside the box at both ends. A name is shown whole or not at all: where two\n * would collide the larger stage keeps its name.\n */\nfunction SankeyChartLabels({ formatValue, showValue = false, minHeight = 6 }: SankeyChartLabelsProps) {\n  const { setSlot } = useChart('SankeyChart.Labels');\n  const latest = useLatest({ formatValue });\n  useEffect(() => {\n    setSlot('labels', { showValue, minHeight, latest });\n    return () => setSlot('labels', undefined);\n  }, [showValue, minHeight, latest, setSlot]);\n  return null;\n}\nSankeyChartLabels.displayName = 'SankeyChart.Labels';\n\nexport interface SankeyChartTooltipProps {\n  /** Format the figures. Defaults to a compact number. */\n  formatValue?: (value: number) => string;\n  /** Added to the readout's surface. */\n  className?: string;\n}\n\n/** The figures in a popover beside what is being read. It covers some of the diagram; `Breakdown` does not. */\nfunction SankeyChartTooltip({ formatValue, className }: SankeyChartTooltipProps) {\n  const { setSlot } = useChart('SankeyChart.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}\nSankeyChartTooltip.displayName = 'SankeyChart.Tooltip';\n\n/** The waiting shape, drawn while `status` is `loading`. */\nfunction SankeyChartSkeleton() {\n  const { setSlot } = useChart('SankeyChart.Skeleton');\n  useEffect(() => {\n    setSlot('skeleton', true);\n    return () => setSlot('skeleton', undefined);\n  }, [setSlot]);\n  return null;\n}\nSankeyChartSkeleton.displayName = 'SankeyChart.Skeleton';\n\nexport interface SankeyChartBreakdownProps extends ComponentProps<'div'> {\n  /** Format the figures. Defaults to a compact number. */\n  formatValue?: (value: number) => string;\n  /** How many rows each side shows before stopping. */\n  maxRows?: number;\n  /** Fires with the node at the other end of a row, as the chart follows it there. */\n  onSelectNode?: (id: string) => void;\n  /** The heading over the stages nothing arrives at, while nothing is being read. */\n  startsTitle?: ReactNode;\n  /** The heading over the stages nothing leaves, while nothing is being read. */\n  endsTitle?: ReactNode;\n  /** The heading over what arrives at the stage being read. */\n  sourcesTitle?: ReactNode;\n  /** The heading over what leaves the stage being read. */\n  targetsTitle?: ReactNode;\n}\n\n/**\n * Optional: leave it out for the diagram alone. What is being read, written out\n * under the diagram: where each stream came from and where it went, or where the\n * whole flow starts and ends while nothing is. A row selects the node it names,\n * so a flow can be walked one stage at a time.\n */\nfunction SankeyChartBreakdown({\n  formatValue,\n  maxRows,\n  onSelectNode,\n  startsTitle = 'Sources',\n  endsTitle = 'Outcomes',\n  sourcesTitle = 'From',\n  targetsTitle = 'To',\n  className,\n  render,\n  style,\n  ...props\n}: SankeyChartBreakdownProps & RenderProp<'div'>) {\n  const { rows, status, select } = useChart('SankeyChart.Breakdown');\n  const { activeId, activeLink, sources, targets, starts, ends } = useSankeyChart();\n  const slots = sankeyChartVariants();\n  const format = formatValue ?? compactNumber;\n  const limit = maxRows && maxRows > 0 ? Math.floor(maxRows) : undefined;\n\n  // Held at the tallest stage's height, so reading one does not move the page under the pointer.\n  const tallest = useMemo(() => {\n    let most = 1;\n    for (const node of rows.nodes) {\n      most = Math.max(\n        most,\n        rows.links.filter(({ source }) => source === node.id).length,\n        rows.links.filter(({ target }) => target === node.id).length\n      );\n    }\n    most = Math.max(most, starts.length, ends.length);\n    // Past the limit, \"and N more\" takes a row of its own.\n    return limit && most > limit ? limit + 1 : most;\n  }, [rows, starts, ends, limit]);\n\n  const flowRow = (flow: SankeyChartFlow, showShare: boolean) => (\n    <button\n      key={flow.id}\n      type=\"button\"\n      className={slots.breakdownRow()}\n      onClick={(event) => {\n        // This row is about to be replaced, and focus would fall out of the chart with it.\n        event.currentTarget.closest<HTMLElement>('[data-slot=\"sankey-chart-breakdown\"]')?.focus();\n        select(flow.id);\n        onSelectNode?.(flow.id);\n      }}\n    >\n      <span className={slots.swatch()} style={{ background: flow.color }} />\n      <span className={slots.rowLabel()}>{flow.label}</span>\n      <span className={slots.rowValue()}>{format(flow.value)}</span>\n      {showShare ? <span className={slots.rowShare()}>{Math.round(flow.share * 100)}%</span> : null}\n    </button>\n  );\n\n  const side = (title: ReactNode, flows: SankeyChartFlow[]) => {\n    const shown = limit ? flows.slice(0, limit) : flows;\n    const rest = flows.length - shown.length;\n    return (\n      <div className={slots.breakdownSide()}>\n        <div className={slots.breakdownTitle()}>{title}</div>\n        {shown.map((flow) => flowRow(flow, true))}\n        {rest > 0 ? <div className={slots.breakdownPlaceholder()}>{`and ${rest} more`}</div> : null}\n      </div>\n    );\n  };\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'sankey-chart-breakdown',\n        'aria-live': 'polite' as const,\n        tabIndex: -1,\n        className: slots.breakdown({ className }),\n        // A row is 1.625rem with its gap, the heading over a side about as much, and 0.75rem pads the top.\n        style: { minHeight: `${(tallest + 1) * 1.625 + 0.8125}rem`, ...style },\n        children: activeLink ? (\n          <div className={slots.breakdownSides()}>\n            <div className={slots.breakdownSide()}>\n              <div className={slots.breakdownTitle()}>{sourcesTitle}</div>\n              {flowRow(activeLink.source, true)}\n            </div>\n            <div className={slots.breakdownSide()}>\n              <div className={slots.breakdownTitle()}>{targetsTitle}</div>\n              {flowRow(activeLink.target, true)}\n            </div>\n          </div>\n        ) : activeId ? (\n          <div className={slots.breakdownSides()}>\n            {side(sourcesTitle, sources)}\n            {side(targetsTitle, targets)}\n          </div>\n        ) : (\n          <div className={slots.breakdownSides()}>\n            {side(startsTitle, starts)}\n            {side(endsTitle, ends)}\n          </div>\n        ),\n      },\n      props\n    ),\n  });\n\n  return status === 'loading' || !rows.nodes.length ? null : element;\n}\nSankeyChartBreakdown.displayName = 'SankeyChart.Breakdown';\n\nexport interface SankeyChartLegendProps extends ComponentProps<'div'> {\n  /** How many names to show before stopping. */\n  limit?: number;\n  /** Show each node's share of the largest column's total beside its name. */\n  showShare?: boolean;\n}\n\n/**\n * Optional: every stage named under the diagram, and a way to reach a bar too\n * small to carry a name. Pressing one selects the node its bar would.\n */\nfunction SankeyChartLegend({ limit, showShare = true, className, render, ...props }: SankeyChartLegendProps & RenderProp<'div'>) {\n  const { rows, status, reading, select } = useChart('SankeyChart.Legend');\n  const slots = sankeyChartVariants();\n  const activeId = reading?.kind === 'node' ? reading.id : null;\n\n  // Against the largest column rather than every node, which counts what passes through twice.\n  const byLayer = new Map<number, number>();\n  for (const node of rows.nodes) byLayer.set(node.layer, (byLayer.get(node.layer) ?? 0) + node.value);\n  const total = Math.max(0, ...byLayer.values());\n  const shown = limit && limit > 0 ? rows.nodes.slice(0, Math.floor(limit)) : rows.nodes;\n\n  const element = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'sankey-chart-legend',\n        className: slots.legend({ className }),\n        children: shown.map((node) => (\n          <button\n            key={node.id}\n            type=\"button\"\n            aria-pressed={activeId === node.id}\n            data-dimmed={activeId !== null && activeId !== node.id ? '' : undefined}\n            className={slots.legendItem()}\n            onClick={() => select(activeId === node.id ? null : node.id)}\n          >\n            <span className={slots.swatch()} style={{ background: node.color }} />\n            <span className={slots.legendLabel()}>{node.name}</span>\n            {showShare ? <span className={slots.legendShare()}>{total > 0 ? Math.round((node.value / total) * 100) : 0}%</span> : null}\n          </button>\n        )),\n      },\n      props\n    ),\n  });\n\n  return status === 'loading' || !rows.nodes.length ? null : element;\n}\nSankeyChartLegend.displayName = 'SankeyChart.Legend';\n\nexport interface SankeyChartHeaderProps extends Omit<ComponentProps<'div'>, 'title'> {\n  /** Small line above the value: what the flow 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 diagram. The value is not derived, because 128400 is a\n * count, a currency or a rate depending on what was routed. A readout that\n * follows the pointer takes it from `useSankeyChart` and passes the string down.\n */\nfunction SankeyChartHeader({ title, value, caption, className, children, render, ...props }: SankeyChartHeaderProps & RenderProp<'div'>) {\n  const slots = sankeyChartVariants();\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'sankey-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}\nSankeyChartHeader.displayName = 'SankeyChart.Header';\n\nexport const SankeyChart = Object.assign(SankeyChartRoot, {\n  Header: SankeyChartHeader,\n  Links: SankeyChartLinks,\n  Nodes: SankeyChartNodes,\n  Labels: SankeyChartLabels,\n  Tooltip: SankeyChartTooltip,\n  Breakdown: SankeyChartBreakdown,\n  Legend: SankeyChartLegend,\n  Skeleton: SankeyChartSkeleton,\n});\n\n/* By name as well, for a Server Component, which cannot dot into a client\n   module. */\nexport {\n  SankeyChartHeader,\n  SankeyChartLinks,\n  SankeyChartNodes,\n  SankeyChartLabels,\n  SankeyChartTooltip,\n  SankeyChartBreakdown,\n  SankeyChartLegend,\n  SankeyChartSkeleton,\n};\n"
    },
    {
      "path": "components/panelui/sankey-chart/sankey-layout.ts",
      "type": "registry:component",
      "target": "@components/panelui/sankey-chart/sankey-layout.ts",
      "content": "/**\n * Where a flow diagram's nodes and ribbons go.\n *\n * The app library's SankeyChart runs the same code, so a flow is arranged the\n * same on both platforms. The copies have to stay identical below this header,\n * and a contract test holds them there.\n *\n * ## The problem the layout is solving\n *\n * A node's column is decided by the flow, not by the caller — a stage that\n * receives from another has to be drawn after it or the ribbon runs backwards.\n * Its height is its value. Neither of those is a choice. What is left over is\n * the *order within a column*, and that is the whole difficulty: the same graph\n * drawn in two orders is the same numbers with a different number of crossings,\n * and crossings are the only thing that makes one of these unreadable.\n *\n * There is no cheap exact answer — minimising crossings is the kind of problem\n * that is only solved by trying — so the order is settled by relaxation. Every\n * node is pulled towards the average height of what it connects to, the pull\n * weakens each round, and nodes that end up overlapping are pushed apart. Six\n * rounds is where the picture stops visibly improving.\n *\n * ## Why it never throws\n *\n * A flow that loops back on itself has no left-to-right reading at all, and the\n * textbook answer is to refuse the graph. A chart cannot refuse: the data is\n * usually arriving from somewhere nobody in the room controls, and a screen\n * that crashes on a bad row is worse than one that draws the rows it can. So a\n * link that closes a loop is dropped, counted, and reported on the layout —\n * the caller can say so, and the rest of the diagram is still true.\n */\n\n/** Which column a node is pushed into when the flow leaves a choice. */\nexport type SankeyAlign = 'justify' | 'left' | 'right' | 'center';\n\nexport interface SankeyLayoutNodeInput {\n  /** Stable key the links name. */\n  id: string;\n  /**\n   * Pins the node's total, for a stage whose links do not account for all of\n   * it — a step that also loses some of what it received to nowhere.\n   */\n  value?: number;\n}\n\nexport interface SankeyLayoutLinkInput {\n  source: string;\n  target: string;\n  value: number;\n}\n\n/** Which nodes get folded into one, and what the result is called. */\nexport interface SankeyCollapse {\n  /**\n   * Keep at most this many nodes in a column, bucket included. A column with\n   * more folds its smallest until it fits.\n   */\n  maxPerColumn?: number;\n  /**\n   * Fold any node worth less than this share of its own column, `0` to `1`.\n   */\n  minShare?: number;\n  /** What the bucket is called. Defaults to `Other`. */\n  label?: string;\n}\n\nexport interface SankeyLayoutOptions {\n  width: number;\n  height: number;\n  /** How thick a node's bar is drawn, in points. */\n  nodeWidth: number;\n  /** The gap asked for between two nodes in a column, in points. */\n  nodePadding: number;\n  align: SankeyAlign;\n  /** Relaxation rounds. More is steadier and slower; six is the useful knee. */\n  iterations: number;\n  /**\n   * Folds a column's smallest nodes into one bucket before laying it out.\n   *\n   * A ribbon carries its value in its thickness, so a column of thirty is\n   * thirty hairlines — present in the data and unreadable on the screen. This\n   * is the only option here that reduces what is drawn rather than rearranging\n   * it.\n   */\n  collapse?: SankeyCollapse;\n}\n\nexport interface SankeyLayoutNode {\n  id: string;\n  /**\n   * Position in the input array, so a caller can find its own datum again.\n   * `-1` on a node the layout made up rather than was given — see `collapsed`.\n   */\n  index: number;\n  /**\n   * The ids folded into this node, on the bucket `collapse` produced. Absent\n   * on every node that came from the caller's array, which is how the two are\n   * told apart without comparing ids against the input.\n   */\n  collapsed?: string[];\n  /** Which column it landed in, counting from the left. */\n  layer: number;\n  /** What flows through it: the larger of what arrives and what leaves. */\n  value: number;\n  x0: number;\n  x1: number;\n  y0: number;\n  y1: number;\n}\n\nexport interface SankeyLayoutLink {\n  index: number;\n  /**\n   * Position in the caller's link array. Not the same as `index`: links that\n   * name nothing or close a loop are dropped, so the drawn order closes up\n   * behind them while this still points at the row it came from.\n   */\n  input: number;\n  /** Index into the laid-out nodes, not into the caller's array. */\n  source: number;\n  target: number;\n  value: number;\n  /** How thick the ribbon is, in points. */\n  width: number;\n  /**\n   * The ribbon's centre where it leaves the source, across the flow — points\n   * from the top of an upright layout, and from the left of a transposed one.\n   */\n  y0: number;\n  /** And where it meets the target. */\n  y1: number;\n}\n\nexport interface SankeyLayout {\n  nodes: SankeyLayoutNode[];\n  links: SankeyLayoutLink[];\n  /** How many columns the flow turned out to need. */\n  columns: number;\n  /** Links dropped for closing a loop, naming nothing, or carrying nothing. */\n  dropped: number;\n}\n\ninterface Node {\n  id: string;\n  index: number;\n  /**\n   * Position in the laid-out array, which is not `index` — a repeated id is\n   * skipped, so the two drift apart the moment the data has one.\n   */\n  slot: number;\n  fixedValue: number | undefined;\n  value: number;\n  /** Longest run of links from a node nothing feeds. */\n  depth: number;\n  /** Longest run of links to a node that feeds nothing. */\n  toSink: number;\n  layer: number;\n  x0: number;\n  x1: number;\n  y0: number;\n  y1: number;\n  sourceLinks: Link[];\n  targetLinks: Link[];\n}\n\ninterface Link {\n  index: number;\n  input: number;\n  source: Node;\n  target: Node;\n  value: number;\n  width: number;\n  y0: number;\n  y1: number;\n}\n\nconst EMPTY: SankeyLayout = { nodes: [], links: [], columns: 0, dropped: 0 };\n\n/** The most of the height the gaps in one column may take between them. */\nconst MAX_PADDING_SHARE = 0.5;\n\nfunction ascendingBreadth(a: Node, b: Node): number {\n  return a.y0 - b.y0;\n}\n\nfunction ascendingSourceBreadth(a: Link, b: Link): number {\n  return ascendingBreadth(a.source, b.source) || a.index - b.index;\n}\n\nfunction ascendingTargetBreadth(a: Link, b: Link): number {\n  return ascendingBreadth(a.target, b.target) || a.index - b.index;\n}\n\nfunction sumValues(links: Link[]): number {\n  let total = 0;\n  for (const link of links) total += link.value;\n  return total;\n}\n\n/**\n * The links worth drawing, with the ones that close a loop taken out.\n *\n * Depth-first, colouring a node grey while it is on the stack: a link to a grey\n * node is a link back into the run currently being walked, which is the\n * definition of a loop. Dropping that one link is the smallest cut that breaks\n * it, and it keeps every other link in the cycle — so a diagram of mostly-good\n * data loses one ribbon rather than a whole branch.\n *\n * Iterative rather than recursive: a deep chain of stages is ordinary data, and\n * a blown call stack is not an acceptable failure for one.\n */\nfunction withoutCycles(nodes: Node[], links: Link[]): { kept: Link[]; dropped: number } {\n  const WHITE = 0;\n  const GREY = 1;\n  const BLACK = 2;\n  const state = new Uint8Array(nodes.length);\n  const back = new Set<number>();\n\n  for (const root of nodes) {\n    if (state[root.slot] !== WHITE) continue;\n    // Each frame is a node and how far through its outgoing links we are.\n    const stack: { node: Node; cursor: number }[] = [{ node: root, cursor: 0 }];\n    state[root.slot] = GREY;\n\n    while (stack.length) {\n      const frame = stack[stack.length - 1]!;\n      const outgoing = frame.node.sourceLinks;\n\n      if (frame.cursor >= outgoing.length) {\n        state[frame.node.slot] = BLACK;\n        stack.pop();\n        continue;\n      }\n\n      const link = outgoing[frame.cursor]!;\n      frame.cursor += 1;\n      if (back.has(link.index)) continue;\n\n      const next = link.target;\n      if (state[next.slot] === GREY) {\n        back.add(link.index);\n      } else if (state[next.slot] === WHITE) {\n        state[next.slot] = GREY;\n        stack.push({ node: next, cursor: 0 });\n      }\n    }\n  }\n\n  if (!back.size) return { kept: links, dropped: 0 };\n  return { kept: links.filter((link) => !back.has(link.index)), dropped: back.size };\n}\n\n/** How far a node is from the start of the flow, the long way round. */\nfunction computeDepths(nodes: Node[]): void {\n  let current = new Set(nodes);\n  let next = new Set<Node>();\n  let x = 0;\n\n  while (current.size) {\n    for (const node of current) {\n      node.depth = x;\n      for (const link of node.sourceLinks) next.add(link.target);\n    }\n    // The graph is acyclic by here, so this cannot run away — the guard is for\n    // the case where it is not, which is a bug rather than bad data.\n    if (++x > nodes.length) break;\n    current = next;\n    next = new Set();\n  }\n}\n\n/** And how far it is from the end of it. */\nfunction computeToSink(nodes: Node[]): void {\n  let current = new Set(nodes);\n  let next = new Set<Node>();\n  let x = 0;\n\n  while (current.size) {\n    for (const node of current) {\n      node.toSink = x;\n      for (const link of node.targetLinks) next.add(link.source);\n    }\n    if (++x > nodes.length) break;\n    current = next;\n    next = new Set();\n  }\n}\n\n/**\n * Which column a node belongs in.\n *\n * `left` reads the flow from where things start, `right` from where they end,\n * and the two disagree about everything in between. `justify` is the default\n * because it does the one thing a reader expects of the edges: every node that\n * feeds nothing is pushed to the last column, so the diagram ends in a straight\n * line of destinations rather than a ragged one.\n */\nfunction layerOf(node: Node, columns: number, align: SankeyAlign): number {\n  switch (align) {\n    case 'left':\n      return node.depth;\n    case 'right':\n      return columns - 1 - node.toSink;\n    case 'center': {\n      if (node.targetLinks.length) return node.depth;\n      if (!node.sourceLinks.length) return 0;\n      let least = Infinity;\n      for (const link of node.sourceLinks) least = Math.min(least, link.target.depth);\n      return least - 1;\n    }\n    default:\n      return node.sourceLinks.length ? node.depth : columns - 1;\n  }\n}\n\n/**\n * The height a target would sit at for its ribbon from `source` to run flat.\n *\n * Every link leaving a node is stacked against its neighbours, so \"flat\" is not\n * the node's own height — it is that height plus whatever is stacked above this\n * particular ribbon at one end, minus what is stacked above it at the other.\n */\nfunction targetTop(source: Node, target: Node, padding: number): number {\n  let y = source.y0 - ((source.sourceLinks.length - 1) * padding) / 2;\n  for (const link of source.sourceLinks) {\n    if (link.target === target) break;\n    y += link.width + padding;\n  }\n  for (const link of target.targetLinks) {\n    if (link.source === source) break;\n    y -= link.width;\n  }\n  return y;\n}\n\n/** The same reading, taken from the target's end. */\nfunction sourceTop(source: Node, target: Node, padding: number): number {\n  let y = target.y0 - ((target.targetLinks.length - 1) * padding) / 2;\n  for (const link of target.targetLinks) {\n    if (link.source === source) break;\n    y += link.width + padding;\n  }\n  for (const link of source.sourceLinks) {\n    if (link.target === target) break;\n    y -= link.width;\n  }\n  return y;\n}\n\nfunction reorderNodeLinks(node: Node): void {\n  for (const link of node.targetLinks) {\n    link.source.sourceLinks.sort(ascendingTargetBreadth);\n  }\n  for (const link of node.sourceLinks) {\n    link.target.targetLinks.sort(ascendingSourceBreadth);\n  }\n}\n\n/** Push nodes down until none of them overlaps the one above it. */\nfunction resolveDown(column: Node[], y: number, from: number, alpha: number, padding: number): void {\n  let edge = y;\n  for (let i = from; i < column.length; i += 1) {\n    const node = column[i]!;\n    const shift = (edge - node.y0) * alpha;\n    if (shift > 1e-6) {\n      node.y0 += shift;\n      node.y1 += shift;\n    }\n    edge = node.y1 + padding;\n  }\n}\n\n/** And up, for the ones that have run off the bottom. */\nfunction resolveUp(column: Node[], y: number, from: number, alpha: number, padding: number): void {\n  let edge = y;\n  for (let i = from; i >= 0; i -= 1) {\n    const node = column[i]!;\n    const shift = (node.y1 - edge) * alpha;\n    if (shift > 1e-6) {\n      node.y0 -= shift;\n      node.y1 -= shift;\n    }\n    edge = node.y0 - padding;\n  }\n}\n\n/**\n * Four passes, pivoting on the middle node of the column.\n *\n * Starting from the middle rather than the top is what keeps a column centred:\n * resolving downwards from the top pushes the whole column towards the bottom\n * every round, and after six rounds everything is piled against the floor. The\n * last two passes are the ones that catch a column that has been pushed past\n * an edge, and they run outside-in for the same reason.\n */\nfunction resolveCollisions(column: Node[], alpha: number, padding: number, height: number): void {\n  const middle = column.length >> 1;\n  const pivot = column[middle];\n  if (!pivot) return;\n  resolveUp(column, pivot.y0 - padding, middle - 1, alpha, padding);\n  resolveDown(column, pivot.y1 + padding, middle + 1, alpha, padding);\n  resolveUp(column, height, column.length - 1, alpha, padding);\n  resolveDown(column, 0, 0, alpha, padding);\n}\n\n/**\n * Lays out a flow diagram.\n *\n * Returns positions in points inside a `width` by `height` box. An input that\n * cannot be drawn — no nodes, no room, nothing carrying a value — comes back\n * empty rather than as a diagram of zeroes.\n */\n/**\n * A bucket's id, chosen so it cannot be one the caller already used.\n *\n * Suffixed rather than prefixed with something unlikely: the id is what the\n * chart falls back to for the name, so a readable one means a bucket reads as\n * \"Other\" without anybody registering a label for it.\n */\nfunction bucketId(label: string, taken: Set<string>, layer: number): string {\n  if (!taken.has(label)) return label;\n  let candidate = `${label} (${layer + 1})`;\n  let n = 2;\n  while (taken.has(candidate)) {\n    candidate = `${label} (${layer + 1}.${n})`;\n    n += 1;\n  }\n  return candidate;\n}\n\ninterface CollapsePlan {\n  nodes: SankeyLayoutNodeInput[];\n  links: SankeyLayoutLinkInput[];\n  /** Bucket id -> the caller ids folded into it. */\n  buckets: Map<string, string[]>;\n  /** New node id -> the caller's index, or `-1` for a bucket. */\n  origin: Map<string, number>;\n  /** New link position -> the caller's row, or `-1` where rows were merged. */\n  linkOrigin: number[];\n}\n\n/**\n * Which nodes to fold, and the graph that results.\n *\n * Worked out from a finished layout rather than from the raw rows, because\n * \"smallest in its column\" needs the columns, and the columns come from the\n * links. So the flow is solved once to find out where everything landed, the\n * tail is folded, and it is solved again — twice through a few hundred\n * microseconds of arithmetic, against a diagram nobody can read.\n *\n * Returns `null` when there is nothing worth folding. One node in a bucket is\n * not a bucket, it is a rename, so a column only collapses where at least two\n * of its nodes go in.\n */\nfunction planCollapse(\n  layout: SankeyLayout,\n  nodeInput: readonly SankeyLayoutNodeInput[],\n  linkInput: readonly SankeyLayoutLinkInput[],\n  collapse: SankeyCollapse\n): CollapsePlan | null {\n  const label = collapse.label ?? 'Other';\n  const maxPerColumn =\n    typeof collapse.maxPerColumn === 'number' && collapse.maxPerColumn >= 1\n      ? Math.floor(collapse.maxPerColumn)\n      : Infinity;\n  const minShare =\n    typeof collapse.minShare === 'number' && collapse.minShare > 0 ? collapse.minShare : 0;\n  if (maxPerColumn === Infinity && minShare === 0) return null;\n\n  const byLayer = new Map<number, SankeyLayoutNode[]>();\n  for (const node of layout.nodes) {\n    const column = byLayer.get(node.layer);\n    if (column) column.push(node);\n    else byLayer.set(node.layer, [node]);\n  }\n\n  /** Caller id -> the bucket it was folded into. */\n  const folded = new Map<string, string>();\n  const buckets = new Map<string, string[]>();\n  const taken = new Set(layout.nodes.map((node) => node.id));\n\n  for (const [layer, column] of byLayer) {\n    if (column.length < 2) continue;\n    let total = 0;\n    for (const node of column) total += node.value;\n    if (!(total > 0)) continue;\n\n    // Largest first, so \"the ones that go\" is always a tail of the list and\n    // the two rules can be applied to the same ordering.\n    const ranked = [...column].sort((a, b) => b.value - a.value || a.id.localeCompare(b.id));\n    const doomed = new Set<string>();\n    if (minShare > 0) {\n      for (const node of ranked) {\n        if (node.value / total < minShare) doomed.add(node.id);\n      }\n    }\n    if (ranked.length > maxPerColumn) {\n      // The bucket takes one of the places, so only `maxPerColumn - 1` survive.\n      for (const node of ranked.slice(Math.max(0, maxPerColumn - 1))) doomed.add(node.id);\n    }\n    if (doomed.size < 2) continue;\n\n    const id = bucketId(label, taken, layer);\n    taken.add(id);\n    const members = ranked.filter((node) => doomed.has(node.id)).map((node) => node.id);\n    buckets.set(id, members);\n    for (const member of members) folded.set(member, id);\n  }\n\n  if (!buckets.size) return null;\n\n  const origin = new Map<string, number>();\n  const nodes: SankeyLayoutNodeInput[] = [];\n  const emitted = new Set<string>();\n  for (const [index, input] of nodeInput.entries()) {\n    const bucket = folded.get(input.id);\n    if (bucket === undefined) {\n      if (emitted.has(input.id)) continue;\n      emitted.add(input.id);\n      nodes.push(input);\n      origin.set(input.id, index);\n      continue;\n    }\n    // The bucket takes the place of the first of its members, so a column's\n    // order is still the order the caller wrote.\n    if (emitted.has(bucket)) continue;\n    emitted.add(bucket);\n    // No pinned value: a bucket is worth what its links carry, and summing\n    // pins would state a total none of the rows support.\n    nodes.push({ id: bucket });\n    origin.set(bucket, -1);\n  }\n\n  /*\n   * The rows, with folded endpoints renamed to their bucket.\n   *\n   * Two rows that now name the same pair are added together — that is the\n   * whole point of a bucket, and leaving them separate would stack a dozen\n   * hairlines between the same two bars instead of one ribbon. A row whose\n   * ends both landed in one bucket described a flow inside it and has nowhere\n   * left to go, so it is taken out here rather than being failed by the second\n   * pass and counted a second time.\n   *\n   * Rows that were already undrawable pass through untouched, so the second\n   * pass fails them for the reason the first one did.\n   */\n  const rename = (id: string) => folded.get(id) ?? id;\n  const links: SankeyLayoutLinkInput[] = [];\n  const linkOrigin: number[] = [];\n  const mergedAt = new Map<string, number>();\n  for (const [index, row] of linkInput.entries()) {\n    const source = rename(row.source);\n    const target = rename(row.target);\n    const usable =\n      origin.has(source) &&\n      origin.has(target) &&\n      source !== target &&\n      typeof row.value === 'number' &&\n      Number.isFinite(row.value) &&\n      row.value > 0;\n\n    if (!usable) {\n      if (folded.has(row.source) && folded.has(row.target) && source === target) continue;\n      links.push(row);\n      linkOrigin.push(index);\n      continue;\n    }\n\n    const key = `${source}\\u0000${target}`;\n    const at = mergedAt.get(key);\n    if (at === undefined) {\n      mergedAt.set(key, links.length);\n      links.push({ source, target, value: row.value });\n      linkOrigin.push(index);\n      continue;\n    }\n    links[at] = { source, target, value: links[at]!.value + row.value };\n    // Merged: no single row of the caller's describes it any more.\n    linkOrigin[at] = -1;\n  }\n\n  return { nodes, links, buckets, origin, linkOrigin };\n}\n\n/**\n * The same arrangement, read down the screen instead of across it.\n *\n * A flow diagram has one axis carrying the order of the stages and another\n * carrying the values, and which of them is horizontal is a question about the\n * screen rather than about the data. So the layout is solved once, upright,\n * and turned afterwards — the alternative is a second copy of the relaxation\n * with every comparison reversed, which is the same maths maintained twice.\n *\n * Reflecting about the diagonal, so it is its own inverse: transposing twice\n * returns the layout unchanged. Call `sankeyLayout` with `width` and `height`\n * swapped and then pass the result through here, or the diagram comes back\n * fitted to the wrong box.\n */\nexport function transposeLayout(layout: SankeyLayout): SankeyLayout {\n  return {\n    ...layout,\n    nodes: layout.nodes.map((node) => ({\n      ...node,\n      x0: node.y0,\n      x1: node.y1,\n      y0: node.x0,\n      y1: node.x1,\n    })),\n    // A link's `y0`/`y1` are already across the flow rather than along it, so\n    // the axis they name changes while the numbers do not.\n    links: layout.links.map((link) => ({ ...link })),\n  };\n}\n\nexport function sankeyLayout(\n  nodeInput: readonly SankeyLayoutNodeInput[],\n  linkInput: readonly SankeyLayoutLinkInput[],\n  options: SankeyLayoutOptions\n): SankeyLayout {\n  const { width, height, align, iterations } = options;\n  const nodeWidth = Math.max(0, options.nodeWidth);\n  const requestedPadding = Math.max(0, options.nodePadding);\n\n  if (!nodeInput.length || !(width > 0) || !(height > 0)) return EMPTY;\n\n  /*\n   * Folding the tail needs the columns, and the columns come out of the links,\n   * so the only way to know what to fold is to lay it out once and look. The\n   * second pass runs with `collapse` cleared, which is what stops this\n   * recurring.\n   */\n  if (options.collapse) {\n    const bare = { ...options, collapse: undefined };\n    const first = sankeyLayout(nodeInput, linkInput, bare);\n    const plan = planCollapse(first, nodeInput, linkInput, options.collapse);\n    if (plan) {\n      const second = sankeyLayout(plan.nodes, plan.links, bare);\n      return {\n        ...second,\n        nodes: second.nodes.map((node) => {\n          const members = plan.buckets.get(node.id);\n          return {\n            ...node,\n            index: plan.origin.get(node.id) ?? -1,\n            ...(members ? { collapsed: members } : {}),\n          };\n        }),\n        links: second.links.map((link) => ({\n          ...link,\n          input: plan.linkOrigin[link.input] ?? -1,\n        })),\n        /*\n         * Counted from the pass that saw the caller's own rows. The second\n         * pass reads a graph this function invented, and how many of those\n         * failed is not something anybody asked about.\n         */\n        dropped: first.dropped,\n      };\n    }\n  }\n\n  const nodes: Node[] = [];\n  const byId = new Map<string, Node>();\n  for (const [index, input] of nodeInput.entries()) {\n    // A repeated id would give the links two nodes to mean; the first wins, so\n    // the diagram is the one the earlier row described rather than a mix.\n    if (byId.has(input.id)) continue;\n    const node: Node = {\n      id: input.id,\n      index,\n      slot: nodes.length,\n      fixedValue:\n        typeof input.value === 'number' && Number.isFinite(input.value) && input.value >= 0\n          ? input.value\n          : undefined,\n      value: 0,\n      depth: 0,\n      toSink: 0,\n      layer: 0,\n      x0: 0,\n      x1: 0,\n      y0: 0,\n      y1: 0,\n      sourceLinks: [],\n      targetLinks: [],\n    };\n    nodes.push(node);\n    byId.set(input.id, node);\n  }\n\n  let dropped = 0;\n  const links: Link[] = [];\n  for (const [inputIndex, input] of linkInput.entries()) {\n    const source = byId.get(input.source);\n    const target = byId.get(input.target);\n    const value = input.value;\n    // A link to nowhere, a link to itself, and a link carrying nothing are all\n    // undrawable for different reasons and all silently skipped.\n    if (!source || !target || source === target) {\n      dropped += 1;\n      continue;\n    }\n    if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n      dropped += 1;\n      continue;\n    }\n    links.push({\n      index: links.length,\n      input: inputIndex,\n      source,\n      target,\n      value,\n      width: 0,\n      y0: 0,\n      y1: 0,\n    });\n  }\n\n  for (const link of links) {\n    link.source.sourceLinks.push(link);\n    link.target.targetLinks.push(link);\n  }\n\n  const cut = withoutCycles(nodes, links);\n  if (cut.dropped) {\n    dropped += cut.dropped;\n    for (const node of nodes) {\n      node.sourceLinks = [];\n      node.targetLinks = [];\n    }\n    cut.kept.forEach((link, index) => {\n      link.index = index;\n      link.source.sourceLinks.push(link);\n      link.target.targetLinks.push(link);\n    });\n  }\n  const kept = cut.kept;\n\n  for (const node of nodes) {\n    node.value =\n      node.fixedValue ??\n      Math.max(sumValues(node.sourceLinks), sumValues(node.targetLinks));\n  }\n\n  computeDepths(nodes);\n  computeToSink(nodes);\n\n  let columnCount = 0;\n  for (const node of nodes) columnCount = Math.max(columnCount, node.depth);\n  columnCount += 1;\n\n  const columns: Node[][] = Array.from({ length: columnCount }, () => []);\n  // One column has nowhere to spread to, so its node sits at the left edge\n  // rather than dividing by a gap that does not exist.\n  const kx = columnCount > 1 ? (width - nodeWidth) / (columnCount - 1) : 0;\n  for (const node of nodes) {\n    const layer = Math.max(0, Math.min(columnCount - 1, Math.floor(layerOf(node, columnCount, align))));\n    node.layer = layer;\n    node.x0 = layer * kx;\n    node.x1 = node.x0 + nodeWidth;\n    columns[layer]!.push(node);\n  }\n\n  let tallest = 0;\n  for (const column of columns) tallest = Math.max(tallest, column.length);\n\n  /*\n   * The gap asked for is a maximum, not a promise. A column of twelve nodes at\n   * a padding of twelve is 132 points of gap, which on a phone is most of the\n   * chart — so a crowded column gives up its spacing rather than its bars,\n   * because a bar is the reading and the gap is only the separation.\n   *\n   * Hence the share as well as the count. Dividing the whole height by the gaps\n   * is the obvious cap and it is the wrong one: at twelve nodes in 120 points it\n   * hands every point to the gaps and leaves the bars exactly nothing, so the\n   * chart goes blank at precisely the crowding this is meant to survive. Half\n   * the height is the most the gaps may ever take between them.\n   */\n  const padding =\n    tallest > 1\n      ? Math.min(requestedPadding, (height * MAX_PADDING_SHARE) / (tallest - 1))\n      : requestedPadding;\n\n  /*\n   * One scale for every column, taken from whichever column it fits worst.\n   * A scale per column would draw two nodes of the same value at two different\n   * heights, which is the one thing this chart cannot do and still be read.\n   */\n  let ky = Infinity;\n  for (const column of columns) {\n    if (!column.length) continue;\n    let total = 0;\n    for (const node of column) total += node.value;\n    if (total <= 0) continue;\n    ky = Math.min(ky, (height - (column.length - 1) * padding) / total);\n  }\n  if (!Number.isFinite(ky) || ky <= 0) return { ...EMPTY, columns: columnCount, dropped };\n\n  for (const column of columns) {\n    let y = 0;\n    for (const node of column) {\n      node.y0 = y;\n      node.y1 = y + node.value * ky;\n      y = node.y1 + padding;\n      for (const link of node.sourceLinks) link.width = link.value * ky;\n    }\n    // Whatever the column did not use is shared out as extra space between its\n    // nodes, which centres a short column instead of hanging it from the top.\n    const slack = (height - y + padding) / (column.length + 1);\n    column.forEach((node, i) => {\n      node.y0 += slack * (i + 1);\n      node.y1 += slack * (i + 1);\n    });\n    for (const node of column) {\n      node.sourceLinks.sort(ascendingTargetBreadth);\n      node.targetLinks.sort(ascendingSourceBreadth);\n    }\n  }\n\n  const rounds = Math.max(0, Math.floor(iterations));\n  for (let i = 0; i < rounds; i += 1) {\n    /*\n     * The pull weakens and the shove strengthens as the rounds go by. Early on\n     * the nodes are still finding their neighbourhood and a firm pull is what\n     * gets them there; by the end the arrangement is settled and the only thing\n     * left worth doing is making sure nothing overlaps.\n     */\n    const alpha = 0.99 ** i;\n    const beta = Math.max(1 - alpha, (i + 1) / rounds);\n\n    for (let c = columnCount - 2; c >= 0; c -= 1) {\n      const column = columns[c]!;\n      for (const node of column) {\n        let weighted = 0;\n        let weight = 0;\n        for (const link of node.sourceLinks) {\n          // A ribbon that spans three columns is three times as expensive to\n          // bend as one that spans a single column, so it pulls three times\n          // as hard on where its ends sit.\n          const span = link.value * (link.target.layer - node.layer);\n          weighted += sourceTop(node, link.target, padding) * span;\n          weight += span;\n        }\n        if (!(weight > 0)) continue;\n        const shift = (weighted / weight - node.y0) * alpha;\n        node.y0 += shift;\n        node.y1 += shift;\n        reorderNodeLinks(node);\n      }\n      column.sort(ascendingBreadth);\n      resolveCollisions(column, beta, padding, height);\n    }\n\n    for (let c = 1; c < columnCount; c += 1) {\n      const column = columns[c]!;\n      for (const node of column) {\n        let weighted = 0;\n        let weight = 0;\n        for (const link of node.targetLinks) {\n          const span = link.value * (node.layer - link.source.layer);\n          weighted += targetTop(link.source, node, padding) * span;\n          weight += span;\n        }\n        if (!(weight > 0)) continue;\n        const shift = (weighted / weight - node.y0) * alpha;\n        node.y0 += shift;\n        node.y1 += shift;\n        reorderNodeLinks(node);\n      }\n      column.sort(ascendingBreadth);\n      resolveCollisions(column, beta, padding, height);\n    }\n  }\n\n  /*\n   * The ribbons are stacked against each node's edge in the order they were\n   * sorted into, and each one is recorded by its centre — which is where a\n   * stroked or filled ribbon of that thickness wants to be anchored.\n   */\n  for (const node of nodes) {\n    let out = node.y0;\n    for (const link of node.sourceLinks) {\n      link.y0 = out + link.width / 2;\n      out += link.width;\n    }\n    let into = node.y0;\n    for (const link of node.targetLinks) {\n      link.y1 = into + link.width / 2;\n      into += link.width;\n    }\n  }\n\n  const order = new Map(nodes.map((node, i) => [node, i]));\n\n  return {\n    columns: columnCount,\n    dropped,\n    nodes: nodes.map((node) => ({\n      id: node.id,\n      index: node.index,\n      layer: node.layer,\n      value: node.value,\n      x0: node.x0,\n      x1: node.x1,\n      y0: node.y0,\n      y1: node.y1,\n    })),\n    links: kept.map((link, index) => ({\n      index,\n      input: link.input,\n      source: order.get(link.source)!,\n      target: order.get(link.target)!,\n      value: link.value,\n      width: link.width,\n      y0: link.y0,\n      y1: link.y1,\n    })),\n  };\n}\n"
    }
  ]
}
