{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sankey-chart",
  "type": "registry:component",
  "title": "Sankey Chart",
  "description": "Flows between stages as bands whose widths are the amounts: where a total comes from, where it goes and what is lost on the way, with every node and band reachable by arrow keys.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-sankey"
  ],
  "devDependencies": [
    "@types/d3-sankey"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/sankey-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/sankey-chart.tsx",
      "content": "\"use client\";\n/**\n * @name sankey-chart\n * @category viz\n * @description Flows between stages as bands whose widths are the amounts: where a total comes from, where it goes and what is lost on the way, with every node and band reachable by arrow keys.\n * @when Showing how amounts move through steps or between categories: a budget from sources to uses, visitors through a sign-up, energy from fuel to use. For a single funnel of shrinking steps use funnel-chart; for links without amounts use network-graph; for two-way flows between the same groups use chord-diagram.\n * @example\n * <SankeyChart\n *   label=\"Where the money goes\"\n *   nodes={[{ id: \"income\", label: \"Income\" }, { id: \"rent\", label: \"Rent\" }, { id: \"food\", label: \"Food\" }, { id: \"saved\", label: \"Saved\" }]}\n *   links={[\n *     { source: \"income\", target: \"rent\", value: 1200 },\n *     { source: \"income\", target: \"food\", value: 500 },\n *     { source: \"income\", target: \"saved\", value: 300 },\n *   ]}\n * />\n */\nimport { sankey, sankeyJustify, sankeyLinkHorizontal, type SankeyLink, type SankeyNode } from \"d3-sankey\";\nimport { useMemo } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { ChartContainer, ChartEmpty, chartSeries, ChartSvg, ChartTooltip, fitText, formatNumber, useChartCursor, widestText, type ChartBaseProps } from \"@/components/viz/chart\";\n\nexport type SankeyChartNode = {\n  id: string;\n  /** Its name. Default: the id. */\n  label?: string;\n  /** A group name: nodes of a group share a colour, in order of first appearance. Default: all one colour. */\n  group?: string;\n};\n\nexport type SankeyChartLink = { source: string; target: string; value: number };\n\nexport type SankeyChartLabels = { source: string; target: string; value: string; incoming: string; outgoing: string };\n\nexport type SankeyChartProps = ChartBaseProps & {\n  nodes: readonly SankeyChartNode[];\n  /** Amounts from one node to another. The graph must not loop back on itself. */\n  links: readonly SankeyChartLink[];\n  /** Words for the table and the tooltip. */\n  labels?: Partial<SankeyChartLabels>;\n  /** The width of a node bar in pixels. Default 12. */\n  nodeWidth?: number;\n};\n\nconst LABELS: SankeyChartLabels = { source: \"From\", target: \"To\", value: \"Amount\", incoming: \"In\", outgoing: \"Out\" };\n\ntype N = { id: string; name: string; colour: number };\ntype L = { value: number };\ntype LaidNode = SankeyNode<N, L>;\ntype LaidLink = SankeyLink<N, L>;\n\nexport function SankeyChart({ nodes, links, labels: given, nodeWidth = 12, label, aspect, height, emptyLabel, locale, formatValue, className, ...props }: SankeyChartProps) {\n  const labels = { ...LABELS, ...given };\n  const number = formatValue ?? ((value: number) => formatNumber(value, locale));\n  const known = useMemo(() => {\n    const groups = [...new Set(nodes.map((node) => node.group ?? \"\"))];\n    const graphNodes: N[] = nodes.map((node) => {\n      const index = groups.indexOf(node.group ?? \"\");\n      return { id: node.id, name: node.label ?? node.id, colour: index < 5 ? index : -1 };\n    });\n    const ids = new Set(graphNodes.map((node) => node.id));\n    const graphLinks = links.filter((link) => ids.has(link.source) && ids.has(link.target) && link.value > 0 && link.source !== link.target);\n    return { graphNodes, graphLinks };\n  }, [nodes, links]);\n  const count = known.graphNodes.length + known.graphLinks.length;\n  const cursor = useChartCursor(count);\n  const nameOf = (id: string): string => known.graphNodes.find((node) => node.id === id)?.name ?? id;\n  const totals = (id: string): { incoming: number; outgoing: number } => ({\n    incoming: known.graphLinks.filter((link) => link.target === id).reduce((sum, link) => sum + link.value, 0),\n    outgoing: known.graphLinks.filter((link) => link.source === id).reduce((sum, link) => sum + link.value, 0),\n  });\n  const describeAt = (index: number): { title: string; rows: { label: string; value: string }[] } => {\n    const node = known.graphNodes[index];\n    if (node) {\n      const t = totals(node.id);\n      return {\n        title: node.name,\n        rows: [...(t.incoming > 0 ? [{ label: labels.incoming, value: number(t.incoming) }] : []), ...(t.outgoing > 0 ? [{ label: labels.outgoing, value: number(t.outgoing) }] : [])],\n      };\n    }\n    const link = known.graphLinks[index - known.graphNodes.length];\n    return link ? { title: `${nameOf(link.source)} → ${nameOf(link.target)}`, rows: [{ label: labels.value, value: number(link.value) }] } : { title: \"\", rows: [] };\n  };\n  const reading = cursor.active === null ? undefined : describeAt(cursor.active);\n  const table = { caption: label, columns: [labels.source, labels.target, labels.value], rows: known.graphLinks.map((link) => [nameOf(link.source), nameOf(link.target), number(link.value)]) };\n\n  return (\n    <div data-slot=\"sankey-chart\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      <ChartContainer\n        aspect={aspect}\n        height={height}\n        table={table}\n        announcement={cursor.keyboard && reading ? `${reading.title}: ${reading.rows.map((row) => `${row.label} ${row.value}`).join(\", \")}` : \"\"}\n      >\n        {({ width, height: plotHeight }) => {\n          if (known.graphLinks.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const room = Math.min(width * 0.28, widestText(known.graphNodes.map((node) => node.name)) + 10);\n          let laid: { nodes: LaidNode[]; links: LaidLink[] };\n          try {\n            laid = sankey<N, L>()\n              .nodeId((node) => node.id)\n              .nodeAlign(sankeyJustify)\n              .nodeWidth(nodeWidth)\n              .nodePadding(Math.max(8, Math.min(20, plotHeight / (known.graphNodes.length * 2))))\n              .extent([\n                [room, 6],\n                [width - room, plotHeight - 6],\n              ])({ nodes: known.graphNodes.map((node) => ({ ...node })), links: known.graphLinks.map((link) => ({ ...link })) });\n          } catch {\n            // A loop in the links cannot be laid out left to right.\n            return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          }\n          const path = sankeyLinkHorizontal<N, L>();\n          const activeNode = cursor.active !== null && cursor.active < laid.nodes.length ? laid.nodes[cursor.active] : undefined;\n          const activeLink = cursor.active !== null && cursor.active >= laid.nodes.length ? laid.links[cursor.active - laid.nodes.length] : undefined;\n          const lit = (link: LaidLink): boolean => link === activeLink || (activeNode !== undefined && (link.source === activeNode || link.target === activeNode));\n          const anchor = activeNode\n            ? { x: activeNode.x1 ?? 0, y: ((activeNode.y0 ?? 0) + (activeNode.y1 ?? 0)) / 2 }\n            : activeLink\n              ? { x: (((activeLink.source as LaidNode).x1 ?? 0) + ((activeLink.target as LaidNode).x0 ?? 0)) / 2, y: ((activeLink.y0 ?? 0) + (activeLink.y1 ?? 0)) / 2 }\n              : undefined;\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps}>\n                <g aria-hidden=\"true\" fill=\"none\">\n                  {laid.links.map((link, index) => {\n                    const source = link.source as LaidNode;\n                    return (\n                      <path\n                        key={index}\n                        d={path(link) ?? \"\"}\n                        className={cn(chartSeries(source.colour).stroke, \"transition-opacity duration-instant motion-reduce:transition-none\")}\n                        strokeOpacity={cursor.active === null ? 0.32 : lit(link) ? 0.6 : 0.12}\n                        strokeWidth={Math.max(1, link.width ?? 1)}\n                        onPointerEnter={() => cursor.point(laid.nodes.length + index)}\n                      />\n                    );\n                  })}\n                </g>\n                <g aria-hidden=\"true\">\n                  {laid.nodes.map((node, index) => {\n                    const x0 = node.x0 ?? 0;\n                    const x1 = node.x1 ?? 0;\n                    const y0 = node.y0 ?? 0;\n                    const y1 = node.y1 ?? 0;\n                    const onLeft = x0 < width / 2;\n                    return (\n                      <g key={node.id} onPointerEnter={() => cursor.point(index)}>\n                        <rect x={x0} y={y0} width={x1 - x0} height={Math.max(1, y1 - y0)} className={cn(chartSeries(node.colour).fill, \"[rx:min(var(--radius),2px)]\")} />\n                        <text\n                          x={onLeft ? x0 - 6 : x1 + 6}\n                          y={(y0 + y1) / 2}\n                          dy=\"0.32em\"\n                          textAnchor={onLeft ? \"end\" : \"start\"}\n                          className={cn(\"text-xs\", activeNode === node ? \"fill-foreground font-medium\" : \"fill-muted-foreground\")}\n                        >\n                          {fitText(node.name, room - 8)}\n                        </text>\n                      </g>\n                    );\n                  })}\n                  {activeNode ? (\n                    <rect\n                      x={(activeNode.x0 ?? 0) - 2}\n                      y={(activeNode.y0 ?? 0) - 2}\n                      width={(activeNode.x1 ?? 0) - (activeNode.x0 ?? 0) + 4}\n                      height={(activeNode.y1 ?? 0) - (activeNode.y0 ?? 0) + 4}\n                      fill=\"none\"\n                      className=\"pointer-events-none stroke-foreground\"\n                      strokeWidth={2}\n                    />\n                  ) : null}\n                </g>\n              </ChartSvg>\n              {anchor && reading ? <ChartTooltip x={anchor.x} y={anchor.y} side={anchor.x > width / 2 ? \"left\" : \"right\"} title={reading.title} rows={reading.rows} /> : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Showing how amounts move through steps or between categories: a budget from sources to uses, visitors through a sign-up, energy from fuel to use. For a single funnel of shrinking steps use funnel-chart; for links without amounts use network-graph; for two-way flows between the same groups use chord-diagram.",
    "example": "<SankeyChart\n  label=\"Where the money goes\"\n  nodes={[{ id: \"income\", label: \"Income\" }, { id: \"rent\", label: \"Rent\" }, { id: \"food\", label: \"Food\" }, { id: \"saved\", label: \"Saved\" }]}\n  links={[\n    { source: \"income\", target: \"rent\", value: 1200 },\n    { source: \"income\", target: \"food\", value: 500 },\n    { source: \"income\", target: \"saved\", value: 300 },\n  ]}\n/>",
    "client": true
  }
}
