SankeyChart
Examples
Simple Flow — keyboard access (Tab through links then nodes; Enter/Space activates the focused one exactly like a click)
With Values
Website Traffic Flow
dataLabelOffsetX — Extra breathing room between nodes and labels (offset: 30px)
minLinkWidth — Tiny flows stay visible (minLinkWidth: 3, payment data with near-zero failure rates)
disableDimOnHover — All nodes stay at full opacity when hovering
Crowded funnel — loaded-font spacing + width-aware truncation (all node labels stay visible; full labels remain available in accessible names and keyboard/pointer tooltips)
Combined — minLinkWidth + dataLabelOffsetX + disableDimOnHover
radius + maxHeight — squared-off nodes, capped chart height
radius sets the corner radius on each node rect (SVG rx/ry cannot read CSS var(), so this is a prop). maxHeight caps the rendered
height regardless of aspectRatio.
Tooltip portal — chart sits inside an overflow: hidden box that would otherwise clip the
tooltip
Non-finite link value — degrades to a zero-width link, not NaN geometry
"Direct" → "Landing Page" has no reading this period (NaN). The sanitized-links choke
point in computeSankeyLayout gives it a zero value, so it collapses to the minLinkWidth floor and contributes nothing to "Landing Page"'s incoming total — every
other node and link keeps its correct width and position instead of the one non-finite value
spreading through the layout's column-centring step. See docs/CHART_INPUT_POLICY.md for the full input-shape table.
Documentation
A responsive SVG Sankey diagram for visualizing flows between nodes. Automatically positions nodes into columns via topological ordering and iterative relaxation. Node heights and link widths share one global px-per-value scale (set by the tightest column), so equal values render equally tall in every column and each node's ribbon stack sits flush inside its bar — ribbons never spill past a bar's bottom edge. Hovering highlights all connected nodes and dims unrelated ones (opt-out via disableDimOnHover). Supports a configurable minimum link/node thickness (minLinkWidth) so tiny flows remain visible, and a horizontal label offset (dataLabelOffsetX) for fine-grained spacing between node bars and their text labels.
Usage
<script>
import { SankeyChart } from '@juspay/svelte-ui-components';
const nodes = [
{ id: 'source-a', label: 'Source A' },
{ id: 'source-b', label: 'Source B' },
{ id: 'process-1', label: 'Process 1' },
{ id: 'output', label: 'Output' }
];
const links = [
{ source: 'source-a', target: 'process-1', value: 40 },
{ source: 'source-b', target: 'process-1', value: 30 },
{ source: 'process-1', target: 'output', value: 70 }
];
</script>
<SankeyChart {nodes} {links} />
With Flow Values
<SankeyChart {nodes} {links} showValues />
Custom Node Colors
<script>
const nodes = [
{ id: 'a', label: 'A', color: '#4285f4' },
{ id: 'b', label: 'B', color: '#34a853' }
];
</script>
Column Labels
<SankeyChart {nodes} {links} columnLabels={['Input', 'Processing', 'Output']} />
Custom Node Colors via Resolver
<script>
const resolveColor = (id, label) => {
if (id.startsWith('error-')) return '#ef4444';
return null; // fall through to default palette
};
</script>
<SankeyChart {nodes} {links} nodeColorResolver={resolveColor} />
Minimum Link Width — keep tiny flows visible
Use minLinkWidth to ensure flows with very small values still render as a visible band rather than collapsing to a sub-pixel line. Particularly useful for dense payment-flow diagrams where failure rates are small fractions of the total.
<SankeyChart {nodes} {links} minLinkWidth={3} />
Data Label Offset — breathing room between nodes and labels
dataLabelOffsetX shifts every node label further away from (positive) or closer to (negative) its node bar. Lighthouse uses 30 for dense diagrams.
<SankeyChart {nodes} {links} dataLabelOffsetX={30} />
Disable Dim on Hover — all nodes stay at full opacity
When you want the overall flow structure to remain fully readable while the user inspects one node, set disableDimOnHover. All nodes and links stay at their normal opacity regardless of hover state.
<SankeyChart {nodes} {links} disableDimOnHover />
Custom Tooltip
<SankeyChart {nodes} {links}>
{#snippet tooltipSnippet(context)}
<div style="background: #333; color: white; padding: 8px; border-radius: 4px;">
{#if context.type === 'node'}
<strong>{context.node.label ?? context.node.id}</strong>: {context.value}
{:else}
<!-- sourceLabel, targetLabel, percentage are always set by the chart at runtime -->
<strong>{context.sourceLabel} → {context.targetLabel}</strong>:
{context.link.value} ({context.percentage?.toFixed(2)}% of source)
{/if}
</div>
{/snippet}
</SankeyChart>
Empty State
<SankeyChart nodes={[]} links={[]}>
{#snippet empty()}
<p>No flow data available.</p>
{/snippet}
</SankeyChart>
Label overflow & collisions
Node labels are laid out defensively so a crowded chart never renders overlapping text:
- Labels are truncated against their real rendered width (canvas-measured, with an SSR-safe
heuristic fallback), so uppercase-heavy labels cannot run under a neighbouring column's bars and
the right label gutter reserves exactly the space the longest sink label needs. Middle columns
also budget for
dataLabelOffsetX. - Labels keep their real loaded SVG font metrics, including Firefox's native painted bounds. Node spacing includes label height, opaque-plate padding and a clear gap. All node labels stay rendered; small-value labels are not removed to resolve collisions.
- Layout and cached truncation widths refresh after
document.fonts.ready, subsequent font loads, text/style changes and resize. At narrow widths the chart reserves a font-sized minimum height withinmaxHeightand scrolls horizontally to preserve meaningful label slots. Existing--chart-min-widthoverrides retain precedence. - Truncated labels keep their full text in their SVG
<title>and the node's accessible name and keyboard/pointer tooltip. Node labels and column headers use opaque glyph-sized plates through--chart-label-background, retaining the existing foreground and optional halo tokens. - Connected-node highlighting still dims unrelated data graphics. Labels retain full opacity by
default so their values remain readable;
--sankey-label-dimmed-opacitycontrols label opacity independently of--sankey-dimmed-opacityon the graphics.
Keyboard access
Every node and link is a focusable role="button" element (tabindex="0"), labelled
via aria-label — a node with its resolved label and value, a link with its source and
target labels and value. Tab/Shift+Tab moves through links then nodes; Enter or
Space on a focused node or link fires onnodeclick/onlinkclick, the same event a
pointer click fires. Focusing a node or link also highlights it (dimming unrelated
nodes/links, unless disableDimOnHover is set) exactly as pointer hover does, and fires
the same onnodehover/onlinkhover callback. This is the same family-wide keyboard/
tooltip contract implemented by BarChart, DualAxisBarChart, FunnelChart and PieChart —
see PieChart's "Keyboard access" section for the full
contract.
Tooltip portal
Pass tooltipPortal to render the tooltip into the chart's own root (its shadow root
when hosted as a custom element, document.body otherwise) with position: fixed,
clamped to the viewport, instead of positioned inside the chart. Use it when the chart
sits inside a container with overflow: hidden/scroll that would otherwise clip the
tooltip:
<div style="overflow: hidden; max-height: 300px;">
<SankeyChart {nodes} {links} tooltipPortal />
</div>
tooltipPortal only changes where the tooltip wrapper renders — it has no effect on
tooltipSnippet's content, so a custom tooltip snippet keeps working unchanged.
Invalid values
A link value that is not a real number (NaN, Infinity, -Infinity), or
is negative, contributes 0. The link is still present in the graph but
carries no volume, so it renders at the minimum link width rather than
disappearing — which keeps the node it connects in the layout.
Every other link and node keeps its correct geometry.
A Sankey diagram is where this mattered most, because the damage travelled
furthest. Node positions are computed column by column, and a per-column
recentring step propagates a shift across every node in that column; a
relaxation pass then carries each column's positions into the next. One
invalid link value therefore reached nodes two columns downstream whose own
links were entirely finite — in a five-node graph, all five nodes ended with
y=NaN and every link path contained literal NaN coordinates. See
Chart Input Policy.
A graph whose links are all invalid is still distinguishable from a genuinely empty one: an empty graph renders the empty state, while an invalid one renders its nodes at minimum width.
Chart name and description
Pass ariaLabel to identify the chart's purpose and ariaDescription for its takeaway,
units or reading instructions. Both belong to the drawing itself, so its points are
reached in a named group. Without an explicit name the chart derives one from its data.
A drawing with no marks is a named image with no point Tab stops.
<SankeyChart
{...chartProps}
ariaLabel="Checkout outcomes"
ariaDescription="Values are available on each data control."
/>
The web component uses chart-aria-label and chart-aria-description, or JS properties
chartAriaLabel / chartAriaDescription. These aliases preserve the host's native
ariaLabel / ariaDescription accessors. The description resolves in the same shadow
root as the drawing, with an instance-scoped ID.
<sui-sankey-chart
chart-aria-label="Checkout outcomes"
chart-aria-description="Values are available on each data control."
></sui-sankey-chart>
A supplied empty snippet replaces the drawing and keeps its own semantics, including
any actions the consumer puts in it.
Props
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| nodes | SankeyNode[] |
Yes | - |
Array of {id, label?, color?}. Each node becomes a vertical bar. |
| links | SankeyLink[] |
Yes | - |
Array of {source, target, value, color?}. Each link becomes a curved band between nodes. |
| nodeWidth | number |
No | 16 |
Width of each node bar in pixels. |
| nodePadding | number |
No | 8 |
Vertical space between nodes in the same column. |
| iterations | number |
No | 6 |
Number of relaxation passes to minimize link crossings. Higher = better layout but slower. |
| showValues | boolean |
No | false |
Whether to append the total flow value to each node label. |
| showLabels | boolean |
No | true |
Whether to render node labels. |
| aspectRatio | number |
No | 16/9 |
Width-to-height ratio. |
| radius | number |
No | 4 |
Corner radius on each node rect, in pixels. SVG rx/ry cannot read CSS var(), so this is a prop rather than a CSS variable — pass it explicitly to track a changed --radius design token at runtime. |
| maxHeight | number |
No | 420 |
Caps the chart's rendered height in pixels regardless of aspectRatio. |
| valueFormat | (value: number) => string |
No | abbreviated | Formatter for flow values. |
| tooltipSnippet | Snippet<[SankeyTooltipContext]> |
No | - |
Custom tooltip. Receives {type: 'node', node, value} on node hover, or {type: 'link', link, sourceLabel, targetLabel, percentage} on link hover. sourceLabel/targetLabel are pre-resolved human-readable names; percentage is the link's share of the source node's total flow (0–100, 2 dp). |
| tooltipPortal | boolean |
No | false |
Render the tooltip into the chart's own root (shadow root, or document.body) with position: fixed, clamped to the viewport, instead of positioned inside the chart. Use inside an overflow: hidden/scroll container. No effect on tooltipSnippet's content. |
| empty | Snippet |
No | - |
Content rendered when nodes is empty. |
| ariaLabel | string |
No | Derived from data | Accessible name of the drawing. |
| ariaDescription | string |
No | — | Longer description scoped to this drawing instance. |
| testId | string |
No | - |
Value for the data-pw attribute on the chart container. |
| classes | string |
No | - |
CSS class string applied to the top-level element. |
| columnLabels | string[] |
No | - |
Labels rendered above each column (index 0 = first column). Positioned above the chart area, centered on the column midpoint. |
| nodeColorResolver | (id: string, label: string | null) => string | null |
No | - |
Called for each node and also for link strokes (links inherit the source node's resolved colour). Return a CSS colour string to override the default palette, or null to fall through. label is null when the node has no label. |
| minLinkWidth | number |
No | 1 |
Minimum rendered thickness (px) for any link or node bar. Tiny flows that would otherwise collapse to sub-pixel widths remain at this thickness so they stay visually discoverable. Lighthouse uses 2–3 for dense payment-flow diagrams. |
| dataLabelOffsetX | number |
No | 0 |
Horizontal offset in pixels applied to every node data-label, relative to the default position. Positive values push the label further away from the node bar; negative values pull it closer. Lighthouse uses 30 to create breathing room in dense diagrams. |
| disableDimOnHover | boolean |
No | false |
When true, hovering a node does not dim unrelated nodes — all nodes and links remain at full opacity. Useful for dense diagrams where the standard dim effect makes the overall flow structure hard to read. |
| firstColumnLabelSide | 'left' | 'right' |
No | 'left' |
Which side of a first-column node its label renders on. 'left' anchors the label into a reserved left gutter outside the diagram. 'right' renders it like every other column — right of the bar, over the outgoing ribbons (pair with the --sankey-label-halo-* tokens); no left gutter is reserved, so the diagram gains that width. |
| lastColumnLabelSide | 'left' | 'right' |
No | 'right' |
Which side of a last-column (sink) node its label renders on. 'right' anchors the label into a reserved right gutter outside the diagram. 'left' renders it inside the plot — left of the bar, over the incoming ribbons; no right gutter is reserved, so the diagram runs to the right edge. In a single-column chart firstColumnLabelSide wins. |
| marginX | number |
No | 40 |
Horizontal inset between the svg edges and the diagram (plus any label gutters). Lower it for edge-to-edge funnels when both first/last column labels render inside the plot; column headers clamp to the canvas so they never paint past the svg edge. |
Events
| Event | Type | Description |
|---|---|---|
| onnodeclick | (event: { node: SankeyNode }) => void |
Fires when a node is clicked. |
| onlinkclick | (event: { link: SankeyLink }) => void |
Fires when a link is clicked. |
| onnodehover | (event: { node: SankeyNode } | null) => void |
Fires on node hover or leave. |
| onlinkhover | (event: { link: SankeyLink } | null) => void |
Fires on link hover or leave. |
CSS Variables
In addition to the shared --chart-* variables (see BarChart docs), SankeyChart exposes:
| Variable | Default | CSS Property | Description |
|---|---|---|---|
--sankey-dimmed-opacity |
0.15 |
opacity | Opacity of non-connected data nodes when hovering. Has no effect when disableDimOnHover is true. |
--sankey-plot-background |
transparent |
fill | Backdrop panel behind the diagram — spans exactly the plot (first column's bars to last column's bars, header row excluded). |
--chart-label-background |
light-dark(#fff, #111827) |
fill | Opaque measured backdrop for node labels and column headers. |
--sankey-label-dimmed-opacity |
1 |
opacity | Opacity of non-connected node labels; graphics still use --sankey-dimmed-opacity. |
--sankey-label-color |
light-dark(#333, #e5e7eb) |
fill | Color of node labels. |
--sankey-label-font-size |
12px |
font-size | Font size of node labels. Also feeds the text-measurement engine (truncation budgets, vertical de-collision). |
--sankey-label-font-weight |
400 |
font-weight | Weight of node labels (numeric value, e.g. 700). Also feeds the text-measurement engine so truncation budgets stay honest at bolder weights. |
--sankey-label-halo-color |
transparent |
stroke | Highcharts-style text outline behind node labels (paint-order: stroke). Set it to the chart's background colour so labels stay legible over dense link ribbons. |
--sankey-label-halo-width |
0 |
stroke-width | Thickness of the node-label halo, e.g. 2px. 0 disables it. |
--sankey-col-label-color |
light-dark(#666, #9ca3af) |
fill | Color of column header labels (columnLabels prop). |
--sankey-col-label-font-size |
11px |
font-size | Font size of column header labels. |
--sankey-col-label-font-weight |
400 |
font-weight | Weight of column header labels (numeric value). |
Type Reference
type SankeyNode = {
id: string;
label?: string;
color?: string;
};
type SankeyLink = {
source: string;
target: string;
value: number;
color?: string;
};
type SankeyTooltipContext =
| { type: 'node'; node: SankeyNode; value: number }
| {
type: 'link';
link: SankeyLink;
/** Human-readable label of the source node (falls back to node id when label is undefined). Always present at runtime. */
sourceLabel?: string;
/** Human-readable label of the target node (falls back to node id when label is undefined). Always present at runtime. */
targetLabel?: string;
/** link.value as a percentage of the source node's total outgoing value (0–100, rounded to 2 dp). Always present at runtime. */
percentage?: number;
};
The tooltipSnippet prop receives a SankeyTooltipContext. In the 'link' branch, sourceLabel and targetLabel are pre-resolved human-readable names (falling back to the node id when no label is set), and percentage gives the link's share of the source node's total flow as a 0–100 value rounded to two decimal places.
Additive / backward-compatible: The
'link'branch ofSankeyTooltipContextgained three new optional fields —sourceLabel,targetLabel, andpercentage. They are always populated at runtime by the chart. Existing consumer code that typed a variable as{ type: 'link'; link: SankeyLink }continues to compile without changes. Accessing the new fields requires addingsourceLabel?: string,targetLabel?: string, andpercentage?: number(or widening toSankeyTooltipContext) in the consumer's type annotation.
Web Component
sui-sankey-chart is registered by the web-component bundle. Historically SankeyChart
had no tooltipPortal and this note explained why a Web Component wrapper was safe to
ship regardless: nothing here portalled a node out of the shadow root, so there was
nothing to lose its shadow-scoped styles. That is no longer the reason it is safe —
SankeyChart now supports tooltipPortal too, and ChartTooltip resolves the portal
destination from the node's own root (getRootNode()) rather than hardcoding
document.body, so a portalled tooltip keeps its shadow-scoped styles inside a
<sui-sankey-chart> custom element exactly as an unportalled one does.
<script type="module" src="@juspay/svelte-ui-components/wc"></script>
<sui-sankey-chart show-values node-width="18" margin-x="48"></sui-sankey-chart>
<script>
const chart = document.querySelector('sui-sankey-chart');
chart.nodes = [
{ id: 'visit', label: 'Visit' },
{ id: 'cart', label: 'Cart' },
{ id: 'buy', label: 'Purchase' }
];
chart.links = [
{ source: 'visit', target: 'cart', value: 4200 },
{ source: 'cart', target: 'buy', value: 980 }
];
chart.valueFormat = (v) => `${(v / 1000).toFixed(1)}k`;
</script>
Arrays, objects and functions — nodes, links, columnLabels, valueFormat,
nodeColorResolver and every callback — must be assigned as JavaScript
properties. They cannot cross the HTML-attribute boundary.
Web Component Events
onnodeclick, onlinkclick, onnodehover, and onlinkhover are available as JS
properties, and each also dispatches a same-named DOM custom event (bubbles, composed)
for a consumer who only calls addEventListener — nodeclick's detail is { node },
linkclick's is { link }, and the hover events carry the same shape (or null on
hover-out):
const chart = document.querySelector('sui-sankey-chart');
chart.addEventListener('nodeclick', (e) => console.log(e.detail.node));
chart.addEventListener('linkclick', (e) => console.log(e.detail.link));
chart.addEventListener('nodehover', (e) => setHighlighted(e.detail?.node ?? null));
chart.addEventListener('linkhover', (e) => setHighlighted(e.detail?.link ?? null));
Slots
| Slot | Replaces |
|---|---|
empty |
The empty state shown when there are no links to lay out. |
Supply it only when you mean to: with no empty slot the component falls through
to its own chart frame, and an empty slot would replace that frame with a blank box.
Svelte-only:
tooltipSnippet(receivesSankeyTooltipContext) takes an argument, so it cannot be expressed as a named slot: a Web Component<slot>projects markup and does not forward Svelte snippet parameters, so the hover context would be silently dropped. Use the Svelte component directly when you need a custom tooltip.