{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sankey-chart",
  "title": "Sankey chart",
  "description": "Flows between steps, such as where visitors go or where money goes, as bands as thick as their value between nodes as tall as what passes through them, with each node’s name and value beside it where they fit. A node or a flow under the pointer, or a node the keys reach, keeps every way through it bright while the rest step back, and new data moves every node and flow from where it is.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/chart.json",
    "https://kinoui.com/r/chart-core.json",
    "https://kinoui.com/r/chart-root.json",
    "https://kinoui.com/r/chart-flows.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/controllable.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/placeholder.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/sankey-chart.tsx",
      "content": "'use client'\n\nimport {\n  type CategoryChartProps,\n  type EntrancePhase,\n  figureProps,\n  IndexActive,\n  pickedName,\n  ShareTooltipContent,\n  useChartActive,\n  useChartLife,\n  useChartLoad,\n  useChartPick,\n  useIndexFocus,\n  useLeavingItems,\n} from '@/registry/lib/chart-base'\nimport { flowItem, type FlowStop, flowReader } from '@/registry/lib/chart-flow-reader'\nimport {\n  type FlowAlign,\n  flowAt,\n  flowEnds,\n  type FlowGraph,\n  flowGraph,\n  fitLabels,\n  type FlowLayout,\n  flowLayout,\n  flowMoves,\n  flowPath,\n  type FlowShape,\n  flowShapes,\n  flowShapesAt,\n  type LaidNode,\n  linkPath,\n  stepNode,\n} from '@/registry/lib/chart-flows'\nimport type { ChartConfig } from '@/registry/lib/chart-math'\nimport {\n  ChartFrame,\n  type ChartRootValue,\n  drawingSize,\n  isMeasured,\n  stepBackInkClassName,\n  swatchClassName,\n  useChartRoot,\n  useChartRootValue,\n  usePointsMove,\n} from '@/registry/lib/chart-root'\nimport { useControllable } from '@/registry/lib/controllable'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport {\n  placeholderBreatheClassName,\n  placeholderInkClassName,\n} from '@/registry/lib/placeholder'\nimport { type CSSProperties, memo, useMemo, useRef, useState } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The Sankey chart: flows between steps, such as where visitors go or where\n * money goes, as bands as thick as their value between nodes as tall as\n * what passes through them. Each row is a flow from one node to another;\n * the nodes come from the flows and stand in columns from the reading\n * start. A node or a flow under the pointer, or a node the keys reach,\n * keeps every way through it bright while the rest step back. New data\n * moves every node and flow from where it is, on the chart's moves, which\n * write their shapes each frame, so the feel, reduced motion and a slowed\n * playback time it as they time everything else; a flow that arrives draws\n * along its length.\n */\n\ninterface SankeyChartProps extends Omit<\n  CategoryChartProps,\n  | 'index'\n  | 'domain'\n  | 'tickCount'\n  | 'tickValues'\n  | 'allowDecimals'\n  | 'ordered'\n  | 'patterns'\n  | 'selected'\n  | 'defaultSelected'\n  | 'onSelectedChange'\n> {\n  /** The key of the node each flow starts from. */\n  source: string\n  /** The key of the node each flow goes to. */\n  target: string\n  /** The key of each flow's value. Rows between the same two nodes add up. */\n  dataKey: string\n  /** What the values are, such as \"Visitors\": the tooltip's and the data table's word for them. */\n  valueLabel?: string\n  /** How each column's nodes are ordered: where their flows cross least, or the rows' order. */\n  sort?: 'auto' | 'data'\n  /**\n   * Which column a node stands in: as far along as its longest way in, with\n   * the nodes nothing leaves in the last column (`justify`), as early as it\n   * can (`start`), as late as it can (`end`), or near its flows (`center`).\n   */\n  align?: FlowAlign\n  /** The colour of each flow: from its source's to its target's, or either one's. */\n  linkColor?: 'gradient' | 'source' | 'target'\n  /** What each node writes beside itself, where it has the room: its name and value, its name, or nothing. */\n  labels?: 'value' | 'name' | 'none'\n  /**\n   * How the flows arrive the first time the chart comes into view: drawn\n   * along their length, or simply there, the default, since a page that\n   * loads doesn't animate into place.\n   */\n  entrance?: 'draw' | 'none'\n}\n\nconst sankeyChartKeys = [\n  'source',\n  'target',\n  'dataKey',\n  'valueLabel',\n  'sort',\n  'align',\n  'linkColor',\n  'labels',\n  'entrance',\n]\n\n/** A node's width, in px. */\nconst NODE_WIDTH = 8\n/** The least room between two nodes of a column, in px. */\nconst NODE_PADDING = 12\n/** The room between a node and its label, in px. */\nconst LABEL_GAP = 6\n/** A line of a label, in px: the chart's text and its leading. */\nconst LABEL_LINE = 16\n/** The most of the plot's width the outer columns' labels may take, each, before they sit inside. */\nconst MOST_LABEL_ROOM = 0.3\n/** How far from a node, in px, the pointer still lights it. */\nconst NEAR_NODE = 4\n\n/**\n * The chart's root: the graph from the rows, laid out in the plot, with the\n * frame its legend and tooltip draw in.\n */\nfunction SankeyChart(props: SankeyChartProps) {\n  const {\n    data,\n    source,\n    target,\n    dataKey,\n    config,\n    valueLabel,\n    sort = 'auto',\n    align = 'justify',\n    linkColor = 'gradient',\n    labels = 'value',\n    entrance = 'none',\n    messages,\n    description,\n    empty,\n    className,\n    ref,\n  } = props\n  const [hidden, setHidden] = useControllable(\n    props.hiddenSeries,\n    props.defaultHiddenSeries ?? [],\n    props.onHiddenSeriesChange,\n  )\n  // Every node the rows name, so the legend can hide one; the shown ones make the graph.\n  const all = flowGraph(data, { source, target, dataKey, align })\n  const graph = flowGraph(data, { source, target, dataKey, align, hidden })\n  const nodes: ChartConfig = { ...config }\n  for (const node of all.nodes) nodes[node.key] ??= { label: nameText(node.name) }\n  const nodeByKey = new Map(graph.nodes.map((node) => [node.key, node]))\n\n  const nameOf = (key: string): string => {\n    const name =\n      nodeByKey.get(key)?.name ?? all.nodes.find((one) => one.key === key)?.name ?? key\n    if (props.categoryFormat) return props.categoryFormat(name)\n    const named = config[key]?.label\n    return typeof named === 'string' ? named : nameText(name)\n  }\n  const flowName = (key: string): string => {\n    const [from, to] = flowEnds(key)\n    return chart.messages.flow(nameOf(from), nameOf(to))\n  }\n\n  const state = useChartRoot(\n    {\n      ...props,\n      config: nodes,\n      hiddenSeries: hidden,\n      defaultHiddenSeries: undefined,\n      onHiddenSeriesChange: setHidden,\n      messages: {\n        series: 'Steps',\n        empty: 'No flows yet',\n        allHidden: 'Hiding these steps leaves no flows',\n        showAll: (count) => `Show all ${count} steps`,\n        ...messages,\n      },\n    },\n    { entrance: entrance !== 'none', heightFromData: false },\n  )\n  const chart = state\n  const load = useChartLoad(props)\n  const loaded = !load.placeholder && !load.failed\n  // Every node, then every flow, the hidden ones too, so hiding them all says so rather than\n  // that there are none; what the keys and `activeIndex` count are the ones still drawn.\n  const rows = loaded ? all.nodes.length + all.links.length : 0\n  const linkByKey = new Map(graph.links.map((link) => [link.key, link]))\n  const shownNodes = loaded ? all.nodes.filter((node) => nodeByKey.has(node.key)) : []\n  const shownLinks = loaded ? all.links.filter((link) => linkByKey.has(link.key)) : []\n  const items: FlowStop[] = [\n    ...shownNodes.map((node, at): FlowStop => ({\n      kind: 'node',\n      key: node.key,\n      name: nameOf(node.key),\n      value: nodeByKey.get(node.key)?.value ?? 0,\n      index: at,\n    })),\n    ...shownLinks.map((link, at): FlowStop => {\n      const drawn = linkByKey.get(link.key) ?? link\n      return {\n        kind: 'link',\n        key: link.key,\n        source: drawn.source.key,\n        target: drawn.target.key,\n        value: drawn.value,\n        datum: link.datum,\n        index: shownNodes.length + at,\n      }\n    }),\n  ]\n  const { status, phase } = useChartLife(\n    props,\n    state,\n    load,\n    {\n      rows,\n      shown: state.series.filter((key) => !hidden.includes(key)).length,\n      drawn: items.length,\n    },\n    { entrance: entrance !== 'none', cascade: null },\n  )\n  // Its props leave out `selected`, so nothing is picked.\n  const pick = useChartPick({}, items.map(flowKeyOf))\n  // What leaves moves with the rest, so the chart waits on the move before letting it go.\n  const marks = useLeavingItems(state.moves, items, flowKeyOf)\n\n  const size = drawingSize(chart.plotSize)\n  const label = valueLabel ?? chart.messages.value\n  const twoLines = labels === 'value'\n  const labelWidth = (key: string) => {\n    if (labels === 'none') return 0\n    const node = nodeByKey.get(key)\n    const name = chart.textWidth(nameOf(key))\n    return twoLines && node\n      ? Math.max(name, chart.textWidth(chart.valueText(node.value)))\n      : name\n  }\n  // The first column's labels stand before it and the last's after it, where they fit.\n  const lastLayer = graph.columns - 1\n  const roomFor = (layer: number) => {\n    const widest = Math.max(\n      0,\n      ...graph.nodes\n        .filter((node) => node.layer === layer)\n        .map((node) => labelWidth(node.key)),\n    )\n    const room = widest === 0 ? 0 : widest + LABEL_GAP\n    return room <= size.width * MOST_LABEL_ROOM ? room : 0\n  }\n  const startRoom = graph.columns > 1 ? roomFor(0) : 0\n  const endRoom = graph.columns > 1 ? roomFor(lastLayer) : 0\n  const layout = flowLayout(graph, {\n    width: size.width,\n    height: size.height,\n    nodeWidth: NODE_WIDTH,\n    nodePadding: NODE_PADDING,\n    start: startRoom,\n    end: endRoom,\n    sort,\n    direction: chart.direction,\n  })\n  // Each node's label, on its side, in the fullest form that clears the other labels and nodes.\n  const room = { start: startRoom, end: endRoom }\n  const sideOf = (key: string) =>\n    labelSide(nodeByKey.get(key)?.layer ?? 0, graph.columns, chart.direction, room)\n  const valueOf = (key: string) => chart.valueText(nodeByKey.get(key)?.value ?? 0)\n  const fits = fitLabels(\n    labels === 'none'\n      ? []\n      : graph.nodes.map((node) => {\n          const name = chart.textWidth(nameOf(node.key))\n          return {\n            key: node.key,\n            side: sideOf(node.key),\n            forms: [\n              ...(twoLines\n                ? [\n                    {\n                      fit: 'value' as const,\n                      width: Math.max(name, chart.textWidth(valueOf(node.key))),\n                      lines: 2,\n                    },\n                  ]\n                : []),\n              { fit: 'name' as const, width: name, lines: 1 },\n            ],\n          }\n        }),\n    layout,\n    { width: size.width, gap: LABEL_GAP, line: LABEL_LINE },\n  )\n  const labelOf = (key: string): NodeLabel | null => {\n    const fit = fits.get(key) ?? 'none'\n    if (fit === 'none') return null\n    return {\n      side: sideOf(key),\n      name: nameOf(key),\n      value: fit === 'value' ? valueOf(key) : null,\n    }\n  }\n  // The layout shown before this one, kept while what left it finishes leaving.\n  const signature = layoutSignature(layout)\n  const [held, setHeld] = useState<{\n    signature: string\n    now: FlowLayout\n    was: FlowLayout | null\n  }>({ signature, now: layout, was: null })\n  if (held.signature !== signature) setHeld({ signature, now: layout, was: held.now })\n  const was = held.signature === signature ? held.was : held.now\n  // The same layout object while its signature holds, so the marks' shapes stay the same objects.\n  const steady = held.signature === signature ? held.now : layout\n\n  const total = Math.max(\n    0,\n    ...Array.from({ length: graph.columns }, (_, layer) =>\n      graph.nodes\n        .filter((node) => node.layer === layer)\n        .reduce((sum, node) => sum + node.value, 0),\n    ),\n  )\n  const percent = numberFormatter(chart.locale, {\n    style: 'percent',\n    maximumFractionDigits: 1,\n  })\n  const share = (value: number, of: number) => percent.format(of === 0 ? 0 : value / of)\n  const nodeBox = new Map(layout.nodes.map((node) => [node.key, node]))\n  const linkBox = new Map(layout.links.map((link) => [link.key, link]))\n  const byKey = new Map(items.map((item) => [item.key, item]))\n  const colorOf = (key: string) =>\n    nodeColor(config, key, nodeByKey.get(key)?.layer ?? 0, graph.columns)\n\n  // The nodes as they are drawn: column by column from the reading start, each from the top.\n  const drawnOrder = graph.nodes\n    .toSorted(\n      (a, b) =>\n        a.layer - b.layer ||\n        (nodeBox.get(a.key)?.y0 ?? 0) - (nodeBox.get(b.key)?.y0 ?? 0),\n    )\n    .map((node) => node.key)\n  const nameOfStop = (stop: FlowStop) =>\n    stop.kind === 'node' ? nameOf(stop.key) : flowName(stop.key)\n  const reader = flowReader({\n    items,\n    drawnOrder,\n    step: (from, key) => stepNode(graph, layout, from, key, chart.direction),\n    hit: (point) => {\n      if (point.width === 0 || point.height === 0) return null\n      const found = flowAt(\n        {\n          x: (point.x / point.width) * size.width,\n          y: (point.y / point.height) * size.height,\n        },\n        layout,\n        NEAR_NODE,\n      )\n      if (!found) return null\n      return byKey.get('node' in found ? found.node : found.link) ?? null\n    },\n    // The tooltip sits above a node's top, or above the middle of a flow.\n    anchor: (stop) => {\n      if (size.width === 0 || size.height === 0) return null\n      const node = nodeBox.get(stop.key)\n      if (node) {\n        return {\n          x: (node.x0 + node.x1) / 2 / size.width,\n          y: node.y0 / size.height,\n          side: 'top',\n        }\n      }\n      const link = linkBox.get(stop.key)\n      if (!link) return null\n      const middle = (link.y0 + link.y1) / 2 - link.width / 2\n      return {\n        x: (link.x0 + link.x1) / 2 / size.width,\n        y: middle / size.height,\n        side: 'top',\n      }\n    },\n    words: {\n      describe: (stop) => {\n        const name = pickedName(\n          nameOfStop(stop),\n          pick.picked === stop.key,\n          chart.messages,\n        )\n        const node = nodeByKey.get(stop.key)\n        if (node) {\n          return `${name}: ${label} ${chart.valueText(node.value)}, ${share(node.value, total)}`\n        }\n        const link = linkByKey.get(stop.key)\n        if (!link) return `${name}: `\n        return `${name}: ${label} ${chart.valueText(link.value)}, ${chart.messages.outOf(share(link.value, link.source.value), nameOf(link.source.key))}`\n      },\n      table: {\n        header: chart.messages.from,\n        columns: [chart.messages.to, label, chart.messages.share],\n        rows: graph.links.map((link) => ({\n          key: link.key,\n          name: nameOf(link.source.key),\n          cells: [\n            nameOf(link.target.key),\n            chart.valueText(link.value),\n            share(link.value, link.source.value),\n          ],\n        })),\n        footer: [],\n      },\n      tooltip: (stop) => {\n        const node = nodeByKey.get(stop.key)\n        if (node) {\n          // Where it goes, or for a last step, where it came from: the biggest first, a few.\n          const out = node.sourceLinks.length > 0\n          const flows = (out ? node.sourceLinks : node.targetLinks)\n            .toSorted((a, b) => b.value - a.value)\n            .slice(0, TOOLTIP_FLOWS)\n          return (\n            <ShareTooltipContent\n              chart={chart}\n              category={flowItem(stop)}\n              name={nameOf(node.key)}\n              rows={[\n                {\n                  label,\n                  value: chart.valueText(node.value),\n                  share: share(node.value, total),\n                },\n                ...flows.map((link) => ({\n                  label: `${out ? chart.messages.to : chart.messages.from} ${nameOf(out ? link.target.key : link.source.key)}`,\n                  value: chart.valueText(link.value),\n                  share: share(link.value, node.value),\n                })),\n              ]}\n              swatch={<Swatch color={colorOf(node.key)} />}\n            />\n          )\n        }\n        const link = linkByKey.get(stop.key)\n        if (!link) return null\n        return (\n          <ShareTooltipContent\n            chart={chart}\n            category={flowItem(stop)}\n            name={flowName(link.key)}\n            rows={[\n              {\n                label: null,\n                value: chart.valueText(link.value),\n                share: share(link.value, link.source.value),\n              },\n            ]}\n            swatch={\n              <Swatch\n                color={colorOf(\n                  linkColor === 'target' ? link.target.key : link.source.key,\n                )}\n              />\n            }\n          />\n        )\n      },\n    },\n  })\n  const root: ChartRootValue = {\n    ...state,\n    status,\n    reader,\n    markerOf: () => null,\n    selectable: pick.selectable,\n    picked: pick.picked === null ? null : { kind: 'node', id: pick.picked },\n    togglePicked: (target) => {\n      if (target.kind === 'node' && reader.holds(target)) pick.toggle(target.id)\n    },\n  }\n  const { focusProps, toldRef } = useIndexFocus(reader.items, props)\n\n  return (\n    <ChartFrame\n      root={root}\n      focus={focusProps}\n      ref={ref}\n      slot='sankey-chart'\n      description={description}\n      empty={empty}\n      measuring={false}\n      inset={0}\n      data-orientation='vertical'\n      className={className}\n      {...figureProps(props, sankeyChartKeys)}\n    >\n      <IndexActive items={reader.items} active={props} toldRef={toldRef}>\n        <SankeyMarks\n          graph={graph}\n          layout={steady}\n          was={was}\n          phase={phase}\n          marks={marks}\n          items={items}\n          linkColor={linkColor}\n          colorOf={colorOf}\n          labelOf={labelOf}\n        />\n        {props.children}\n        {load.placeholder && <SankeyPlaceholder />}\n      </IndexActive>\n    </ChartFrame>\n  )\n}\n\nfunction flowKeyOf(stop: FlowStop) {\n  return stop.key\n}\n\n/** How many of a node's flows its tooltip lists. */\nconst TOOLTIP_FLOWS = 4\n\nfunction nameText(name: unknown) {\n  return String(name)\n}\n\n/** What tells one layout from another: every box and band, to a hundredth of a px. */\nfunction layoutSignature(layout: FlowLayout) {\n  return flowShapes(layout)\n    .map((shape) =>\n      [\n        shape.key,\n        shape.x0,\n        shape.x1,\n        shape.y0,\n        shape.y1,\n        shape.kind === 'link' ? shape.width : '',\n      ]\n        .map((part) => (typeof part === 'number' ? part.toFixed(2) : part))\n        .join(':'),\n    )\n    .join('|')\n}\n\n/**\n * A node's colour: its own from the config's `color` or `theme`, or the chart's colours spread\n * along the columns, lightest first, so the flows deepen as they go.\n */\nfunction nodeColor(config: ChartConfig, key: string, layer: number, columns: number) {\n  const slot =\n    columns <= 1 ? 0 : columns <= 5 ? Math.round((layer * 4) / (columns - 1)) : layer % 5\n  const ramp = `var(--chart-${slot + 1})`\n  // Only a colour of its own: a node the config names for its label keeps its column's.\n  const own = config[key]\n  return own?.color || own?.theme ? `var(--color-${key}, ${ramp})` : ramp\n}\n\nfunction Swatch({ color }: { color: string }) {\n  return (\n    <span\n      aria-hidden\n      className={cn(swatchClassName, 'forced-colors:bg-[CanvasText]')}\n      style={{ '--swatch': color } as CSSProperties}\n    />\n  )\n}\n\n/** Which side of its node a label stands, physically: outside the outer columns where they have room, else after the node. */\nfunction labelSide(\n  layer: number,\n  columns: number,\n  direction: 'ltr' | 'rtl',\n  room: { start: number; end: number },\n): 'left' | 'right' {\n  // Before its node, at the reading start's side: the first column's, in its room, and the\n  // last column's when it has none, so it stays inside the plot.\n  const before =\n    (layer === 0 && room.start > 0) ||\n    (layer === columns - 1 && columns > 1 && room.end === 0)\n  if (direction === 'rtl') return before ? 'right' : 'left'\n  return before ? 'left' : 'right'\n}\n\n/** What a node writes beside itself, and on which side. */\ninterface NodeLabel {\n  side: 'left' | 'right'\n  name: string\n  value: string | null\n}\n\n/**\n * Every node, flow and label, drawn in one SVG as large as the plot. Their\n * shapes are written each frame of the chart's move while new data moves\n * them; at rest they are the layout's. What steps back is everything off the\n * way through the node or flow lit, or the node brought forward.\n */\nfunction SankeyMarks({\n  graph,\n  layout,\n  was,\n  phase,\n  marks,\n  items,\n  linkColor,\n  colorOf,\n  labelOf,\n}: {\n  graph: FlowGraph\n  layout: FlowLayout\n  was: FlowLayout | null\n  phase: EntrancePhase\n  /** Every node and flow to draw, the leaving ones too. */\n  marks: readonly (FlowStop & { leaving: boolean })[]\n  /** The nodes and flows still drawn, in the order `activeIndex` counts. */\n  items: readonly FlowStop[]\n  linkColor: 'gradient' | 'source' | 'target'\n  colorOf: (key: string) => string\n  labelOf: (key: string) => NodeLabel | null\n}) {\n  const chart = useChartRootValue()\n  const { spotlit } = useChartActive()\n  const svg = useRef<SVGSVGElement>(null)\n  const size = drawingSize(chart.plotSize)\n  const shapes = useMemo(() => flowShapes(layout), [layout])\n  // Each mark's shape, the leaving layout's first, so a mark the pointer doesn't change keeps its\n  // props and its memo holds.\n  const byKey = useMemo(\n    () =>\n      new Map(\n        [...(was ? flowShapes(was) : []), ...shapes].map((shape) => [shape.key, shape]),\n      ),\n    [was, shapes],\n  )\n  const shown = useMemo(() => new Set(shapes.map((shape) => shape.key)), [shapes])\n  usePointsMove(\n    'layout',\n    shapes,\n    layoutSignature(layout),\n    shapes,\n    `${size.width}x${size.height}`,\n    {\n      align: flowMoves,\n      at: flowShapesAt,\n      draw: (now) => drawShapes(svg.current, now),\n    },\n  )\n  // The layout follows the plot's shape, so until it is measured there is nothing to draw:\n  // a guess would rearrange itself once the page is running.\n  if (chart.status === 'empty' || !isMeasured(chart.plotSize)) return null\n\n  const litKey = spotlit === null ? null : (items[spotlit]?.key ?? null)\n  const way =\n    litKey !== null\n      ? flowPath(\n          graph,\n          layout.nodes.some((node) => node.key === litKey)\n            ? { node: litKey }\n            : { link: litKey },\n        )\n      : chart.emphasis !== null\n        ? flowPath(graph, { node: chart.emphasis })\n        : null\n  const id = chart.id\n\n  const linkMarks = marks.filter((mark) => byKey.get(mark.key)?.kind === 'link')\n  const nodeMarks = marks.filter((mark) => byKey.get(mark.key)?.kind === 'node')\n\n  return (\n    <div\n      data-slot='sankey-chart-flows'\n      aria-hidden\n      className='pointer-events-none relative z-10 min-h-0 min-w-0 [grid-area:plot]'\n    >\n      <svg\n        ref={svg}\n        data-entering={phase === 'entering' ? '' : undefined}\n        data-waiting={phase === 'waiting' ? '' : undefined}\n        width={size.width}\n        height={size.height}\n        className='absolute inset-0 size-full overflow-visible'\n      >\n        {linkMarks.map((mark) => {\n          const shape = byKey.get(mark.key)\n          if (shape?.kind !== 'link') return null\n          const color = (key: string) => colorOf(key)\n          return (\n            <SankeyLink\n              key={mark.key}\n              id={`${id}-flow-${mark.index}`}\n              flowKey={mark.key}\n              shape={shape}\n              from={color(shape.source)}\n              to={color(shape.target)}\n              mode={linkColor}\n              dim={way !== null && !way.links.has(mark.key)}\n              leaving={mark.leaving || !shown.has(mark.key)}\n            />\n          )\n        })}\n        {nodeMarks.map((mark) => {\n          const shape = byKey.get(mark.key)\n          if (shape?.kind !== 'node') return null\n          return (\n            <SankeyNode\n              key={mark.key}\n              flowKey={mark.key}\n              shape={shape}\n              color={colorOf(mark.key)}\n              dim={way !== null && !way.nodes.has(mark.key)}\n              leaving={mark.leaving || !shown.has(mark.key)}\n              side={labelOf(mark.key)?.side ?? null}\n              name={labelOf(mark.key)?.name ?? null}\n              value={labelOf(mark.key)?.value ?? null}\n            />\n          )\n        })}\n      </svg>\n    </div>\n  )\n}\n\n/** Writes each shape where it is now onto its element, found by its key. */\nfunction drawShapes(svg: SVGSVGElement | null, shapes: readonly FlowShape[]) {\n  if (!svg) return\n  const byKey = new Map(shapes.map((shape) => [shape.key, shape]))\n  for (const element of svg.querySelectorAll<SVGElement>('[data-flow]')) {\n    const shape = byKey.get(element.dataset.flow ?? '')\n    if (!shape) continue\n    if (shape.kind === 'node') placeNode(element, shape)\n    else placeLink(element, shape)\n  }\n}\n\nfunction placeNode(element: SVGElement, node: LaidNode) {\n  const [rect, label] = [element.querySelector('rect'), element.querySelector('g')]\n  rect?.setAttribute('x', String(node.x0))\n  rect?.setAttribute('y', String(node.y0))\n  rect?.setAttribute('width', String(Math.max(0, node.x1 - node.x0)))\n  rect?.setAttribute('height', String(Math.max(1, node.y1 - node.y0)))\n  label?.setAttribute(\n    'transform',\n    labelTransform(node, label.dataset.side === 'left' ? 'left' : 'right'),\n  )\n}\n\nfunction placeLink(element: SVGElement, link: Extract<FlowShape, { kind: 'link' }>) {\n  const path = element.querySelector('path')\n  path?.setAttribute('d', linkPath(link))\n  path?.setAttribute('stroke-width', String(Math.max(1, link.width)))\n  const gradient = element.querySelector('linearGradient')\n  gradient?.setAttribute('x1', String(link.x0))\n  gradient?.setAttribute('x2', String(link.x1))\n}\n\nfunction labelTransform(node: LaidNode, side: 'left' | 'right') {\n  const x = side === 'left' ? node.x0 - LABEL_GAP : node.x1 + LABEL_GAP\n  return `translate(${Math.round(x * 100) / 100} ${Math.round(((node.y0 + node.y1) / 2) * 100) / 100})`\n}\n\nconst fadeClassName =\n  'transition-none duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing) group-data-mounted/chart:transition-[stroke,fill,stop-color,opacity]'\n\n/**\n * One flow: its band, stroked as thick as it, in its colour or a gradient\n * from its source's to its target's, stepping back while another way is\n * lit. Memoised, so a pointer moving between marks redraws only the ones\n * it lights or dims.\n */\nconst SankeyLink = memo(function SankeyLink({\n  id,\n  flowKey,\n  shape,\n  from,\n  to,\n  mode,\n  dim,\n  leaving,\n}: {\n  id: string\n  flowKey: string\n  shape: Extract<FlowShape, { kind: 'link' }>\n  from: string\n  to: string\n  mode: 'gradient' | 'source' | 'target'\n  dim: boolean\n  leaving: boolean\n}) {\n  const stopClassName = cn(\n    fadeClassName,\n    '[stop-color:var(--mark-ink)] forced-colors:[stop-color:GrayText]',\n    stepBackInkClassName,\n  )\n  return (\n    <g\n      data-flow={flowKey}\n      data-dim={dim ? '' : undefined}\n      data-leaving={leaving ? '' : undefined}\n      className={stepBackInkClassName}\n    >\n      {mode === 'gradient' && (\n        <linearGradient\n          id={id}\n          gradientUnits='userSpaceOnUse'\n          x1={shape.x0}\n          x2={shape.x1}\n          y1={0}\n          y2={0}\n        >\n          <stop\n            offset='0%'\n            className={stopClassName}\n            style={{ '--mark-color': from } as CSSProperties}\n          />\n          <stop\n            offset='100%'\n            className={stopClassName}\n            style={{ '--mark-color': to } as CSSProperties}\n          />\n        </linearGradient>\n      )}\n      <path\n        d={linkPath(shape)}\n        pathLength={1}\n        strokeWidth={Math.max(1, shape.width)}\n        className={cn(\n          'fill-none [stroke-opacity:var(--sankey-chart-flow-opacity,0.4)] [stroke-dasharray:1] [stroke-dashoffset:0]',\n          mode === 'gradient'\n            ? '[stroke:var(--flow-paint)]'\n            : cn('[stroke:var(--mark-ink)]', stepBackInkClassName),\n          'transition-none group-data-mounted/chart:[transition:stroke_var(--motion-layout-duration)_var(--motion-layout-fade-easing),stroke-dashoffset_var(--motion-draw-duration)_var(--motion-draw-easing),opacity_var(--motion-exit-duration)_var(--motion-exit-fade-easing)] group-data-mounted/chart:starting:[stroke-dashoffset:1] in-data-waiting:[stroke-dashoffset:1] in-data-leaving:opacity-0 motion-reduce:group-data-mounted/chart:[transition:stroke_var(--motion-layout-duration)_var(--motion-layout-fade-easing),opacity_var(--motion-exit-duration)_var(--motion-exit-fade-easing)] motion-reduce:group-data-mounted/chart:starting:opacity-0 motion-reduce:in-data-waiting:opacity-0 motion-reduce:[stroke-dashoffset:0]! forced-colors:[stroke:GrayText] forced-colors:in-data-dim:[stroke-opacity:0.15]',\n        )}\n        style={\n          {\n            '--mark-color': mode === 'target' ? to : from,\n            '--flow-paint': `url(#${id})`,\n          } as CSSProperties\n        }\n      />\n    </g>\n  )\n})\n\n/**\n * One node, and its label beside it: its name, and under it its value,\n * where they fit.\n */\nconst SankeyNode = memo(function SankeyNode({\n  flowKey,\n  shape,\n  color,\n  dim,\n  leaving,\n  side: givenSide,\n  name: givenName,\n  value: givenValue,\n}: {\n  flowKey: string\n  shape: Extract<FlowShape, { kind: 'node' }>\n  color: string\n  dim: boolean\n  leaving: boolean\n  side: 'left' | 'right' | null\n  name: string | null\n  value: string | null\n}) {\n  // A node on its way out keeps the words it had while it fades.\n  const given =\n    givenSide === null || givenName === null\n      ? null\n      : { side: givenSide, name: givenName, value: givenValue }\n  const [held, setHeld] = useState(given)\n  if (!leaving && !sameLabel(given, held)) setHeld(given)\n  const label = leaving ? held : given\n  const side = label?.side ?? 'right'\n  const name = label?.name ?? null\n  const value = label?.value ?? null\n  const two = name !== null && value !== null\n  // The label's own edge faces its node, whatever the page's direction.\n  const anchor = side === 'left' ? 'end' : 'start'\n  return (\n    <g\n      data-flow={flowKey}\n      data-dim={dim ? '' : undefined}\n      data-leaving={leaving ? '' : undefined}\n      className={cn(\n        fadeClassName,\n        stepBackInkClassName,\n        'opacity-100 group-data-mounted/chart:starting:opacity-0 in-data-waiting:opacity-0 data-leaving:opacity-0 data-leaving:duration-(--motion-exit-duration) data-leaving:ease-(--motion-exit-fade-easing) in-data-entering:duration-(--motion-draw-duration)',\n      )}\n    >\n      <rect\n        x={shape.x0}\n        y={shape.y0}\n        width={Math.max(0, shape.x1 - shape.x0)}\n        height={Math.max(1, shape.y1 - shape.y0)}\n        rx={1.5}\n        className={cn(\n          fadeClassName,\n          '[fill:var(--mark-ink)] forced-colors:[fill:CanvasText] forced-colors:in-data-dim:[fill:GrayText]',\n          stepBackInkClassName,\n        )}\n        style={{ '--mark-color': color } as CSSProperties}\n      />\n      {name !== null && (\n        <g\n          data-side={side}\n          transform={labelTransform(shape, side)}\n          textAnchor={anchor}\n          className='[direction:ltr]'\n        >\n          <text\n            y={two ? -LABEL_LINE / 2 : 0}\n            dominantBaseline='central'\n            // Labels never step back, and a halo in the surface's colour keeps them clear of the flows.\n            className='fill-foreground font-medium forced-colors:fill-[CanvasText] stroke-(--chart-surface,var(--card)) [stroke-width:3] [stroke-linejoin:round] [paint-order:stroke] forced-colors:stroke-[Canvas]'\n          >\n            {name}\n          </text>\n          {value !== null && (\n            <text\n              y={LABEL_LINE / 2}\n              dominantBaseline='central'\n              className='fill-foreground tabular-nums forced-colors:fill-[CanvasText] stroke-(--chart-surface,var(--card)) [stroke-width:3] [stroke-linejoin:round] [paint-order:stroke] forced-colors:stroke-[Canvas]'\n            >\n              {value}\n            </text>\n          )}\n        </g>\n      )}\n    </g>\n  )\n})\n\nfunction sameLabel(a: NodeLabel | null, b: NodeLabel | null) {\n  return a?.side === b?.side && a?.name === b?.name && a?.value === b?.value\n}\n\n/** The shape the placeholder takes: a few steps narrowing, as most flows do. */\nconst PLACEHOLDER = flowGraph(\n  [\n    { from: 'a', to: 'd', value: 30 },\n    { from: 'b', to: 'd', value: 20 },\n    { from: 'b', to: 'e', value: 14 },\n    { from: 'c', to: 'e', value: 12 },\n    { from: 'd', to: 'f', value: 34 },\n    { from: 'd', to: 'g', value: 16 },\n    { from: 'e', to: 'g', value: 18 },\n  ],\n  { source: 'from', target: 'to', dataKey: 'value' },\n)\n\n/** The flows in the placeholder's tint, breathing slowly, while the data loads. */\nfunction SankeyPlaceholder() {\n  const chart = useChartRootValue()\n  if (!isMeasured(chart.plotSize)) return null\n  const size = drawingSize(chart.plotSize)\n  const layout = flowLayout(PLACEHOLDER, {\n    width: size.width,\n    height: size.height,\n    nodeWidth: NODE_WIDTH,\n    nodePadding: NODE_PADDING,\n    sort: 'data',\n    direction: chart.direction,\n  })\n  return (\n    <div\n      data-slot='sankey-chart-placeholder'\n      aria-hidden\n      className={cn(\n        'pointer-events-none relative z-10 min-h-0 min-w-0 [grid-area:plot]',\n        placeholderBreatheClassName,\n      )}\n    >\n      <svg\n        width={size.width}\n        height={size.height}\n        className={cn('absolute inset-0 size-full', placeholderInkClassName)}\n      >\n        {layout.links.map((link) => (\n          <path\n            key={link.key}\n            d={linkPath(link)}\n            strokeWidth={Math.max(1, link.width)}\n            className='fill-none stroke-current [stroke-opacity:0.6]'\n          />\n        ))}\n        {layout.nodes.map((node) => (\n          <rect\n            key={node.key}\n            x={node.x0}\n            y={node.y0}\n            width={node.x1 - node.x0}\n            height={Math.max(1, node.y1 - node.y0)}\n            rx={1.5}\n            className='fill-current'\n          />\n        ))}\n      </svg>\n    </div>\n  )\n}\n\nexport { labelSide, nodeColor, SankeyChart, type SankeyChartProps }\n",
      "type": "registry:component",
      "target": "@components/kino/sankey-chart.tsx"
    }
  ],
  "type": "registry:component"
}