Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(lab): XDSSankeyChart — ribbon-based flow visualization (#1516)

Cindy Zhang5b7f535d9b02
diff --git a/apps/storybook/stories/SankeyChart.stories.tsx b/apps/storybook/stories/SankeyChart.stories.tsx
new file mode 100644
index 0000000000..1c7d5f4d23
--- /dev/null
+++ b/apps/storybook/stories/SankeyChart.stories.tsx
@@ -0,0 +1,662 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ XDSSankeyChart,
+ XDSSankeyLink,
+ XDSSankeyNode,
+ XDSSankeyLabel,
+ XDSSankeyGrid,
+ type SankeyNode,
+ type SankeyLink,
+} from '@xds/lab';
+import {XDSStack, XDSText} from '@xds/core';
+import {XDSHeading} from '@xds/core/Text';
+
+const meta: Meta = {
+ title: 'Lab/XDSSankeyChart',
+ tags: ['autodocs'],
+};
+
+export default meta;
+type Story = StoryObj;
+
+// --- Data ---
+
+const funnelNodes: SankeyNode[] = [
+ {id: 'visitors', label: 'Visitors', value: 52000, color: [0.65, 0.2, 270]},
+ {id: 'signups', label: 'Sign Ups', value: 28000, color: [0.6, 0.17, 235]},
+ {id: 'bounced', label: 'Bounced', value: 24000, color: [0.55, 0.14, 350]},
+ {id: 'activated', label: 'Activated', value: 19500, color: [0.62, 0.16, 190]},
+ {id: 'dormant', label: 'Dormant', value: 8500, color: [0.55, 0.13, 50]},
+ {
+ id: 'subscribed',
+ label: 'Subscribed',
+ value: 12400,
+ color: [0.64, 0.18, 155],
+ },
+ {id: 'churned', label: 'Churned', value: 7100, color: [0.54, 0.15, 20]},
+];
+
+const funnelLinks: SankeyLink[] = [
+ {source: 'visitors', target: 'signups', value: 28000},
+ {source: 'visitors', target: 'bounced', value: 24000},
+ {source: 'signups', target: 'activated', value: 19500},
+ {source: 'signups', target: 'dormant', value: 8500},
+ {source: 'activated', target: 'subscribed', value: 12400},
+ {source: 'activated', target: 'churned', value: 7100},
+];
+
+const funnelColumns = [
+ ['visitors'],
+ ['signups', 'bounced'],
+ ['activated', 'dormant'],
+ ['subscribed', 'churned'],
+];
+
+/** Classic diverging funnel with grid lines */
+export const ConversionFunnel: Story = {
+ render: () => (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Conversion Funnel</XDSHeading>
+ <XDSText type="body" color="secondary">
+ User journey · Last 30 days
+ </XDSText>
+ <XDSSankeyChart
+ nodes={funnelNodes}
+ links={funnelLinks}
+ columns={funnelColumns}
+ height={360}>
+ <XDSSankeyGrid />
+ <XDSSankeyLink />
+ <XDSSankeyNode />
+ <XDSSankeyLabel />
+ </XDSSankeyChart>
+ </XDSStack>
+ ),
+};
+
+// --- Revenue Sources (converging) ---
+
+const revenueNodes: SankeyNode[] = [
+ {id: 'organic', label: 'Organic', value: 18000, color: [0.62, 0.17, 155]},
+ {id: 'paid', label: 'Paid Ads', value: 22000, color: [0.6, 0.18, 240]},
+ {id: 'referral', label: 'Referral', value: 12000, color: [0.58, 0.15, 40]},
+ {id: 'direct', label: 'Direct', value: 8000, color: [0.55, 0.14, 300]},
+ {id: 'web', label: 'Web', value: 32000, color: [0.61, 0.16, 210]},
+ {id: 'mobile', label: 'Mobile', value: 20000, color: [0.59, 0.16, 170]},
+ {id: 'other', label: 'Other', value: 8000, color: [0.5, 0.11, 320]},
+ {id: 'sub', label: 'Subscription', value: 38000, color: [0.64, 0.19, 260]},
+ {id: 'onetime', label: 'One-time', value: 14000, color: [0.58, 0.15, 50]},
+ {
+ id: 'enterprise',
+ label: 'Enterprise',
+ value: 8000,
+ color: [0.56, 0.13, 190],
+ },
+];
+
+const revenueLinks: SankeyLink[] = [
+ {source: 'organic', target: 'web', value: 12000},
+ {source: 'organic', target: 'mobile', value: 6000},
+ {source: 'paid', target: 'web', value: 14000},
+ {source: 'paid', target: 'mobile', value: 8000},
+ {source: 'referral', target: 'web', value: 4000},
+ {source: 'referral', target: 'mobile', value: 6000},
+ {source: 'referral', target: 'other', value: 2000},
+ {source: 'direct', target: 'web', value: 2000},
+ {source: 'direct', target: 'other', value: 6000},
+ {source: 'web', target: 'sub', value: 22000},
+ {source: 'web', target: 'onetime', value: 6000},
+ {source: 'web', target: 'enterprise', value: 4000},
+ {source: 'mobile', target: 'sub', value: 14000},
+ {source: 'mobile', target: 'onetime', value: 4000},
+ {source: 'mobile', target: 'enterprise', value: 2000},
+ {source: 'other', target: 'sub', value: 2000},
+ {source: 'other', target: 'onetime', value: 4000},
+ {source: 'other', target: 'enterprise', value: 2000},
+];
+
+const revenueColumns = [
+ ['organic', 'paid', 'referral', 'direct'],
+ ['web', 'mobile', 'other'],
+ ['sub', 'onetime', 'enterprise'],
+];
+
+/** Converging Sankey — multiple sources flowing to fewer destinations */
+export const RevenueFlow: Story = {
+ render: () => (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Revenue Sources</XDSHeading>
+ <XDSText type="body" color="secondary">
+ Channel attribution · March 2026
+ </XDSText>
+ <XDSSankeyChart
+ nodes={revenueNodes}
+ links={revenueLinks}
+ columns={revenueColumns}
+ height={420}>
+ <XDSSankeyGrid />
+ <XDSSankeyLink opacity={0.65} tension={0.55} />
+ <XDSSankeyNode />
+ <XDSSankeyLabel />
+ </XDSSankeyChart>
+ </XDSStack>
+ ),
+};
+
+/** Minimal — auto-detected columns, no grid */
+export const AutoColumns: Story = {
+ render: () => {
+ const nodes: SankeyNode[] = [
+ {id: 'a', label: 'Source A', value: 100},
+ {id: 'b', label: 'Source B', value: 80},
+ {id: 'mid', label: 'Middle', value: 180},
+ {id: 'out1', label: 'Output 1', value: 120},
+ {id: 'out2', label: 'Output 2', value: 60},
+ ];
+ const links: SankeyLink[] = [
+ {source: 'a', target: 'mid', value: 100},
+ {source: 'b', target: 'mid', value: 80},
+ {source: 'mid', target: 'out1', value: 120},
+ {source: 'mid', target: 'out2', value: 60},
+ ];
+
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Auto Column Detection</XDSHeading>
+ <XDSText type="body" color="secondary">
+ No explicit columns — topologically sorted
+ </XDSText>
+ <XDSSankeyChart nodes={nodes} links={links} height={280}>
+ <XDSSankeyLink tension={0.6} />
+ <XDSSankeyNode />
+ <XDSSankeyLabel showPercent={false} />
+ </XDSSankeyChart>
+ </XDSStack>
+ );
+ },
+};
+
+/** Many columns — demonstrates horizontal scroll with minColumnWidth */
+export const ManyColumns: Story = {
+ render: () => {
+ const nodes: SankeyNode[] = [
+ {id: 'awareness', label: 'Awareness', value: 100000},
+ {id: 'interest', label: 'Interest', value: 68000},
+ {id: 'dropped1', label: 'Dropped', value: 32000, color: [0.5, 0.12, 350]},
+ {id: 'consideration', label: 'Consideration', value: 45000},
+ {
+ id: 'dropped2',
+ label: 'Distracted',
+ value: 23000,
+ color: [0.5, 0.12, 350],
+ },
+ {id: 'intent', label: 'Intent', value: 32000},
+ {
+ id: 'dropped3',
+ label: 'Abandoned',
+ value: 13000,
+ color: [0.5, 0.12, 350],
+ },
+ {id: 'evaluation', label: 'Evaluation', value: 24000},
+ {id: 'dropped4', label: 'Lost', value: 8000, color: [0.5, 0.12, 350]},
+ {
+ id: 'purchase',
+ label: 'Purchase',
+ value: 18000,
+ color: [0.64, 0.18, 155],
+ },
+ {id: 'dropped5', label: 'Rejected', value: 6000, color: [0.5, 0.12, 350]},
+ ];
+ const links: SankeyLink[] = [
+ {source: 'awareness', target: 'interest', value: 68000},
+ {source: 'awareness', target: 'dropped1', value: 32000},
+ {source: 'interest', target: 'consideration', value: 45000},
+ {source: 'interest', target: 'dropped2', value: 23000},
+ {source: 'consideration', target: 'intent', value: 32000},
+ {source: 'consideration', target: 'dropped3', value: 13000},
+ {source: 'intent', target: 'evaluation', value: 24000},
+ {source: 'intent', target: 'dropped4', value: 8000},
+ {source: 'evaluation', target: 'purchase', value: 18000},
+ {source: 'evaluation', target: 'dropped5', value: 6000},
+ ];
+ const columns = [
+ ['awareness'],
+ ['interest', 'dropped1'],
+ ['consideration', 'dropped2'],
+ ['intent', 'dropped3'],
+ ['evaluation', 'dropped4'],
+ ['purchase', 'dropped5'],
+ ];
+
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Deep Funnel (6 stages)</XDSHeading>
+ <XDSText type="body" color="secondary">
+ Scrolls horizontally when columns exceed container width
+ </XDSText>
+ <div
+ style={{
+ maxWidth: 600,
+ border: '1px solid var(--color-border, #ddd)',
+ borderRadius: 12,
+ overflow: 'hidden',
+ }}>
+ <XDSSankeyChart
+ nodes={nodes}
+ links={links}
+ columns={columns}
+ height={360}
+ minColumnWidth={160}>
+ <XDSSankeyGrid />
+ <XDSSankeyLink />
+ <XDSSankeyNode />
+ <XDSSankeyLabel />
+ </XDSSankeyChart>
+ </div>
+ </XDSStack>
+ );
+ },
+};
+
+// --- Business Funnel: blue main flow, gray exits ---
+
+// oklch approximations of XDS data tokens:
+// blue categorical: #0171E3 ≈ oklch(0.55 0.19 255)
+// blue-3: #2694FE ≈ oklch(0.65 0.17 250)
+// gray-4: #5D6C7B ≈ oklch(0.50 0.02 240)
+// gray-3: #AFB9C4 ≈ oklch(0.77 0.02 240)
+
+const bizNodes: SankeyNode[] = [
+ {id: 'visitors', label: 'Visitors', value: 84200, color: [0.55, 0.19, 255]},
+ {id: 'signups', label: 'Signed Up', value: 42100, color: [0.58, 0.18, 255]},
+ {id: 'bounce', label: 'Bounced', value: 42100, color: [0.5, 0.02, 240]},
+ {id: 'onboarded', label: 'Onboarded', value: 28700, color: [0.61, 0.17, 252]},
+ {id: 'stalled', label: 'Stalled', value: 13400, color: [0.5, 0.02, 240]},
+ {id: 'active', label: 'Active Users', value: 21500, color: [0.64, 0.16, 250]},
+ {id: 'inactive', label: 'Inactive', value: 7200, color: [0.5, 0.02, 240]},
+ {id: 'paying', label: 'Paying', value: 15200, color: [0.67, 0.15, 248]},
+ {id: 'free', label: 'Free Tier', value: 6300, color: [0.5, 0.02, 240]},
+];
+
+const bizLinks: SankeyLink[] = [
+ {source: 'visitors', target: 'signups', value: 42100},
+ {source: 'visitors', target: 'bounce', value: 42100},
+ {source: 'signups', target: 'onboarded', value: 28700},
+ {source: 'signups', target: 'stalled', value: 13400},
+ {source: 'onboarded', target: 'active', value: 21500},
+ {source: 'onboarded', target: 'inactive', value: 7200},
+ {source: 'active', target: 'paying', value: 15200},
+ {source: 'active', target: 'free', value: 6300},
+];
+
+const bizColumns = [
+ ['visitors'],
+ ['signups', 'bounce'],
+ ['onboarded', 'stalled'],
+ ['active', 'inactive'],
+ ['paying', 'free'],
+];
+
+/**
+ * Business funnel with blue main flow and gray exit paths.
+ * Uses background labels for readability over the ribbons.
+ */
+export const BusinessFunnel: Story = {
+ render: () => (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Acquisition Funnel</XDSHeading>
+ <XDSText type="body" color="secondary">
+ Blue = progression · Gray = drop-off
+ </XDSText>
+ <XDSSankeyChart
+ nodes={bizNodes}
+ links={bizLinks}
+ columns={bizColumns}
+ height={380}>
+ <XDSSankeyGrid />
+ <XDSSankeyLink opacity={0.6} />
+ <XDSSankeyNode />
+ <XDSSankeyLabel />
+ </XDSSankeyChart>
+ </XDSStack>
+ ),
+};
+
+// --- Art Deco style: wider bars with rotated labels + column headers ---
+
+const demoNodes: SankeyNode[] = [
+ {id: 'single', label: 'Single', value: 48, color: [0.62, 0.16, 30]},
+ {id: 'married', label: 'Married', value: 35, color: [0.58, 0.14, 180]},
+ {id: 'divorced', label: 'Divorced', value: 17, color: [0.55, 0.12, 300]},
+ {id: 'male', label: 'Male', value: 55, color: [0.57, 0.15, 240]},
+ {id: 'female', label: 'Female', value: 45, color: [0.6, 0.16, 340]},
+ {id: 'happy', label: 'Happy', value: 62, color: [0.64, 0.18, 150]},
+ {id: 'unhappy', label: 'Unhappy', value: 38, color: [0.52, 0.14, 25]},
+];
+
+const demoLinks: SankeyLink[] = [
+ {source: 'single', target: 'male', value: 26},
+ {source: 'single', target: 'female', value: 22},
+ {source: 'married', target: 'male', value: 20},
+ {source: 'married', target: 'female', value: 15},
+ {source: 'divorced', target: 'male', value: 9},
+ {source: 'divorced', target: 'female', value: 8},
+ {source: 'male', target: 'happy', value: 34},
+ {source: 'male', target: 'unhappy', value: 21},
+ {source: 'female', target: 'happy', value: 28},
+ {source: 'female', target: 'unhappy', value: 17},
+];
+
+const demoColumns = [
+ {ids: ['single', 'married', 'divorced'], label: 'Relationship'},
+ {ids: ['male', 'female'], label: 'Gender'},
+ {ids: ['happy', 'unhappy'], label: 'Outcome'},
+];
+
+/** Wide bars with rotated labels and column headers — art deco style */
+export const WideBarStyle: Story = {
+ render: () => (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Survey Flow</XDSHeading>
+ <XDSText type="body" color="secondary">
+ Wider node bars with rotated text labels
+ </XDSText>
+ <XDSSankeyChart
+ nodes={demoNodes}
+ links={demoLinks}
+ columns={demoColumns}
+ height={380}
+ nodeGap={8}>
+ <XDSSankeyGrid />
+ <XDSSankeyLink opacity={0.5} tension={0.5} />
+ <XDSSankeyNode />
+ <XDSSankeyLabel />
+ </XDSSankeyChart>
+ </XDSStack>
+ ),
+};
+
+// --- US Federal Budget (Vega dataset) ---
+// Source: vega-datasets budget.json — FY2020 federal receipts
+// Revenue sources → receiving agencies (values in $thousands)
+
+const budgetNodes: SankeyNode[] = [
+ {
+ id: 'income_tax',
+ label: 'Income Tax',
+ value: 2118406000,
+ color: [0.55, 0.19, 255],
+ },
+ {
+ id: 'payroll_tax',
+ label: 'Payroll Tax',
+ value: 1336808000,
+ color: [0.58, 0.17, 240],
+ },
+ {
+ id: 'corp_tax',
+ label: 'Corp Tax',
+ value: 511220000,
+ color: [0.6, 0.16, 220],
+ },
+ {
+ id: 'excise_tax',
+ label: 'Excise Tax',
+ value: 119883000,
+ color: [0.56, 0.14, 200],
+ },
+ {
+ id: 'misc_revenue',
+ label: 'Misc Revenue',
+ value: 96615000,
+ color: [0.54, 0.12, 280],
+ },
+ {id: 'customs', label: 'Customs', value: 47878000, color: [0.52, 0.11, 180]},
+ {
+ id: 'proposals',
+ label: 'Proposals',
+ value: 45000000,
+ color: [0.5, 0.1, 300],
+ },
+ {
+ id: 'estate_tax',
+ label: 'Estate Tax',
+ value: 38543000,
+ color: [0.48, 0.09, 160],
+ },
+ {
+ id: 'general_fund',
+ label: 'General Fund',
+ value: 2812308000,
+ color: [0.62, 0.17, 150],
+ },
+ {
+ id: 'social_security',
+ label: 'Social Security',
+ value: 968357000,
+ color: [0.6, 0.16, 170],
+ },
+ {id: 'hhs', label: 'HHS', value: 309881000, color: [0.58, 0.15, 130]},
+ {
+ id: 'treasury',
+ label: 'Treasury',
+ value: 75173000,
+ color: [0.56, 0.13, 190],
+ },
+ {id: 'labor', label: 'Labor', value: 57839000, color: [0.54, 0.12, 40]},
+ {
+ id: 'transport',
+ label: 'Transport',
+ value: 57056000,
+ color: [0.52, 0.11, 60],
+ },
+ {
+ id: 'agriculture',
+ label: 'Agriculture',
+ value: 11566000,
+ color: [0.5, 0.1, 100],
+ },
+ {id: 'fcc', label: 'FCC', value: 10049000, color: [0.48, 0.09, 260]},
+ {
+ id: 'rail_retire',
+ label: 'Rail Retire',
+ value: 7098000,
+ color: [0.5, 0.08, 320],
+ },
+ {id: 'opm', label: 'OPM', value: 5026000, color: [0.48, 0.08, 340]},
+];
+
+const budgetLinks: SankeyLink[] = [
+ {source: 'income_tax', target: 'general_fund', value: 2118406000},
+ {source: 'payroll_tax', target: 'social_security', value: 968357000},
+ {source: 'corp_tax', target: 'general_fund', value: 511220000},
+ {source: 'payroll_tax', target: 'hhs', value: 298488000},
+ {source: 'misc_revenue', target: 'treasury', value: 75173000},
+ {source: 'excise_tax', target: 'general_fund', value: 62827000},
+ {source: 'payroll_tax', target: 'labor', value: 57839000},
+ {source: 'excise_tax', target: 'transport', value: 57056000},
+ {source: 'proposals', target: 'general_fund', value: 45000000},
+ {source: 'estate_tax', target: 'general_fund', value: 38543000},
+ {source: 'customs', target: 'general_fund', value: 36312000},
+ {source: 'customs', target: 'agriculture', value: 11566000},
+ {source: 'misc_revenue', target: 'hhs', value: 11393000},
+ {source: 'misc_revenue', target: 'fcc', value: 10049000},
+ {source: 'payroll_tax', target: 'rail_retire', value: 7098000},
+ {source: 'payroll_tax', target: 'opm', value: 5026000},
+];
+
+const budgetColumns = [
+ {
+ ids: [
+ 'income_tax',
+ 'payroll_tax',
+ 'corp_tax',
+ 'excise_tax',
+ 'misc_revenue',
+ 'customs',
+ 'proposals',
+ 'estate_tax',
+ ],
+ label: 'Revenue Source',
+ },
+ {
+ ids: [
+ 'general_fund',
+ 'social_security',
+ 'hhs',
+ 'treasury',
+ 'labor',
+ 'transport',
+ 'agriculture',
+ 'fcc',
+ 'rail_retire',
+ 'opm',
+ ],
+ label: 'Receiving Agency',
+ },
+];
+
+function formatBudget(value: number): string {
+ if (value >= 1_000_000_000)
+ return '$' + (value / 1_000_000_000).toFixed(1) + 'T';
+ if (value >= 1_000_000) return '$' + Math.round(value / 1_000_000) + 'B';
+ if (value >= 1_000) return '$' + Math.round(value / 1_000) + 'M';
+ return '$' + value.toLocaleString();
+}
+
+/**
+ * Real data: US Federal Budget FY2020 from vega-datasets.
+ * Tax revenue sources flowing to receiving government agencies.
+ */
+export const USFederalBudget: Story = {
+ render: () => (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>US Federal Budget FY2020</XDSHeading>
+ <XDSText type="body" color="secondary">
+ Revenue sources → receiving agencies (vega-datasets/budget.json)
+ </XDSText>
+ <XDSSankeyChart
+ nodes={budgetNodes}
+ links={budgetLinks}
+ columns={budgetColumns}
+ height={480}>
+ <XDSSankeyGrid />
+ <XDSSankeyLink opacity={0.6} tension={0.5} />
+ <XDSSankeyNode />
+ <XDSSankeyLabel formatValue={formatBudget} />
+ </XDSSankeyChart>
+ </XDSStack>
+ ),
+};
+
+// --- Color modes ---
+
+/** Monochrome — flat black ribbons on white, editorial style */
+export const Monochrome: Story = {
+ render: () => (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Petroleum Flow</XDSHeading>
+ <XDSText type="body" color="secondary">
+ Monochrome — flat color, no gradients
+ </XDSText>
+ <XDSSankeyChart
+ nodes={funnelNodes}
+ links={funnelLinks}
+ columns={funnelColumns}
+ height={340}
+ nodeColor="#1a1a1e">
+ <XDSSankeyLink color="#1a1a1e" opacity={0.75} />
+ <XDSSankeyNode glow={false} />
+ <XDSSankeyLabel />
+ </XDSSankeyChart>
+ </XDSStack>
+ ),
+};
+
+/** Source-colored — each link takes its source node's color */
+export const SourceColored: Story = {
+ render: () => (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Source-Colored Links</XDSHeading>
+ <XDSText type="body" color="secondary">
+ Each ribbon matches its source node
+ </XDSText>
+ <XDSSankeyChart
+ nodes={funnelNodes}
+ links={funnelLinks}
+ columns={funnelColumns}
+ height={340}>
+ <XDSSankeyGrid />
+ <XDSSankeyLink color="source" />
+ <XDSSankeyNode />
+ <XDSSankeyLabel />
+ </XDSSankeyChart>
+ </XDSStack>
+ ),
+};
+
+/** Target-colored — each link takes its target node's color */
+export const TargetColored: Story = {
+ render: () => (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Target-Colored Links</XDSHeading>
+ <XDSText type="body" color="secondary">
+ Each ribbon matches its destination node
+ </XDSText>
+ <XDSSankeyChart
+ nodes={funnelNodes}
+ links={funnelLinks}
+ columns={funnelColumns}
+ height={340}>
+ <XDSSankeyGrid />
+ <XDSSankeyLink color="target" />
+ <XDSSankeyNode />
+ <XDSSankeyLabel />
+ </XDSSankeyChart>
+ </XDSStack>
+ ),
+};
+
+/** Leaned gradient — source-biased, transitions late */
+export const LeanedSourceGradient: Story = {
+ render: () => (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Source-Leaned Gradient</XDSHeading>
+ <XDSText type="body" color="secondary">
+ bias=0.2 — holds source color, transitions near target
+ </XDSText>
+ <XDSSankeyChart
+ nodes={funnelNodes}
+ links={funnelLinks}
+ columns={funnelColumns}
+ height={340}>
+ <XDSSankeyGrid />
+ <XDSSankeyLink color={{gradient: 0.2}} />
+ <XDSSankeyNode />
+ <XDSSankeyLabel />
+ </XDSSankeyChart>
+ </XDSStack>
+ ),
+};
+
+/** Leaned gradient — target-biased, transitions early */
+export const LeanedTargetGradient: Story = {
+ render: () => (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Target-Leaned Gradient</XDSHeading>
+ <XDSText type="body" color="secondary">
+ bias=0.8 — transitions early, holds target color
+ </XDSText>
+ <XDSSankeyChart
+ nodes={funnelNodes}
+ links={funnelLinks}
+ columns={funnelColumns}
+ height={340}>
+ <XDSSankeyGrid />
+ <XDSSankeyLink color={{gradient: 0.8}} />
+ <XDSSankeyNode />
+ <XDSSankeyLabel />
+ </XDSSankeyChart>
+ </XDSStack>
+ ),
+};
diff --git a/packages/lab/src/Sankey/SankeyContext.ts b/packages/lab/src/Sankey/SankeyContext.ts
new file mode 100644
index 0000000000..736e755c41
--- /dev/null
+++ b/packages/lab/src/Sankey/SankeyContext.ts
@@ -0,0 +1,21 @@
+/**
+ * @file SankeyContext.ts
+ * @output React context for sharing Sankey layout between components
+ * @position Consumed by XDSSankeyChart (provider) and all child components (consumers)
+ */
+
+import {createContext, useContext} from 'react';
+import type {SankeyContext} from './types';
+
+const SankeyCtx = createContext<SankeyContext | null>(null);
+
+export const SankeyProvider = SankeyCtx.Provider;
+
+/** Access the sankey context. Throws if used outside <XDSSankeyChart>. */
+export function useSankey(): SankeyContext {
+ const ctx = useContext(SankeyCtx);
+ if (!ctx) {
+ throw new Error('Sankey components must be used inside <XDSSankeyChart>');
+ }
+ return ctx;
+}
diff --git a/packages/lab/src/Sankey/XDSSankeyChart.tsx b/packages/lab/src/Sankey/XDSSankeyChart.tsx
new file mode 100644
index 0000000000..46bd455de4
--- /dev/null
+++ b/packages/lab/src/Sankey/XDSSankeyChart.tsx
@@ -0,0 +1,210 @@
+/**
+ * @file XDSSankeyChart.tsx
+ * @output Root Sankey container — computes layout and provides context
+ * @position Parent component; all Sankey marks are children
+ *
+ * When columns × minColumnWidth exceeds the container, the chart
+ * scrolls horizontally rather than squishing columns together.
+ */
+
+import {
+ type ReactNode,
+ useMemo,
+ useRef,
+ useState,
+ useLayoutEffect,
+} from 'react';
+import {SankeyProvider} from './SankeyContext';
+import {computeLayout} from './layout';
+import type {
+ SankeyNode,
+ SankeyLink,
+ SankeyColumn,
+ SankeyColumnDef,
+} from './types';
+
+export interface XDSSankeyChartProps {
+ /** Node definitions */
+ nodes: SankeyNode[];
+ /** Link definitions */
+ links: SankeyLink[];
+ /**
+ * Column definitions. Accepts either:
+ * - Simple: `string[][]` — arrays of node IDs per column
+ * - Rich: `SankeyColumnDef[]` — objects with `ids`, optional `label`
+ * - Mixed: any combination
+ *
+ * If omitted, columns are auto-detected via topological sort.
+ */
+ columns?: SankeyColumn[];
+ /** Chart height in px (default: 320) */
+ height?: number;
+ /** Node bar width in px (default: 20) */
+ nodeWidth?: number;
+ /** Vertical gap between sibling nodes (default: 14) */
+ nodeGap?: number;
+ /**
+ * Override all node bar colors with a single CSS color.
+ * Both XDSSankeyNode and XDSSankeyLabel read this from context
+ * so labels adapt their text color for contrast.
+ */
+ nodeColor?: string;
+ /**
+ * Minimum width per column in px (default: 160).
+ * When total min width exceeds the container, horizontal scrolling activates.
+ */
+ minColumnWidth?: number;
+ /** Chart contents */
+ children: ReactNode;
+}
+
+/** Resolve column count from raw column input or auto-detect from graph */
+function resolveColumnCount(
+ columns: SankeyColumn[] | undefined,
+ nodes: SankeyNode[],
+ links: SankeyLink[],
+): number {
+ if (columns) return columns.length;
+ // Quick topological column count
+ const inDegree = new Map<string, number>();
+ const outEdges = new Map<string, string[]>();
+ nodes.forEach(n => {
+ inDegree.set(n.id, 0);
+ outEdges.set(n.id, []);
+ });
+ links.forEach(l => {
+ inDegree.set(l.target, (inDegree.get(l.target) || 0) + 1);
+ outEdges.get(l.source)?.push(l.target);
+ });
+ const colMap = new Map<string, number>();
+ const queue: string[] = [];
+ nodes.forEach(n => {
+ if (inDegree.get(n.id) === 0) {
+ queue.push(n.id);
+ colMap.set(n.id, 0);
+ }
+ });
+ while (queue.length) {
+ const id = queue.shift()!;
+ const col = colMap.get(id)!;
+ for (const tgt of outEdges.get(id) || []) {
+ colMap.set(tgt, Math.max(colMap.get(tgt) || 0, col + 1));
+ inDegree.set(tgt, (inDegree.get(tgt) || 0) - 1);
+ if (inDegree.get(tgt) === 0) queue.push(tgt);
+ }
+ }
+ return Math.max(...Array.from(colMap.values()), 0) + 1;
+}
+
+/**
+ * Root component for Sankey/flow diagrams.
+ *
+ * Computes layout from nodes + links, exposes positions via context.
+ * Width is responsive but enforces minColumnWidth — scrolls when needed.
+ *
+ * @example
+ * ```tsx
+ * <XDSSankeyChart
+ * nodes={nodes}
+ * links={links}
+ * columns={[
+ * {ids: ['a', 'b'], label: 'Source'},
+ * {ids: ['c', 'd'], label: 'Target'},
+ * ]}
+ * >
+ * <XDSSankeyGrid />
+ * <XDSSankeyLink />
+ * <XDSSankeyNode />
+ * <XDSSankeyLabel />
+ * </XDSSankeyChart>
+ * ```
+ */
+export function XDSSankeyChart({
+ nodes,
+ links,
+ columns,
+ height = 320,
+ nodeWidth = 20,
+ nodeGap = 14,
+ nodeColor,
+ minColumnWidth = 160,
+ children,
+}: XDSSankeyChartProps) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [containerWidth, setContainerWidth] = useState(0);
+
+ useLayoutEffect(() => {
+ const el = containerRef.current;
+ if (!el) return;
+ const ro = new ResizeObserver(entries => {
+ const w = entries[0]?.contentRect.width ?? 0;
+ setContainerWidth(w);
+ });
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+
+ const colCount = useMemo(
+ () => resolveColumnCount(columns, nodes, links),
+ [columns, nodes, links],
+ );
+
+ const minWidth = colCount * minColumnWidth;
+ const chartWidth = Math.max(containerWidth, minWidth);
+ const needsScroll = containerWidth > 0 && chartWidth > containerWidth;
+
+ const layout = useMemo(() => {
+ if (containerWidth === 0) return null;
+ return computeLayout(nodes, links, {
+ width: chartWidth,
+ height,
+ nodeWidth,
+ nodeGap,
+ columns,
+ });
+ }, [
+ nodes,
+ links,
+ chartWidth,
+ height,
+ nodeWidth,
+ nodeGap,
+ columns,
+ containerWidth,
+ ]);
+
+ const ctx = useMemo(() => {
+ if (!layout) return null;
+ return {
+ nodes: layout.nodes,
+ links: layout.links,
+ columns: layout.columns,
+ width: chartWidth,
+ height,
+ valueScale: layout.valueScale,
+ maxValue: layout.maxValue,
+ nodeWidth,
+ nodeColor,
+ };
+ }, [layout, chartWidth, height, nodeWidth, nodeColor]);
+
+ return (
+ <div ref={containerRef} style={{width: '100%'}}>
+ {ctx && (
+ <div
+ style={
+ needsScroll ? {overflowX: 'auto', overflowY: 'hidden'} : undefined
+ }>
+ <svg
+ width={chartWidth}
+ height={height}
+ style={{overflow: 'visible', display: 'block'}}>
+ <SankeyProvider value={ctx}>{children}</SankeyProvider>
+ </svg>
+ </div>
+ )}
+ </div>
+ );
+}
+
+XDSSankeyChart.displayName = 'XDSSankeyChart';
diff --git a/packages/lab/src/Sankey/XDSSankeyGrid.tsx b/packages/lab/src/Sankey/XDSSankeyGrid.tsx
new file mode 100644
index 0000000000..27d9826583
--- /dev/null
+++ b/packages/lab/src/Sankey/XDSSankeyGrid.tsx
@@ -0,0 +1,67 @@
+/**
+ * @file XDSSankeyGrid.tsx
+ * @output Dashed vertical lines at each column + optional column headers
+ * @position Visual layer — structural guide behind the flow ribbons
+ */
+
+import {useSankey} from './SankeyContext';
+
+export interface XDSSankeyGridProps {
+ /** Dash pattern (default: "4 4") */
+ dashArray?: string;
+ /** Stroke color (default: theme border) */
+ color?: string;
+ /** Opacity (default: 0.3) */
+ opacity?: number;
+ /** Show column header labels if defined (default: true) */
+ showHeaders?: boolean;
+}
+
+/**
+ * Vertical grid lines at each column position, with optional column headers.
+ *
+ * Place before XDSSankeyLink so grid renders behind ribbons.
+ */
+export function XDSSankeyGrid({
+ dashArray = '4 4',
+ color,
+ opacity = 0.3,
+ showHeaders = true,
+}: XDSSankeyGridProps) {
+ const {columns, height, nodeWidth} = useSankey();
+
+ return (
+ <g>
+ {columns.map((col, i) => (
+ <g key={i}>
+ <line
+ x1={col.x + nodeWidth / 2}
+ x2={col.x + nodeWidth / 2}
+ y1={0}
+ y2={height}
+ stroke={color || 'var(--color-border, #d0d0d8)'}
+ strokeOpacity={opacity}
+ strokeDasharray={dashArray}
+ strokeWidth={1}
+ />
+ {showHeaders && col.label && (
+ <text
+ x={col.x + nodeWidth / 2}
+ y={height - 2}
+ textAnchor="middle"
+ style={{
+ font: '500 10px/1 system-ui',
+ fill: 'var(--color-text-secondary, #6e6e80)',
+ textTransform: 'uppercase',
+ letterSpacing: '0.04em',
+ }}>
+ {col.label}
+ </text>
+ )}
+ </g>
+ ))}
+ </g>
+ );
+}
+
+XDSSankeyGrid.displayName = 'XDSSankeyGrid';
diff --git a/packages/lab/src/Sankey/XDSSankeyLabel.tsx b/packages/lab/src/Sankey/XDSSankeyLabel.tsx
new file mode 100644
index 0000000000..6bff2ba964
--- /dev/null
+++ b/packages/lab/src/Sankey/XDSSankeyLabel.tsx
@@ -0,0 +1,227 @@
+/**
+ * @file XDSSankeyLabel.tsx
+ * @output Renders node labels — rotated on bar or beside it based on fit
+ * @position Visual layer — adapts placement for readability at every scale
+ *
+ * Two strategies based on available space:
+ * - Tall nodes: rotated -90° text directly on the bar (no background)
+ * - Short nodes: horizontal label beside the bar with surface pill
+ *
+ * Last-column labels anchor to the left to avoid clipping at the chart edge.
+ * Text on bars uses --color-on-dark/--color-on-light from XDSMediaTheme.
+ */
+
+import {useSankey} from './SankeyContext';
+
+export interface XDSSankeyLabelProps {
+ /** Show percentage below the node (default: true) */
+ showPercent?: boolean;
+ /** Format function for the value (default: compact notation) */
+ formatValue?: (value: number) => string;
+}
+
+function defaultFormat(value: number): string {
+ if (value >= 10000) return Math.round(value / 1000) + 'k';
+ if (value >= 1000) return (value / 1000).toFixed(1) + 'k';
+ return value.toLocaleString();
+}
+
+/**
+ * On-surface text color. When a CSS color override is active, parse its
+ * perceived lightness. For oklch tuples, use the L channel directly.
+ */
+function onSurfaceColor(
+ color: [number, number, number],
+ cssOverride?: string,
+): string {
+ if (cssOverride) {
+ // Quick heuristic: if the override looks dark, use on-dark
+ // Check for common dark patterns (#1, #0, rgb(0-80,...), black, etc.)
+ const c = cssOverride.toLowerCase().trim();
+ const isDark =
+ c === 'black' ||
+ /^#[0-3]/.test(c) ||
+ /^#.[0-3]/.test(c) ||
+ /^rgb\(\s*[0-7]\d?\s*,/.test(c);
+ return isDark
+ ? 'var(--color-on-dark, #fff)'
+ : 'var(--color-on-light, #000)';
+ }
+ return color[0] < 0.6
+ ? 'var(--color-on-dark, #fff)'
+ : 'var(--color-on-light, #000)';
+}
+
+export function XDSSankeyLabel({
+ showPercent = true,
+ formatValue = defaultFormat,
+}: XDSSankeyLabelProps) {
+ const {nodes, columns, maxValue, height, nodeWidth, nodeColor} = useSankey();
+ const lastColumn = columns.length - 1;
+
+ return (
+ <g>
+ {nodes.map(node => {
+ const pct = (node.value / maxValue) * 100;
+ const pctStr = pct >= 10 ? Math.round(pct) + '%' : pct.toFixed(1) + '%';
+ const formatted = formatValue(node.value);
+ const text = `${node.label} = ${formatted}`;
+
+ const textWidth = text.length * 6.5;
+ const fitsRotated = node.height >= textWidth + 8;
+
+ if (fitsRotated) {
+ return (
+ <RotatedLabel
+ key={node.id}
+ node={node}
+ nodeWidth={nodeWidth}
+ nodeColor={nodeColor}
+ text={text}
+ pctStr={pctStr}
+ showPercent={showPercent}
+ height={height}
+ />
+ );
+ }
+
+ return (
+ <BesideLabel
+ key={node.id}
+ node={node}
+ nodeWidth={nodeWidth}
+ text={text}
+ pctStr={pctStr}
+ showPercent={showPercent}
+ height={height}
+ isLastColumn={node.column === lastColumn}
+ />
+ );
+ })}
+ </g>
+ );
+}
+
+/** Tall bars: rotated text directly on the bar, no background */
+function RotatedLabel({
+ node,
+ nodeWidth,
+ nodeColor,
+ text,
+ pctStr,
+ showPercent,
+ height,
+}: {
+ node: import('./types').SankeyNodeLayout;
+ nodeWidth: number;
+ nodeColor?: string;
+ text: string;
+ pctStr: string;
+ showPercent: boolean;
+ height: number;
+}) {
+ const cx = node.x + nodeWidth / 2;
+ const cy = node.y + node.height / 2;
+
+ return (
+ <g>
+ <g transform={`translate(${cx}, ${cy}) rotate(-90)`}>
+ <text
+ x={0}
+ y={0}
+ textAnchor="middle"
+ dominantBaseline="central"
+ style={{
+ font: '600 10px/1 system-ui',
+ fill: onSurfaceColor(node.color, nodeColor),
+ letterSpacing: '-0.01em',
+ }}>
+ {text}
+ </text>
+ </g>
+ {showPercent && node.column > 0 && (
+ <text
+ x={cx}
+ y={Math.min(height - 2, node.y + node.height + 12)}
+ textAnchor="middle"
+ style={{
+ font: '500 9px/1 system-ui',
+ fill: 'var(--color-text-tertiary, #8e8ea0)',
+ }}>
+ {pctStr}
+ </text>
+ )}
+ </g>
+ );
+}
+
+/**
+ * Short bars: label beside the node with surface pill.
+ * Last column labels go to the left to avoid clipping.
+ */
+function BesideLabel({
+ node,
+ nodeWidth,
+ text,
+ pctStr,
+ showPercent,
+ height,
+ isLastColumn,
+}: {
+ node: import('./types').SankeyNodeLayout;
+ nodeWidth: number;
+ text: string;
+ pctStr: string;
+ showPercent: boolean;
+ height: number;
+ isLastColumn: boolean;
+}) {
+ const cx = node.x + nodeWidth / 2;
+ const cy = node.y + node.height / 2;
+ const pillW = text.length * 6 + 10;
+ const pillH = 16;
+
+ const labelX = isLastColumn ? node.x - 6 : node.x + nodeWidth + 6;
+ const pillX = isLastColumn ? labelX - pillW + 4 : labelX - 4;
+ const textAnchor = isLastColumn ? 'end' : 'start';
+
+ return (
+ <g>
+ <rect
+ x={pillX}
+ y={cy - pillH / 2}
+ width={pillW}
+ height={pillH}
+ rx={3}
+ fill="var(--color-background-surface, #fff)"
+ fillOpacity={0.9}
+ />
+ <text
+ x={labelX}
+ y={cy}
+ textAnchor={textAnchor}
+ dominantBaseline="central"
+ style={{
+ font: '600 10px/1 system-ui',
+ fill: 'var(--color-text-primary, #1c1c1e)',
+ letterSpacing: '-0.01em',
+ }}>
+ {text}
+ </text>
+ {showPercent && node.column > 0 && (
+ <text
+ x={cx}
+ y={Math.min(height - 2, node.y + node.height + 12)}
+ textAnchor="middle"
+ style={{
+ font: '500 9px/1 system-ui',
+ fill: 'var(--color-text-tertiary, #8e8ea0)',
+ }}>
+ {pctStr}
+ </text>
+ )}
+ </g>
+ );
+}
+
+XDSSankeyLabel.displayName = 'XDSSankeyLabel';
diff --git a/packages/lab/src/Sankey/XDSSankeyLink.tsx b/packages/lab/src/Sankey/XDSSankeyLink.tsx
new file mode 100644
index 0000000000..3686a7fdfd
--- /dev/null
+++ b/packages/lab/src/Sankey/XDSSankeyLink.tsx
@@ -0,0 +1,159 @@
+/**
+ * @file XDSSankeyLink.tsx
+ * @output Renders flow ribbons with configurable color modes
+ * @position Visual layer — the colorful flowing areas between nodes
+ *
+ * Color modes: flat CSS string, 'source', 'target', 'gradient',
+ * or {gradient: bias} for leaned transitions.
+ */
+
+import {useSankey} from './SankeyContext';
+import type {SankeyLinkLayout} from './types';
+
+/**
+ * Link color mode:
+ * - `'gradient'` — even transition from source to target color
+ * - `'source'` — each link uses its source node's color
+ * - `'target'` — each link uses its target node's color
+ * - `{gradient: number}` — biased gradient (0–1). 0.2 = source-leaned, 0.8 = target-leaned
+ * - `string` — any CSS color for flat uniform fill
+ */
+export type SankeyLinkColor =
+ | 'gradient'
+ | 'source'
+ | 'target'
+ | {gradient: number}
+ | (string & {});
+
+export interface XDSSankeyLinkProps {
+ /** Link coloring mode (default: 'gradient') */
+ color?: SankeyLinkColor;
+ /** Opacity of the link fills (default: 0.7) */
+ opacity?: number;
+ /** Bezier tension — 0 is straight, 1 is maximum curve (default: 0.5) */
+ tension?: number;
+}
+
+function oklch(c: [number, number, number], alpha: number): string {
+ return `oklch(${c[0]} ${c[1]} ${c[2]} / ${alpha})`;
+}
+
+type ResolvedMode =
+ | {type: 'flat'; value: string}
+ | {type: 'source'}
+ | {type: 'target'}
+ | {type: 'gradient'; bias: number};
+
+function resolveColor(color: SankeyLinkColor): ResolvedMode {
+ if (typeof color === 'object' && 'gradient' in color) {
+ return {type: 'gradient', bias: color.gradient};
+ }
+ if (color === 'gradient') return {type: 'gradient', bias: 0.5};
+ if (color === 'source') return {type: 'source'};
+ if (color === 'target') return {type: 'target'};
+ return {type: 'flat', value: color};
+}
+
+/**
+ * Renders all link ribbons in the Sankey chart.
+ *
+ * Place before XDSSankeyNode so nodes render on top.
+ */
+export function XDSSankeyLink({
+ color = 'gradient',
+ opacity = 0.7,
+ tension = 0.5,
+}: XDSSankeyLinkProps) {
+ const {links} = useSankey();
+ const mode = resolveColor(color);
+
+ return (
+ <g>
+ {mode.type === 'gradient' && (
+ <defs>
+ {links.map((link, i) => (
+ <GradientDef
+ key={i}
+ index={i}
+ link={link}
+ opacity={opacity}
+ bias={mode.bias}
+ />
+ ))}
+ </defs>
+ )}
+ {links.map((link, i) => {
+ const sx = link.source.x + link.source.width;
+ const tx = link.target.x;
+ const sy = link.sourceY;
+ const ty = link.targetY;
+ const lh = link.height;
+ const dx = (tx - sx) * tension;
+
+ const d = [
+ `M${sx},${sy}`,
+ `C${sx + dx},${sy} ${tx - dx},${ty} ${tx},${ty}`,
+ `L${tx},${ty + lh}`,
+ `C${tx - dx},${ty + lh} ${sx + dx},${sy + lh} ${sx},${sy + lh}`,
+ 'Z',
+ ].join(' ');
+
+ let fill: string;
+ let pathOpacity: number | undefined;
+ if (mode.type === 'flat') {
+ fill = mode.value;
+ pathOpacity = opacity;
+ } else if (mode.type === 'source') {
+ fill = oklch(link.source.color, opacity);
+ } else if (mode.type === 'target') {
+ fill = oklch(link.target.color, opacity);
+ } else {
+ fill = `url(#xds-sankey-grad-${i})`;
+ }
+
+ return <path key={i} d={d} fill={fill} opacity={pathOpacity} />;
+ })}
+ </g>
+ );
+}
+
+/** Gradient definition with bias-adjusted stops */
+function GradientDef({
+ index,
+ link,
+ opacity,
+ bias,
+}: {
+ index: number;
+ link: SankeyLinkLayout;
+ opacity: number;
+ bias: number;
+}) {
+ const sx = link.source.x + link.source.width;
+ const tx = link.target.x;
+ const s1 = Math.max(0, bias - 0.15);
+ const s2 = Math.min(1, bias + 0.15);
+
+ return (
+ <linearGradient
+ id={`xds-sankey-grad-${index}`}
+ x1={sx}
+ x2={tx}
+ y1={0}
+ y2={0}
+ gradientUnits="userSpaceOnUse">
+ <stop offset="0%" stopColor={oklch(link.source.color, opacity)} />
+ <stop
+ offset={`${s1 * 100}%`}
+ stopColor={oklch(link.source.color, opacity * 0.9)}
+ />
+ <stop
+ offset={`${s2 * 100}%`}
+ stopColor={oklch(link.target.color, opacity * 0.9)}
+ />
+ <stop offset="100%" stopColor={oklch(link.target.color, opacity)} />
+ </linearGradient>
+ );
+}
+
+XDSSankeyLink.displayName = 'XDSSankeyLink';
diff --git a/packages/lab/src/Sankey/XDSSankeyNode.tsx b/packages/lab/src/Sankey/XDSSankeyNode.tsx
new file mode 100644
index 0000000000..1121b2fdad
--- /dev/null
+++ b/packages/lab/src/Sankey/XDSSankeyNode.tsx
@@ -0,0 +1,64 @@
+/**
+ * @file XDSSankeyNode.tsx
+ * @output Renders node indicators with optional glow
+ * @position Visual layer — node bars that labels sit on
+ *
+ * Reads nodeColor from chart context. When set, all nodes use that color.
+ * Otherwise, uses each node's individual oklch color from data.
+ */
+
+import {useSankey} from './SankeyContext';
+
+export interface XDSSankeyNodeProps {
+ /** Whether to show the glow effect behind nodes (default: true) */
+ glow?: boolean;
+}
+
+function oklch(c: [number, number, number], alpha: number): string {
+ return `oklch(${c[0]} ${c[1]} ${c[2]} / ${alpha})`;
+}
+
+/**
+ * Renders all node indicators in the Sankey chart.
+ *
+ * Color comes from the chart's `nodeColor` prop (global override)
+ * or each node's individual color from data.
+ */
+export function XDSSankeyNode({glow = true}: XDSSankeyNodeProps) {
+ const {nodes, nodeColor} = useSankey();
+
+ return (
+ <g>
+ {nodes.map(node => {
+ const fill = nodeColor || oklch(node.color, 0.9);
+ const glowFill = nodeColor || oklch(node.color, 0.12);
+
+ return (
+ <g key={node.id}>
+ {glow && (
+ <rect
+ x={node.x - 3}
+ y={node.y - 1}
+ width={node.width + 6}
+ height={node.height + 2}
+ rx={4}
+ fill={glowFill}
+ opacity={nodeColor ? 0.12 : 1}
+ />
+ )}
+ <rect
+ x={node.x}
+ y={node.y}
+ width={node.width}
+ height={node.height}
+ rx={1.5}
+ fill={fill}
+ />
+ </g>
+ );
+ })}
+ </g>
+ );
+}
+
+XDSSankeyNode.displayName = 'XDSSankeyNode';
diff --git a/packages/lab/src/Sankey/index.ts b/packages/lab/src/Sankey/index.ts
new file mode 100644
index 0000000000..caef1602c3
--- /dev/null
+++ b/packages/lab/src/Sankey/index.ts
@@ -0,0 +1,20 @@
+export {XDSSankeyChart, type XDSSankeyChartProps} from './XDSSankeyChart';
+export {
+ XDSSankeyLink,
+ type XDSSankeyLinkProps,
+ type SankeyLinkColor,
+} from './XDSSankeyLink';
+export {XDSSankeyNode, type XDSSankeyNodeProps} from './XDSSankeyNode';
+export {XDSSankeyLabel, type XDSSankeyLabelProps} from './XDSSankeyLabel';
+export {XDSSankeyGrid, type XDSSankeyGridProps} from './XDSSankeyGrid';
+export {useSankey} from './SankeyContext';
+export type {
+ SankeyNode,
+ SankeyLink,
+ SankeyColumn,
+ SankeyColumnDef,
+ SankeyNodeLayout,
+ SankeyLinkLayout,
+ SankeyColumnLayout,
+ SankeyContext,
+} from './types';
diff --git a/packages/lab/src/Sankey/layout.ts b/packages/lab/src/Sankey/layout.ts
new file mode 100644
index 0000000000..8d67de77d8
--- /dev/null
+++ b/packages/lab/src/Sankey/layout.ts
@@ -0,0 +1,203 @@
+/**
+ * @file layout.ts
+ * @output Pure layout algorithm — computes node and link positions
+ * @position Core logic; consumed by XDSSankeyChart during render
+ *
+ * Accepts columns as either string[][] (simple) or SankeyColumnDef[]
+ * (with labels). Reserves margin for labels and column headers.
+ */
+
+import type {
+ SankeyNode,
+ SankeyLink,
+ SankeyColumn,
+ SankeyColumnDef,
+ SankeyNodeLayout,
+ SankeyLinkLayout,
+ SankeyColumnLayout,
+} from './types';
+
+const DEFAULT_PALETTE: Array<[number, number, number]> = [
+ [0.65, 0.2, 270],
+ [0.6, 0.17, 235],
+ [0.62, 0.16, 190],
+ [0.64, 0.18, 155],
+ [0.58, 0.15, 40],
+ [0.55, 0.14, 350],
+ [0.54, 0.15, 20],
+ [0.56, 0.13, 300],
+];
+
+export interface LayoutOptions {
+ width: number;
+ height: number;
+ nodeWidth?: number;
+ nodeGap?: number;
+ labelMargin?: number;
+ columns?: SankeyColumn[];
+}
+
+/** Normalize column input to the rich format */
+function normalizeColumns(cols: SankeyColumn[]): SankeyColumnDef[] {
+ return cols.map(c => (Array.isArray(c) ? {ids: c} : c));
+}
+
+function autoColumns(
+ nodes: SankeyNode[],
+ links: SankeyLink[],
+): SankeyColumnDef[] {
+ const inDegree = new Map<string, number>();
+ const outEdges = new Map<string, string[]>();
+ nodes.forEach(n => {
+ inDegree.set(n.id, 0);
+ outEdges.set(n.id, []);
+ });
+ links.forEach(l => {
+ inDegree.set(l.target, (inDegree.get(l.target) || 0) + 1);
+ outEdges.get(l.source)?.push(l.target);
+ });
+
+ const colMap = new Map<string, number>();
+ const queue: string[] = [];
+ nodes.forEach(n => {
+ if (inDegree.get(n.id) === 0) {
+ queue.push(n.id);
+ colMap.set(n.id, 0);
+ }
+ });
+
+ while (queue.length) {
+ const id = queue.shift()!;
+ const col = colMap.get(id)!;
+ for (const tgt of outEdges.get(id) || []) {
+ const newCol = col + 1;
+ colMap.set(tgt, Math.max(colMap.get(tgt) || 0, newCol));
+ inDegree.set(tgt, (inDegree.get(tgt) || 0) - 1);
+ if (inDegree.get(tgt) === 0) queue.push(tgt);
+ }
+ }
+
+ const maxCol = Math.max(...Array.from(colMap.values()), 0);
+ const columns: SankeyColumnDef[] = Array.from({length: maxCol + 1}, () => ({
+ ids: [] as string[],
+ }));
+ nodes.forEach(n => {
+ columns[colMap.get(n.id) || 0].ids.push(n.id);
+ });
+ return columns;
+}
+
+export interface LayoutResult {
+ nodes: SankeyNodeLayout[];
+ links: SankeyLinkLayout[];
+ columns: SankeyColumnLayout[];
+ valueScale: number;
+ maxValue: number;
+}
+
+export function computeLayout(
+ nodes: SankeyNode[],
+ links: SankeyLink[],
+ options: LayoutOptions,
+): LayoutResult {
+ const {
+ width,
+ height,
+ nodeWidth = 20,
+ nodeGap = 14,
+ labelMargin = 28,
+ } = options;
+
+ const colDefs = options.columns
+ ? normalizeColumns(options.columns)
+ : autoColumns(nodes, links);
+ const colCount = colDefs.length;
+ const hasHeaders = colDefs.some(c => c.label);
+ const headerMargin = hasHeaders ? 20 : 0;
+
+ const nodeMap = new Map<string, SankeyNode>();
+ nodes.forEach(n => nodeMap.set(n.id, n));
+
+ // Usable height after reserving space for labels and headers
+ const usableHeight = height - labelMargin - 16 - headerMargin;
+
+ // Scale based on largest column
+ let maxColValue = 0;
+ colDefs.forEach(col => {
+ const total = col.ids.reduce(
+ (s, id) => s + (nodeMap.get(id)?.value || 0),
+ 0,
+ );
+ if (total > maxColValue) maxColValue = total;
+ });
+
+ const maxNodes = Math.max(...colDefs.map(c => c.ids.length));
+ const valueScale = (usableHeight - (maxNodes - 1) * nodeGap) / maxColValue;
+ const colSpacing = colCount > 1 ? (width - nodeWidth) / (colCount - 1) : 0;
+
+ const columnLayouts: SankeyColumnLayout[] = [];
+ const layoutNodes = new Map<string, SankeyNodeLayout>();
+ let colorIdx = 0;
+
+ colDefs.forEach((col, ci) => {
+ const x = ci * colSpacing;
+ columnLayouts.push({x, label: col.label, ids: col.ids});
+
+ const totalH = col.ids.reduce(
+ (s, id) => s + (nodeMap.get(id)?.value || 0) * valueScale,
+ 0,
+ );
+ const totalGap = (col.ids.length - 1) * nodeGap;
+ let y = labelMargin + (usableHeight - totalH - totalGap) / 2;
+
+ col.ids.forEach(id => {
+ const node = nodeMap.get(id);
+ if (!node) return;
+ const h = node.value * valueScale;
+ const color =
+ node.color || DEFAULT_PALETTE[colorIdx % DEFAULT_PALETTE.length];
+ colorIdx++;
+
+ layoutNodes.set(id, {
+ id,
+ label: node.label,
+ value: node.value,
+ color,
+ x,
+ y,
+ width: nodeWidth,
+ height: h,
+ column: ci,
+ _sourceOffset: 0,
+ _targetOffset: 0,
+ });
+ y += h + nodeGap;
+ });
+ });
+
+ const layoutLinks: SankeyLinkLayout[] = links.map(link => {
+ const src = layoutNodes.get(link.source)!;
+ const tgt = layoutNodes.get(link.target)!;
+ const lh = link.value * valueScale;
+ const sourceY = src.y + src._sourceOffset;
+ const targetY = tgt.y + tgt._targetOffset;
+ src._sourceOffset += lh;
+ tgt._targetOffset += lh;
+ return {
+ source: src,
+ target: tgt,
+ value: link.value,
+ height: lh,
+ sourceY,
+ targetY,
+ };
+ });
+
+ return {
+ nodes: Array.from(layoutNodes.values()),
+ links: layoutLinks,
+ columns: columnLayouts,
+ valueScale,
+ maxValue: maxColValue,
+ };
+}
diff --git a/packages/lab/src/Sankey/types.ts b/packages/lab/src/Sankey/types.ts
new file mode 100644
index 0000000000..b89b27a5d3
--- /dev/null
+++ b/packages/lab/src/Sankey/types.ts
@@ -0,0 +1,91 @@
+/**
+ * @file types.ts
+ * @output Sankey chart types — nodes, links, layout, and context
+ * @position Foundation types consumed by all Sankey sub-components
+ */
+
+/** A node in the Sankey diagram */
+export interface SankeyNode {
+ /** Unique identifier */
+ id: string;
+ /** Display label */
+ label: string;
+ /** Total value flowing through this node */
+ value: number;
+ /** Color in oklch format [lightness, chroma, hue] */
+ color?: [number, number, number];
+}
+
+/** A link (flow) between two nodes */
+export interface SankeyLink {
+ /** Source node ID */
+ source: string;
+ /** Target node ID */
+ target: string;
+ /** Flow value */
+ value: number;
+}
+
+/**
+ * Column definition.
+ * Simple form: string[] (just node IDs).
+ * Rich form: object with IDs, optional label, and type.
+ */
+export interface SankeyColumnDef {
+ /** Node IDs in this column */
+ ids: string[];
+ /** Column header label (rendered below the column) */
+ label?: string;
+}
+
+/** Columns can be simple string arrays or rich definitions */
+export type SankeyColumn = string[] | SankeyColumnDef;
+
+/** Computed layout position for a node */
+export interface SankeyNodeLayout {
+ id: string;
+ label: string;
+ value: number;
+ color: [number, number, number];
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ column: number;
+ _sourceOffset: number;
+ _targetOffset: number;
+}
+
+/** Computed layout position for a link */
+export interface SankeyLinkLayout {
+ source: SankeyNodeLayout;
+ target: SankeyNodeLayout;
+ value: number;
+ height: number;
+ sourceY: number;
+ targetY: number;
+}
+
+/** Resolved column info exposed to children */
+export interface SankeyColumnLayout {
+ /** X position of this column */
+ x: number;
+ /** Column header label (if provided) */
+ label?: string;
+ /** Node IDs in this column */
+ ids: string[];
+}
+
+/** Context provided by XDSSankeyChart to children */
+export interface SankeyContext {
+ nodes: SankeyNodeLayout[];
+ links: SankeyLinkLayout[];
+ columns: SankeyColumnLayout[];
+ width: number;
+ height: number;
+ valueScale: number;
+ maxValue: number;
+ nodeWidth: number;
+ /** Global node color override (CSS string) — when set, all nodes use this color */
+ nodeColor?: string;
+}
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index 31c489c2c3..834625c7c2 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -160,3 +160,26 @@ export {
XDSChartReferenceLine,
type XDSChartReferenceLineProps,
} from './Chart';
+
+// Sankey / flow diagrams — ribbon-based flow visualization
+export {
+ XDSSankeyChart,
+ type XDSSankeyChartProps,
+ XDSSankeyLink,
+ type XDSSankeyLinkProps,
+ XDSSankeyNode,
+ type XDSSankeyNodeProps,
+ XDSSankeyLabel,
+ type XDSSankeyLabelProps,
+ useSankey,
+ type SankeyNode,
+ type SankeyLink,
+ type SankeyColumn,
+ type SankeyColumnDef,
+ type SankeyNodeLayout,
+ type SankeyLinkLayout,
+ type SankeyColumnLayout,
+ XDSSankeyGrid,
+ type XDSSankeyGridProps,
+ type SankeyContext,
+} from './Sankey';