# SankeyChart

> Sankey flow diagrams from @salmonui/charts/sankey-chart with horizontal or vertical layout, node and link colors, gradient links, labels, a node legend, adjacent highlight, tooltips and node and flow keyboard navigation.

Canonical: https://salmonui.dev/docs/data-visualization/sankey-chart

`SankeyChart` lives in `@salmonui/charts/sankey-chart`. The layout (node
columns from the longest path, iterative relaxation, link bands) is
computed without d3 and identically on the server and the client.

```tsx
import { SankeyChart } from '@salmonui/charts/sankey-chart';
import '@salmonui/charts/sankey-chart/styles.css';

<SankeyChart nodes={[{ id: 'a', label: 'Coal' }, { id: 'b', label: 'Grid' }]} links={[{ source: 'a', target: 'b', value: 30 }]} height={320} />
```

### Live demo: Energy flow

Live demo: https://salmonui.dev/demos/data-visualization/sankey-chart-basic

A SankeyChart of energy sources to consumers with gradient links, a node legend, adjacent highlight on hover and keyboard navigation between nodes and flows.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { SankeyChart } from '@salmonui/charts/sankey-chart';

const nodes = [
  { id: 'coal', label: 'Coal' },
  { id: 'gas', label: 'Gas' },
  { id: 'solar', label: 'Solar' },
  { id: 'wind', label: 'Wind' },
  { id: 'grid', label: 'Grid' },
  { id: 'homes', label: 'Homes' },
  { id: 'industry', label: 'Industry' },
  { id: 'transport', label: 'Transport' },
];
const links = [
  { source: 'coal', target: 'grid', value: 30 },
  { source: 'gas', target: 'grid', value: 25 },
  { source: 'solar', target: 'grid', value: 15 },
  { source: 'wind', target: 'grid', value: 20 },
  { source: 'gas', target: 'industry', value: 10 },
  { source: 'grid', target: 'homes', value: 40 },
  { source: 'grid', target: 'industry', value: 35 },
  { source: 'grid', target: 'transport', value: 15 },
];

export default function SankeyChartBasicDemo() {
  const [last, setLast] = useState('none');
  return (
    <div className="demo-stack">
      <SankeyChart title="Energy flow (TWh)" nodes={nodes} links={links} height={380} linkColor="gradient" legend onNodeClick={(n) => setLast(n.label)} onLinkClick={(l) => setLast(`${l.source.label} → ${l.target.label}`)} />
      <p className="demo-status" aria-live="polite">
        Clicked: <code>{last}</code>
      </p>
    </div>
  );
}
```

## Layout and colors

`orientation` is `'horizontal'` (default) or `'vertical'`; `nodeWidth`
(default 16 px) and `nodePadding` (default 12 px) size the nodes,
`node.offset` shifts a node along its column and `curvature` (0 to 1,
default 0.5) bends the links. Links that close a cycle or name
an unknown node are dropped. Nodes take the derived palette or
`node.color` (a data color); `linkColor` is `'source'` (default),
`'target'` or `'gradient'`. `getNodeStyle`, `getLinkStyle` and
`formatLabel` restyle and relabel; `labels` is `true`, `false` or
`{ position: 'inside' | 'outside' }`. `format` and `locale` format the
values in labels, tooltips, announcements and the table.

## Interaction

Hovering a node or a link dims everything not adjacent to it
(`highlight: 'adjacent' | false`, default `'adjacent'`) and shows the
tooltip (`tooltip: { renderNode, renderLink }`). `onNodeClick(node, event)`
and `onNodeHover(node | null)` receive `{ index, id, label, value, column,
color }`; `onLinkClick(link, event)` and `onLinkHover(link | null)` receive
`{ index, source, target, value }` with both node records, and `event.source`
is `'pointer'`, `'keyboard'` or `'touch'`. The chart has no controlled
state. `legend` (`true` or `{ position, title }`) lists the nodes; hovering
an entry highlights that node's flows. `onResize`
reports the measured size, and `ref` receives the instance (`export`,
`toBlob`, `toDataURL`, `toSVGString`, `print`, `focus`).

### Live demo: Budget flow with custom tooltips

Live demo: https://salmonui.dev/demos/data-visualization/sankey-chart-budget

A monthly budget SankeyChart with custom node and link tooltips, getNodeStyle and getLinkStyle colors, formatLabel value labels, onResize and SVG / PNG export through the instance.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { SankeyChart, type SankeyChartApi, type SankeyNodeInfo } from '@salmonui/charts/sankey-chart';
import { Button } from '@salmonui/buttons/button';

const nodes = [
  { id: 'salary', label: 'Salary' },
  { id: 'freelance', label: 'Freelance' },
  { id: 'budget', label: 'Budget' },
  { id: 'housing', label: 'Housing' },
  { id: 'food', label: 'Food' },
  { id: 'transport', label: 'Transport' },
  { id: 'fun', label: 'Leisure' },
  { id: 'savings', label: 'Savings' },
];
const links = [
  { source: 'salary', target: 'budget', value: 4200 },
  { source: 'freelance', target: 'budget', value: 800 },
  { source: 'budget', target: 'housing', value: 1700 },
  { source: 'budget', target: 'food', value: 750 },
  { source: 'budget', target: 'transport', value: 300 },
  { source: 'budget', target: 'fun', value: 450 },
  { source: 'budget', target: 'savings', value: 1800 },
];

const money = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 });
const income = new Set(['salary', 'freelance']);
const nodeColor = (n: SankeyNodeInfo) => (income.has(n.id) ? '#15803d' : n.id === 'savings' ? '#2563eb' : n.id === 'budget' ? '#737373' : '#c2410c');

/** A monthly budget with custom tooltips, node and link styles, value labels, resize events and export. */
export default function SankeyChartBudgetDemo() {
  const ref = useRef<SankeyChartApi>(null);
  const [size, setSize] = useState('not measured yet');
  const [svgLength, setSvgLength] = useState<number | null>(null);
  return (
    <div className="demo-stack">
      <div className="demo-toolbar" role="group" aria-label="Export">
        <Button variant="outline" type="button" onClick={() => void ref.current?.export({ format: 'svg', fileName: 'budget.svg' })}>
          Download SVG
        </Button>
        <Button variant="outline" type="button" onClick={() => void ref.current?.export({ format: 'png', fileName: 'budget.png' })}>
          Download PNG
        </Button>
        <Button variant="outline" type="button" onClick={() => setSvgLength(ref.current?.toSVGString().length ?? 0)}>
          Measure SVG markup
        </Button>
      </div>
      <SankeyChart
        ref={ref}
        title="Monthly budget"
        subtitle="Income to spending, USD"
        nodes={nodes}
        links={links}
        height={360}
        format={{ style: 'currency', currency: 'USD', maximumFractionDigits: 0 }}
        formatLabel={(n) => `${n.label} ${money.format(n.value)}`}
        getNodeStyle={(n) => ({ color: nodeColor(n) })}
        getLinkStyle={(l) => ({ color: nodeColor(l.target.id === 'budget' ? l.source : l.target), opacity: l.value < 500 ? 0.3 : 0.55 })}
        tooltip={{
          renderNode: (n) => (
            <span>
              <strong>{n.label}</strong>: {money.format(n.value)}
            </span>
          ),
          renderLink: (l) => (
            <span>
              {l.source.label} → {l.target.label}: {money.format(l.value)} ({Math.round((l.value / l.source.value) * 100)}% of {l.source.label})
            </span>
          ),
        }}
        onResize={(s) => setSize(`${Math.round(s.width)} × ${Math.round(s.height)} px`)}
      />
      <p className="demo-status" aria-live="polite">
        Size: <code>{size}</code>
        {svgLength === null ? null : (
          <>
            {' '}
            · SVG markup: <code>{svgLength} characters</code>
          </>
        )}
      </p>
    </div>
  );
}
```

## Keyboard and accessibility

One tab stop. Arrow keys move between the nodes of a column and to the
nearest node of the next or previous column; Enter steps into the focused
node's flows (arrows cycle them) and Escape returns to the node. Enter on
a node and Enter or Space on a flow fire `onNodeClick` / `onLinkClick`;
Space on a node fires `onNodeClick` without stepping in. A polite
live region announces "Grid: 70, 3 incoming, 2 outgoing" or "Grid to Homes:
40". The accessible table lists source, target and value.

## Server rendering

The layout is pure, so the server renders the final nodes, links, labels,
legend and table. Without `height` (prop or CSS) the server renders the
nominal size and the chart relays out once after hydration (`onResize`);
tooltips and the entrance animation are client only. See
[Size, animation and RTL](https://salmonui.dev/docs/data-visualization/size-animation-rtl).

Node strokes, opacity and fonts are system-owned, not props; see
[Rendering and colors](https://salmonui.dev/docs/data-visualization/rendering-and-colors).
Every prop is listed in the [API reference](https://salmonui.dev/docs/reference/charts/sankey-chart).
