Installation
Run this in a project set up with shadcn/ui:
$ pnpm dlx shadcn@latest add https://uxelith.com/r/sankey-chart.jsonIt adds these packages for you:
clsxtailwind-mergeThe source lands in your components folder as
sankey-chart.tsx. It's yours: change anything.
Usage
import { SankeyChart } from "@/components/sankey-chart"
export function Funnel() {
return (
<SankeyChart
title="Where visitors went"
links={[
{ source: "Search", target: "Docs", value: 420 },
{ source: "Search", target: "Pricing", value: 120 },
{ source: "Social", target: "Pricing", value: 60 },
{ source: "Docs", target: "Signed up", value: 190 },
{ source: "Docs", target: "Left", value: 230 },
{ source: "Pricing", target: "Signed up", value: 180 },
]}
/>
)
}Source
One file, 441 lines, nothing hidden. Read it before you install it.
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
export interface SankeyNode {
id: string;
/** Shown beside the node. Defaults to `id`. */
label?: string;
/** Any CSS colour. Defaults to --chart-1…5 in turn. */
color?: string;
}
export interface SankeyLink {
/** A node `id`. Nodes you don't list in `nodes` are created for you. */
source: string;
target: string;
value: number;
}
export interface SankeyChartProps extends Omit<React.ComponentProps<"figure">, "children"> {
links: SankeyLink[];
/** Optional labels and colours for the nodes in `links`. */
nodes?: SankeyNode[];
/** Names the chart; also the caption of the accessible data table. */
title: string;
/** Show the title above the chart. */
showTitle?: boolean;
/** Formats values on labels, tooltip and table. Overrides `formatOptions`. */
format?: (value: number) => string;
/** Number format without writing a function, e.g. `{ style: "currency", currency: "USD" }`. */
formatOptions?: Intl.NumberFormatOptions;
/** BCP 47 locale for `formatOptions`. Defaults to the visitor's. */
locale?: string;
/** Chart height in pixels. */
height?: number;
/** Space between nodes in a column, in pixels. */
nodeGap?: number;
}
export interface LaidOutNode {
id: string;
label: string;
color: string;
column: number;
x: number;
y: number;
height: number;
value: number;
}
export interface LaidOutLink extends SankeyLink {
/** The source and target as they ended up (a link that closes a loop is dropped). */
path: string;
width: number;
x0: number;
x1: number;
}
const NODE_WIDTH = 12;
const palette = ["var(--chart-1, var(--primary))", "var(--chart-2, var(--muted-foreground))", "var(--chart-3, var(--primary))", "var(--chart-4, var(--muted-foreground))", "var(--chart-5, var(--primary))"];
/** Drops links that would close a loop: a Sankey reads left to right, so a cycle has no place to go. */
function withoutCycles(links: SankeyLink[]) {
const kept: SankeyLink[] = [];
const reaches = (from: string, to: string, seen = new Set<string>()): boolean => {
if (from === to) return true;
seen.add(from);
return kept.some((l) => l.source === from && !seen.has(l.target) && reaches(l.target, to, seen));
};
for (const link of links) if (link.value > 0 && !reaches(link.target, link.source)) kept.push(link);
return kept;
}
/** Places nodes in columns and turns links into ribbons. Pure, so it can be tested and reused. */
export function sankeyLayout(links: SankeyLink[], nodes: SankeyNode[], width: number, height: number, { gap = 18, inset = 0 } = {}) {
const clean = withoutCycles(links);
const ids = [...new Set(clean.flatMap((l) => [l.source, l.target]))];
const info = new Map(nodes.map((n) => [n.id, n]));
// A node sits one column past its furthest source; ends line up on the right.
const column = new Map(ids.map((id) => [id, 0]));
for (let pass = 0; pass < ids.length; pass++) {
for (const l of clean) column.set(l.target, Math.max(column.get(l.target)!, column.get(l.source)! + 1));
}
const last = Math.max(0, ...column.values());
for (const id of ids) if (!clean.some((l) => l.source === id)) column.set(id, last);
const sum = (id: string, side: "source" | "target") => clean.filter((l) => l[side] === id).reduce((s, l) => s + l.value, 0);
const value = new Map(ids.map((id) => [id, Math.max(sum(id, "source"), sum(id, "target"))]));
const columns = Array.from({ length: last + 1 }, (_, c) => ids.filter((id) => column.get(id) === c));
const scale = Math.min(...columns.map((c) => (height - gap * Math.max(c.length - 1, 0)) / (c.reduce((s, id) => s + value.get(id)!, 0) || 1)));
// Sweep both ways, pulling each node towards its neighbours, so ribbons cross less.
const rank = new Map<string, number>();
const place = () => columns.forEach((c) => c.forEach((id, i) => rank.set(id, i / Math.max(c.length - 1, 1))));
place();
for (let sweep = 0; sweep < 6; sweep++) {
const order = sweep % 2 ? [...columns].reverse() : columns;
for (const c of order) {
const weight = (id: string) => {
const near = clean.filter((l) => (sweep % 2 ? l.source === id : l.target === id));
const total = near.reduce((s, l) => s + l.value, 0);
return total ? near.reduce((s, l) => s + l.value * rank.get(sweep % 2 ? l.target : l.source)!, 0) / total : rank.get(id)!;
};
const weights = new Map(c.map((id) => [id, weight(id)]));
c.sort((a, b) => weights.get(a)! - weights.get(b)!);
}
place();
}
const step = last ? (width - inset * 2 - NODE_WIDTH) / last : 0;
const placed = new Map<string, LaidOutNode>();
let colour = 0;
columns.forEach((c, i) => {
const used = c.reduce((s, id) => s + value.get(id)! * scale, 0) + gap * Math.max(c.length - 1, 0);
let y = (height - used) / 2;
for (const id of c) {
const h = value.get(id)! * scale;
placed.set(id, {
id,
label: info.get(id)?.label ?? id,
color: info.get(id)?.color ?? palette[colour++ % palette.length]!,
column: i,
x: inset + i * step,
y,
height: Math.max(h, 2),
value: value.get(id)!,
});
y += h + gap;
}
});
// Ribbons stack within a node in the order of the far end, so they leave without tangling.
const out = new Map<string, number>();
const into = new Map<string, number>();
const ordered = [...clean].sort((a, b) => placed.get(a.target)!.y - placed.get(b.target)!.y || placed.get(a.source)!.y - placed.get(b.source)!.y);
const inY = new Map<SankeyLink, number>();
for (const l of [...ordered].sort((a, b) => placed.get(a.source)!.y - placed.get(b.source)!.y || placed.get(a.target)!.y - placed.get(b.target)!.y)) {
const w = l.value * scale;
inY.set(l, placed.get(l.target)!.y + (into.get(l.target) ?? 0) + w / 2);
into.set(l.target, (into.get(l.target) ?? 0) + w);
}
const laidOut: LaidOutLink[] = ordered.map((l) => {
const a = placed.get(l.source)!;
const b = placed.get(l.target)!;
const w = l.value * scale;
const y0 = a.y + (out.get(l.source) ?? 0) + w / 2;
out.set(l.source, (out.get(l.source) ?? 0) + w);
const y1 = inY.get(l)!;
const x0 = a.x + NODE_WIDTH;
const x1 = b.x;
const mid = (x0 + x1) / 2;
return { ...l, path: `M${x0},${y0}C${mid},${y0} ${mid},${y1} ${x1},${y1}`, width: Math.max(w, 1), x0, x1 };
});
return { nodes: [...placed.values()], links: laidOut, columns: last + 1 };
}
// Labels sit over ribbons in the middle columns; an outline in the page colour keeps them readable.
const halo = (classes: string) => cn(classes, "stroke-[var(--card,var(--background))] [paint-order:stroke] [stroke-linejoin:round] [stroke-width:3]");
function usePrefersReducedMotion() {
return React.useSyncExternalStore(
(notify) => {
const query = window.matchMedia("(prefers-reduced-motion: reduce)");
query.addEventListener("change", notify);
return () => query.removeEventListener("change", notify);
},
() => window.matchMedia("(prefers-reduced-motion: reduce)").matches,
() => false,
);
}
/**
* Where something came from and where it went, drawn as ribbons in proportion
* to their size: traffic, money, energy, anything that flows.
*
* - Give it links; columns, order and sizes are worked out, and ribbons are
* arranged to cross as little as possible. A link that would close a loop
* is dropped, since a Sankey only reads one way.
* - Pointing at a node traces every path through it, and points of light run
* along those ribbons; everything else steps back.
* - Keyboard: Tab into the chart, then ↑/↓ within a column and ←/→ between
* columns; each node is announced with its total.
* - Screen readers also get every link in a real table.
* - Ribbons draw in once on first view; under reduced motion they are simply
* there and nothing runs along them.
* - Colours: `--chart-1`…`--chart-5`, or per node.
*/
export function SankeyChart({
links,
nodes = [],
title,
showTitle = true,
format: formatProp,
formatOptions,
locale,
height = 360,
nodeGap = 18,
className,
...props
}: SankeyChartProps) {
const id = React.useId();
const optionsKey = JSON.stringify(formatOptions ?? { notation: "compact", maximumFractionDigits: 1 });
const intlFormat = React.useMemo(
() => new Intl.NumberFormat(locale, JSON.parse(optionsKey) as Intl.NumberFormatOptions).format,
[locale, optionsKey],
);
const format = formatProp ?? intlFormat;
const wrapRef = React.useRef<HTMLDivElement>(null);
const reduceMotion = usePrefersReducedMotion();
const [width, setWidth] = React.useState(0);
const [shown, setShown] = React.useState(false);
const [active, setActive] = React.useState<{ node?: string; link?: number } | null>(null);
const [tip, setTip] = React.useState<{ x: number; y: number; text: string } | null>(null);
const [focusId, setFocusId] = React.useState<string | null>(null);
const pathRefs = React.useRef(new Map<number, SVGPathElement>());
const dotsRef = React.useRef<SVGGElement>(null);
const nodeRefs = React.useRef(new Map<string, SVGGElement>());
React.useEffect(() => {
const node = wrapRef.current;
if (!node) return;
const ro = new ResizeObserver(([entry]) => setWidth(entry!.contentRect.width));
ro.observe(node);
const io = new IntersectionObserver(([entry]) => entry?.isIntersecting && setShown(true), { threshold: 0.25 });
io.observe(node);
return () => {
ro.disconnect();
io.disconnect();
};
}, []);
const narrow = width < 520;
const labelled = new Map(nodes.map((n) => [n.id, n.label ?? n.id]));
const longest = Math.max(4, ...links.flatMap((l) => [l.source, l.target]).map((n) => (labelled.get(n) ?? n).length));
const inset = Math.min(longest * 6.6 + 10, width * 0.24);
const layout = React.useMemo(
() => sankeyLayout(links, nodes, Math.max(width, 1), height, { gap: narrow ? Math.min(nodeGap, 14) : nodeGap, inset }),
[links, nodes, width, height, nodeGap, inset, narrow],
);
// Everything upstream and downstream of what's pointed at.
const lit = React.useMemo(() => {
const on = new Set<number>();
if (!active) return on;
if (active.link !== undefined) return on.add(active.link);
const walk = (node: string, forward: boolean) =>
layout.links.forEach((l, i) => {
if ((forward ? l.source : l.target) === node && !on.has(i)) {
on.add(i);
walk(forward ? l.target : l.source, forward);
}
});
walk(active.node!, true);
walk(active.node!, false);
return on;
}, [active, layout]);
const litNodes = new Set([...lit].flatMap((i) => [layout.links[i]!.source, layout.links[i]!.target]));
if (active?.node) litNodes.add(active.node);
// Points of light along the lit ribbons, written straight to the DOM on each frame.
React.useEffect(() => {
const group = dotsRef.current;
if (!group || reduceMotion || lit.size === 0) return;
const dots = [...lit].flatMap((i) => {
const path = pathRefs.current.get(i);
if (!path || typeof path.getTotalLength !== "function") return [];
const length = path.getTotalLength();
const count = Math.min(6, Math.max(2, Math.round(length / 160)));
return Array.from({ length: count }, (_, k) => {
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("r", "2.4");
circle.setAttribute("fill", "white");
circle.setAttribute("fill-opacity", "0.9");
group.append(circle);
return { path, length, offset: k / count, circle };
});
});
const start = performance.now();
let frame = requestAnimationFrame(function tick(now) {
for (const d of dots) {
const at = d.path.getPointAtLength((((now - start) / 2400 + d.offset) % 1) * d.length);
d.circle.setAttribute("cx", String(at.x));
d.circle.setAttribute("cy", String(at.y));
}
frame = requestAnimationFrame(tick);
});
return () => {
cancelAnimationFrame(frame);
group.replaceChildren();
};
}, [lit, reduceMotion]);
const clear = () => {
setActive(null);
setTip(null);
};
const focusable = focusId ?? layout.nodes[0]?.id;
const nameOf = (nodeId: string) => layout.nodes.find((n) => n.id === nodeId)?.label ?? nodeId;
const onKeyDown = (event: React.KeyboardEvent) => {
const current = layout.nodes.find((n) => n.id === focusable);
if (!current) return;
const column = (c: number) => layout.nodes.filter((n) => n.column === c).sort((a, b) => a.y - b.y);
const own = column(current.column);
const at = own.findIndex((n) => n.id === current.id);
const across = (c: number) => {
const near = column(c);
return near.reduce((best, n) => (Math.abs(n.y - current.y) < Math.abs(best.y - current.y) ? n : best), near[0] ?? current);
};
const next: Record<string, LaidOutNode | undefined> = {
ArrowUp: own[at - 1],
ArrowDown: own[at + 1],
ArrowLeft: current.column > 0 ? across(current.column - 1) : undefined,
ArrowRight: current.column < layout.columns - 1 ? across(current.column + 1) : undefined,
};
if (!(event.key in next)) return;
event.preventDefault();
const target = next[event.key];
if (target) nodeRefs.current.get(target.id)?.focus();
};
const tipAt = (event: React.PointerEvent, text: string) => {
const box = wrapRef.current!.getBoundingClientRect();
setTip({ x: Math.min(Math.max(event.clientX - box.left, 80), box.width - 80), y: event.clientY - box.top, text });
};
return (
<figure aria-labelledby={`${id}-title`} className={cn("w-full", className)} {...props}>
<figcaption id={`${id}-title`} className={cn("mb-4", showTitle ? "text-sm font-medium" : "sr-only")}>
{title}
</figcaption>
<div ref={wrapRef} className="relative" style={{ height }} onPointerLeave={clear}>
{width > 0 && (
<svg width={width} height={height} className="block overflow-visible" role="group" aria-label={`${title}, chart`} onKeyDown={onKeyDown}>
<defs>
{layout.links.map((l, i) => (
<linearGradient key={i} id={`${id}-g${i}`} gradientUnits="userSpaceOnUse" x1={l.x0} x2={l.x1}>
<stop offset="0" stopColor={layout.nodes.find((n) => n.id === l.source)!.color} />
<stop offset="1" stopColor={layout.nodes.find((n) => n.id === l.target)!.color} />
</linearGradient>
))}
</defs>
<g fill="none">
{layout.links.map((l, i) => (
<path
key={`${l.source}-${l.target}`}
ref={(node) => {
if (node) pathRefs.current.set(i, node);
else pathRefs.current.delete(i);
}}
d={l.path}
pathLength={1}
stroke={`url(#${id}-g${i})`}
strokeWidth={l.width}
strokeOpacity={active && lit.has(i) ? 0.62 : 0.4}
strokeDasharray={1}
strokeDashoffset={shown || reduceMotion ? 0 : 1}
className={cn("cursor-pointer", active && !lit.has(i) && "opacity-[0.08]")}
style={{ transition: "opacity 180ms cubic-bezier(0.22,1,0.36,1), stroke-dashoffset 800ms cubic-bezier(0.22,1,0.36,1)" }}
onPointerEnter={() => setActive({ link: i })}
onPointerMove={(event) => tipAt(event, `${nameOf(l.source)} → ${nameOf(l.target)}: ${format(l.value)}`)}
/>
))}
</g>
<g ref={dotsRef} aria-hidden="true" className="pointer-events-none" />
{layout.nodes.map((n) => {
const first = n.column === 0;
const textX = first ? n.x - 8 : n.x + NODE_WIDTH + 8;
return (
<g
key={n.id}
ref={(node) => {
if (node) nodeRefs.current.set(n.id, node);
else nodeRefs.current.delete(n.id);
}}
role="img"
aria-label={`${n.label}: ${format(n.value)}`}
tabIndex={n.id === focusable ? 0 : -1}
onPointerEnter={() => {
setTip(null);
setActive({ node: n.id });
}}
onFocus={() => {
setFocusId(n.id);
setActive({ node: n.id });
}}
onBlur={clear}
className={cn("cursor-pointer outline-none transition-opacity duration-200 motion-reduce:transition-none [&:focus-visible_rect]:stroke-ring [&:focus-visible_rect]:[stroke-width:2]", active && !litNodes.has(n.id) && "opacity-25")}
>
<rect x={n.x} y={n.y} width={NODE_WIDTH} height={n.height} rx={3} fill={n.color} />
<text x={textX} y={n.y + n.height / 2} dy={n.height > 30 ? "-0.2em" : "0.32em"} textAnchor={first ? "end" : "start"} className={halo("fill-foreground text-xs font-medium")}>
{n.label}
</text>
{n.height > 30 && (
<text x={textX} y={n.y + n.height / 2} dy="1.1em" textAnchor={first ? "end" : "start"} className={halo("fill-muted-foreground text-[11px] tabular-nums")}>
{format(n.value)}
</text>
)}
</g>
);
})}
</svg>
)}
{tip && (
<div
aria-hidden="true"
className="pointer-events-none absolute left-0 top-0 z-10 whitespace-nowrap rounded-lg border border-border bg-popover px-3 py-2 text-xs text-popover-foreground shadow-lg tabular-nums"
style={{ transform: `translate(calc(${tip.x}px - 50%), calc(${tip.y}px - 100% - 10px))` }}
>
{tip.text}
</div>
)}
</div>
<div className="sr-only">
<table>
<caption>{title}</caption>
<thead>
<tr>
<th scope="col">From</th>
<th scope="col">To</th>
<th scope="col">Amount</th>
</tr>
</thead>
<tbody>
{layout.links.map((l) => (
<tr key={`${l.source}-${l.target}`}>
<td>{nameOf(l.source)}</td>
<td>{nameOf(l.target)}</td>
<td>{format(l.value)}</td>
</tr>
))}
</tbody>
</table>
</div>
</figure>
);
}Props
| Prop | Type | Default | Description |
|---|---|---|---|
| links | { source; target; value }[] | — | What flows between what. Columns and order are worked out for you. |
| nodes | { id; label?; color? }[] | [] | Optional labels and colours. |
| title | string | — | Names the chart and its data table. |
| showTitle | boolean | true | Show the title above the chart. |
| format | (value: number) => string | — | Formats labels, tooltip and table values. Overrides formatOptions. |
| formatOptions / locale | Intl.NumberFormatOptions / string | compact, visitor's locale | Number format without a function. |
| height | number | 360 | Chart height in pixels. |
| nodeGap | number | 18 | Space between nodes in a column, in pixels. |
Accessibility
- A labelled <figure>; every link is also available in a visually hidden table.
- Each node is announced with its total; Tab enters the chart, arrow keys move between nodes.
- Focus traces the same paths as hover.
- Ribbons appear without drawing, and nothing runs along them, under prefers-reduced-motion.
Changelog
- v1.0.0Latest
First release.