Sankey flow
Connect staged quantities with proportional ribbons, switch between upright and wide layouts, and trace named node journeys.
pnpm dlx shadcn@latest add @haze/sankey-flow---
import { ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface FlowNode{id:string;label:string;stage:number}
interface Link{source:string;target:string;value:number}
interface Props{label?:string;nodes?:FlowNode[];links?:Link[];unit?:string;class?:string}
const{label="Trial journey",unit="people",nodes=[{id:"search",label:"Search",stage:0},{id:"direct",label:"Direct",stage:0},{id:"trial",label:"Trial",stage:1},{id:"browse",label:"Browse",stage:1},{id:"paid",label:"Paid",stage:2},{id:"leave",label:"Left",stage:2}],links=[{source:"search",target:"trial",value:50},{source:"search",target:"browse",value:30},{source:"direct",target:"trial",value:40},{source:"direct",target:"browse",value:20},{source:"trial",target:"paid",value:65},{source:"trial",target:"leave",value:25},{source:"browse",target:"paid",value:12},{source:"browse",target:"leave",value:38}],class:className}=Astro.props;
const ids=new Set<string>(),items=nodes.filter(node=>{if(!node.id||ids.has(node.id)||!Number.isFinite(node.stage))return false;ids.add(node.id);return true;});
const valid=links.filter(link=>Number.isFinite(link.value)&&link.value>0&&items.some(node=>node.id===link.source)&&items.some(node=>node.id===link.target)&&items.find(node=>node.id===link.source)!.stage<items.find(node=>node.id===link.target)!.stage);
const max=Math.max(0,...valid.map(link=>link.value)),flows=valid.map(link=>({...link,weight:link.value/max}));
const stages=[...new Set(items.map(node=>node.stage))].sort((a,b)=>a-b);
const boxes=items.map(node=>{const incoming=flows.filter(link=>link.target===node.id).reduce((s,link)=>s+link.weight,0),outgoing=flows.filter(link=>link.source===node.id).reduce((s,link)=>s+link.weight,0);return{...node,incoming,outgoing,weight:Math.max(incoming,outgoing),x:stages.length>1?12+stages.indexOf(node.stage)/(stages.length-1)*266:145,y:0,h:0};});
const scale=Math.min(220,...stages.map(stage=>{const column=boxes.filter(node=>node.stage===stage),total=column.reduce((s,node)=>s+node.weight,0);return total?Math.max(1,220-(column.length-1)*12)/total:220;}));
for(const stage of stages){const column=boxes.filter(node=>node.stage===stage),height=column.reduce((s,node)=>s+node.weight*scale,0)+(column.length-1)*12;let y=10+(220-height)/2;for(const node of column){node.y=y;node.h=node.weight*scale;y+=node.h+12;}}
const incoming=new Map<string,number>(),outgoing=new Map<string,number>();
const ribbons=flows.map((link,index)=>{const source=boxes.find(node=>node.id===link.source)!,target=boxes.find(node=>node.id===link.target)!,sy=source.y+(outgoing.get(source.id)??0),ty=target.y+(incoming.get(target.id)??0),width=link.weight*scale;outgoing.set(source.id,(outgoing.get(source.id)??0)+width);incoming.set(target.id,(incoming.get(target.id)??0)+width);return{...link,index,sx:source.x+12,tx:target.x,sy,ty,width};});
const ribbon=(flow:typeof ribbons[number],vertical=false)=>{const point=(x:number,y:number)=>vertical?y+" "+x:x+" "+y,m=(flow.sx+flow.tx)/2;return"M"+point(flow.sx,flow.sy)+"C"+point(m,flow.sy)+" "+point(m,flow.ty)+" "+point(flow.tx,flow.ty)+"L"+point(flow.tx,flow.ty+flow.width)+"C"+point(m,flow.ty+flow.width)+" "+point(m,flow.sy+flow.width)+" "+point(flow.sx,flow.sy+flow.width)+"Z";};
const colors=["fill-brand","fill-success","fill-warning","fill-muted-foreground","fill-destructive"];
---
<figure data-haze-sankey-flow data-nodes={JSON.stringify(boxes)} data-flows={JSON.stringify(flows)} data-unit={unit} data-scale={max} class={cn("@container grid min-w-0 gap-3 rounded-xl border border-border bg-card p-4.5 text-card-foreground",className)}>
<figcaption class="text-[0.9375rem]/5 font-medium tracking-[-0.01em] wrap-anywhere">{label}</figcaption>
{ribbons.length?<>{[false,true].map(vertical=><svg aria-hidden="true" viewBox={vertical?"0 0 240 320":"0 -6 300 246"} class={cn("w-full",vertical?"max-h-96 @sm:hidden":"hidden @sm:block")}>{ribbons.map(flow=><path data-sankey-link={flow.index} d={ribbon(flow,vertical)} class="fill-brand/20 transition-opacity duration-200 ease-snappy data-[dimmed]:opacity-15"/>)}
{boxes.filter(node=>node.h>0).map((node,index)=><g data-sankey-node={node.id} class="transition-opacity duration-200 ease-snappy data-[dimmed]:opacity-20"><rect x={vertical?node.y:node.x} y={vertical?node.x:node.y} width={vertical?node.h:12} height={vertical?12:node.h} rx="2" class={colors[index%colors.length]}/><text x={vertical?node.y+node.h/2:node.x+6} y={vertical?node.x+24:node.y-4} text-anchor="middle" stroke-width="3" class={cn("fill-muted-foreground stroke-card [paint-order:stroke]",vertical?"text-[13px]":"text-[10px]")}>{node.label}</text></g>)}</svg>)}</>:<p class="text-sm/6 text-muted-foreground">No positive forward flows between named stages.</p>}
{boxes.length>0&&<label hidden data-sankey-control class="grid gap-1 text-xs/5 text-muted-foreground">Trace a node<select data-sankey-select class="h-10 min-w-0 rounded-lg border border-frame bg-field px-3 text-[0.8125rem] text-foreground hover:border-frame-strong hover:bg-accent focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden"><option value="">All flows</option>{boxes.map(node=><option value={node.id}>{node.label}</option>)}</select></label>}
<p data-sankey-readout role="status" aria-live="polite" class="min-h-10 text-xs/5 text-muted-foreground">Ribbon width uses a common value scale. Nodes reserve the larger of incoming and outgoing totals.</p>
<details class="group min-w-0 border-t border-border pt-3"><summary class="flex min-h-7 cursor-pointer list-none items-center justify-between gap-2 rounded-sm text-[0.8125rem]/5 font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">Flows and source shares<ChevronDown aria-hidden="true" class="size-3.5 shrink-0 transition-[rotate] duration-200 ease-snappy group-open:rotate-180" /></summary><table class="mt-3 w-full table-fixed text-left text-xs/5"><caption class="sr-only">{label}</caption><thead><tr><th scope="col" class="p-1">Journey</th><th scope="col" class="p-1 text-right">Value / source share</th></tr></thead><tbody>{flows.map(flow=><tr class="border-t border-border"><th scope="row" class="p-1 font-normal wrap-anywhere">{boxes.find(node=>node.id===flow.source)!.label} → {boxes.find(node=>node.id===flow.target)!.label}</th><td class="p-1 text-right tabular-nums wrap-anywhere">{flow.value} {unit} / {(flow.weight/boxes.find(node=>node.id===flow.source)!.outgoing*100).toFixed(1)}%</td></tr>)}</tbody></table></details>
</figure>
<script>
function initSankey(){document.querySelectorAll<HTMLElement>("[data-haze-sankey-flow]:not([data-enhanced])").forEach(root=>{
root.dataset.enhanced="";const nodes:{id:string;label:string;incoming:number;outgoing:number;weight:number}[]=JSON.parse(root.dataset.nodes||"[]"),flows:{source:string;target:string;value:number;weight:number}[]=JSON.parse(root.dataset.flows||"[]"),select=root.querySelector<HTMLSelectElement>("[data-sankey-select]");root.querySelector("[data-sankey-control]")?.removeAttribute("hidden");
select?.addEventListener("change",()=>{const chosen=select.value,ancestors=new Set(chosen?[chosen]:[]),descendants=new Set(chosen?[chosen]:[]);for(let pass=0;pass<nodes.length;pass++){for(const flow of flows){if(ancestors.has(flow.target))ancestors.add(flow.source);if(descendants.has(flow.source))descendants.add(flow.target);}}const traced=flows.map(flow=>!chosen||ancestors.has(flow.target)&&ancestors.has(flow.source)||descendants.has(flow.source)&&descendants.has(flow.target));root.querySelectorAll<SVGPathElement>("[data-sankey-link]").forEach(path=>path.toggleAttribute("data-dimmed",!traced[Number(path.dataset.sankeyLink)]));root.querySelectorAll<SVGGElement>("[data-sankey-node]").forEach(node=>node.toggleAttribute("data-dimmed",Boolean(chosen)&&!ancestors.has(node.dataset.sankeyNode||"")&&!descendants.has(node.dataset.sankeyNode||"")));const node=nodes.find(item=>item.id===chosen),scale=Number(root.dataset.scale),format=(v:number)=>Number.isFinite(v*scale)?(v*scale).toLocaleString("en",{maximumFractionDigits:2}):"above numeric range";root.querySelector("[data-sankey-readout]")!.textContent=node?node.label+": "+format(node.incoming)+" incoming, "+format(node.outgoing)+" outgoing "+(root.dataset.unit||"")+". Next: "+(flows.filter(flow=>flow.source===chosen).map(flow=>nodes.find(n=>n.id===flow.target)?.label+" "+flow.value).join("; ")||"end of journey")+".":"All flows shown on a shared width scale.";});
});}
initSankey();if(!document.documentElement.hasAttribute("data-haze-sankey-flow-listener")){document.documentElement.setAttribute("data-haze-sankey-flow-listener","");document.addEventListener("astro:page-load",initSankey);}
</script>When to use
- A total splits or combines between two or more ordered stages.
- Incoming and outgoing quantities must be compared on a common ribbon-width scale.
When not to use
- The journey is a single ordered conversion sequence. Use funnel-chart.
Installation
Add the Haze registry to components.json once, then install Sankey flow with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/sankey-flownpx shadcn@latest add @haze/sankey-flowyarn dlx shadcn@latest add @haze/sankey-flowbunx --bun shadcn@latest add @haze/sankey-flowFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| label | string | Trial journey | Journey caption. |
| nodes | { id: string; label: string; stage: number }[] | – | Unique node ids with finite ordered stages. Duplicate ids and invalid stages are omitted. |
| links | { source: string; target: string; value: number }[] | – | Positive finite forward links. Node height reserves the greater of inbound and outbound totals. |
| unit | string | people | Flow unit for readout and the table. |
| class | string | – | Additional classes on the chart figure. |
Keyboard interactions
- Arrow keys
- Select a node to trace its ancestors and descendants through the native select.
Accessibility
- The trace selector names every node and reports incoming, outgoing and next destinations in text.
- The table lists all valid flows and source shares. Only finite positive links between strictly increasing named stages are rendered.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Sankey flow" with `npx shadcn@latest add @haze/sankey-flow`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import SankeyFlow from "@/components/haze/ui/sankey-flow.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/sankey-flow.md
Customize with real content
Adapt the Haze sankey-flow ui for our product. Replace the demo values of these props with our real content: label, nodes, links, unit, class. Keep the layout, the heading level rules and these accessibility details: The trace selector names every node and reports incoming, outgoing and next destinations in text. The table lists all valid flows and source shares. Only finite positive links between strictly increasing named stages are rendered. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using sankey-flow, check it fits: use it when a total splits or combines between two or more ordered stages.; incoming and outgoing quantities must be compared on a common ribbon-width scale.. Avoid it when the journey is a single ordered conversion sequence. use funnel-chart.. Alternatives: @haze/funnel-chart, @haze/streamgraph, @haze/sunburst.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.