Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
dist/
demo-dist/
.tests/
.claude/
node_modules/
playwright-report/
test-results/
Expand Down
3 changes: 2 additions & 1 deletion demo/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ import tradeData from './trade.json';
import currenciesData from './currencies.json';
import wideRangeData from './wide-range.json';
import { renderOverlay } from './layout-overlay.js';
import { formatValue } from './format.js';
import { stressGraph } from '../fixtures/stress.js';
export const fullGraph = full as SankeyGraph;
export const distribution = distributionData as SankeyGraph;
const tradeAmount = (value: number) => `$${value.toLocaleString('en-US')} bn`;
const formatAmount = (value: number, context: SankeyAmountContext) => {
const formatted = `${value.toLocaleString('en-US', { maximumFractionDigits: 2 })} ${context.unit ?? 'units'}`;
const formatted = formatValue(value, context.unit);
if (
context.kind !== 'link' ||
context.isConverted ||
Expand Down
8 changes: 8 additions & 0 deletions demo/format.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/** Shared demo formatter so fixtures and views show identical numeric units. */
export const formatValue = (value: number, unit?: string) =>
`${value.toLocaleString('en-US', { maximumFractionDigits: 2 })} ${unit ?? 'units'}`;

export const formatQuantity = (
value: number,
context?: { readonly unit?: string },
) => formatValue(value, context?.unit);
8 changes: 2 additions & 6 deletions demo/linked-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,10 @@ import type {
SankeySubject,
} from '../src/index.js';
import { resolveGraph } from '../src/model.js';
import { same as sameSubject } from '../src/presentation.js';
import { formatValue as format } from './format.js';
import './linked-table.css';

const format = (value: number, unit?: string) =>
`${value.toLocaleString('en-US', { maximumFractionDigits: 2 })} ${unit ?? 'units'}`;

const sameSubject = (a: SankeySubject | null | undefined, b: SankeySubject) =>
!!a && a.kind === b.kind && a.key === b.key;

const placementLabel = (placement: SankeyPlacement) =>
placement.stage !== undefined ? placement.stage : `Edge · ${placement.edge}`;

Expand Down
11 changes: 4 additions & 7 deletions demo/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ import {
type SankeyLayout,
} from '../src/index.js';
import { examples } from './fixtures.js';
import { formatQuantity as format } from './format.js';
import { showConverted } from '../src/presentation.js';
import { ValidationPanel } from './validation-panel.js';
import { InspectionPanel } from './inspection-panel.js';
import { LinkedTable } from './linked-table.js';
import { useExampleTiming } from './useExampleTiming.js';
import './demo.css';
import '../src/style.css';
const format = (value: number, context?: { unit?: string }) =>
`${value.toLocaleString('en-US', { maximumFractionDigits: 2 })} ${context?.unit ?? 'units'}`;
const nodeName = (node: SankeyNode, graph: SankeyGraph) =>
graph.nodes.some(
(other) => other.key !== node.key && other.title === node.title,
Expand All @@ -36,17 +36,14 @@ const title = (view: SankeyPresentation) =>
view.kind === 'node'
? view.node.title
: `${view.fromNode.title} → ${view.toNode.title}`;
const hasCombined = (view: Extract<SankeyPresentation, { kind: 'node' }>) =>
!!view.converted &&
(view.totals.length > 1 || view.totals[0]?.unit !== view.converted.unit);
const labels = (view: SankeyPresentation) =>
view.kind === 'node'
? [
view.node.title,
...view.text.totals.map(
(row) => `${row.total}${row.unit ? '' : ' total'}`,
),
...(hasCombined(view) ? [`Σ ${view.text.converted!.total}`] : []),
...(showConverted(view) ? [`Σ ${view.text.converted!.total}`] : []),
]
: view.input.unit !== view.output.unit ||
view.input.amount !== view.output.amount
Expand Down Expand Up @@ -124,7 +121,7 @@ const details = (
</dl>
</div>
))}
{hasCombined(view) && (
{showConverted(view) && (
<div className="flow-tip-balance flow-tip-combined">
<strong>Combined in {view.converted!.unit}</strong>
<dl>
Expand Down
10 changes: 9 additions & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ import globals from 'globals';
import tseslint from 'typescript-eslint';

export default defineConfig([
globalIgnores(['dist/', 'demo-dist/', '.tests/', 'node_modules/']),
globalIgnores([
'dist/',
'demo-dist/',
'.tests/',
'.claude/',
'node_modules/',
'playwright-report/',
'test-results/',
]),
{
files: ['**/*.{js,mjs}'],
extends: [js.configs.recommended],
Expand Down
129 changes: 66 additions & 63 deletions src/SankeyDiagram.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
type Ref,
} from 'react';
import { createPortal } from 'react-dom';
import { emphasis, resolveGraph, subjectExists } from './model.js';
import { emphasis, resolveGraph, subjectExists, subjectList } from './model.js';
import {
hitTest,
layoutGraphSteps,
Expand Down Expand Up @@ -51,40 +51,34 @@ import type {
} from './types.js';
const useBrowserLayoutEffect =
typeof window === 'undefined' ? useEffect : useLayoutEffect;
type Anchor = {
x: number;
y: number;
};
type Inspection = SankeyInspection & {
anchor: {
x: number;
y: number;
};
anchor: Anchor;
pinned: boolean;
};
function subjectList(
subject: SankeySubject | readonly SankeySubject[] | null | undefined,
): readonly SankeySubject[] {
return subject == null
? []
: Array.isArray(subject)
? (subject as readonly SankeySubject[])
: [subject as SankeySubject];
}
type SceneSnapshot = {
scene: Scene;
selection: string;
highlight: string;
type SceneCapture = {
markup: string;
width: number;
height: number;
font: string;
};
type SceneGhost = {
type SceneSnapshot = SceneCapture & {
scene: Scene;
selection: string;
highlight: string;
};
type SceneGhost = SceneCapture & {
id: number;
markup: string;
width: number;
height: number;
font: string;
duration: number;
easing: string;
};
function anchorAt(element: Element): Anchor {
const box = element.getBoundingClientRect();
return { x: box.right, y: box.top + box.height / 2 };
}
function Text({
box,
...props
Expand All @@ -110,6 +104,26 @@ function Text({
</text>
);
}
function BalanceRows({
total,
incoming,
outgoing,
}: {
readonly total: string;
readonly incoming: string;
readonly outgoing: string;
}) {
return (
<dl>
<dt>Total</dt>
<dd>{total}</dd>
<dt>Incoming</dt>
<dd>{incoming}</dd>
<dt>Outgoing</dt>
<dd>{outgoing}</dd>
</dl>
);
}
function DefaultDetails({ view }: { view: SankeyPresentation }) {
return (
<>
Expand All @@ -130,27 +144,21 @@ function DefaultDetails({ view }: { view: SankeyPresentation }) {
</span>
</strong>
)}
<dl>
<dt>Total</dt>
<dd>{row.total}</dd>
<dt>Incoming</dt>
<dd>{row.incoming}</dd>
<dt>Outgoing</dt>
<dd>{row.outgoing}</dd>
</dl>
<BalanceRows
total={row.total}
incoming={row.incoming}
outgoing={row.outgoing}
/>
</div>
))}
{showConverted(view) && (
<div className="flow-tip-balance flow-tip-combined">
<strong>Combined in {view.converted!.unit}</strong>
<dl>
<dt>Total</dt>
<dd>{view.text.converted!.total}</dd>
<dt>Incoming</dt>
<dd>{view.text.converted!.incoming}</dd>
<dt>Outgoing</dt>
<dd>{view.text.converted!.outgoing}</dd>
</dl>
<BalanceRows
total={view.text.converted!.total}
incoming={view.text.converted!.incoming}
outgoing={view.text.converted!.outgoing}
/>
</div>
)}
</>
Expand Down Expand Up @@ -190,17 +198,14 @@ function DefaultDetails({ view }: { view: SankeyPresentation }) {
);
}
type DetailsHandle = {
move: (anchor: { x: number; y: number }) => void;
move: (anchor: Anchor) => void;
contains: (node: Node | null) => boolean;
};
const Details = forwardRef<
DetailsHandle,
{
id: string;
anchor: {
x: number;
y: number;
};
anchor: Anchor;
children: ReactNode;
theme: CSSProperties;
onPointerEnter: () => void;
Expand Down Expand Up @@ -376,10 +381,13 @@ function SankeyDiagramRender<I = unknown, T = unknown>(
);
return { nodes, links };
}, [model]);
const indexOf = (subject: SankeySubject) =>
subject.kind === 'node'
? (subjectIndex.nodes.get(subject.key) ?? -1)
: (subjectIndex.links.get(subject.key) ?? -1);
const indexOf = useCallback(
(subject: SankeySubject) =>
subject.kind === 'node'
? (subjectIndex.nodes.get(subject.key) ?? -1)
: (subjectIndex.links.get(subject.key) ?? -1),
[subjectIndex],
);
useBrowserLayoutEffect(() => {
const el = root.current;
if (!el) return;
Expand Down Expand Up @@ -614,18 +622,15 @@ function SankeyDiagramRender<I = unknown, T = unknown>(
if (!exists(subject)) return false;
const control = controls.current.get(identity(subject));
if (!control) return false;
const index =
subject.kind === 'node'
? subjectIndex.nodes.get(subject.key)
: subjectIndex.links.get(subject.key);
if (index === undefined) return false;
const index = indexOf(subject);
if (index < 0) return false;
input.current = 'keyboard';
suppressed.current = null;
setRoving(index);
control.focus({ preventScroll: true });
return true;
},
[exists, subjectIndex],
[exists, indexOf],
);
focusSubjectRef.current = focusSubject;
useImperativeHandle(
Expand Down Expand Up @@ -681,11 +686,9 @@ function SankeyDiagramRender<I = unknown, T = unknown>(
function repositionInspection() {
setInspection((old) => {
if (!old || old.modality === 'pointer') return null;
const box = controls.current
.get(identity(old.subject))
?.getBoundingClientRect();
if (!box) return null;
const anchor = { x: box.right, y: box.top + box.height / 2 };
const control = controls.current.get(identity(old.subject));
if (!control) return null;
const anchor = anchorAt(control);
lastAnchor.current = anchor;
return Math.abs(anchor.x - old.anchor.x) +
Math.abs(anchor.y - old.anchor.y) <
Expand Down Expand Up @@ -916,8 +919,8 @@ function SankeyDiagramRender<I = unknown, T = unknown>(
if (e.repeat) return;
lastKeyboard.current = performance.now();
suppressed.current = null;
const r = e.currentTarget.getBoundingClientRect();
inspect(subject, r.right, r.top + r.height / 2, 'keyboard', true);
const anchor = anchorAt(e.currentTarget);
inspect(subject, anchor.x, anchor.y, 'keyboard', true);
activate(subject, e);
}
}
Expand Down Expand Up @@ -968,8 +971,8 @@ function SankeyDiagramRender<I = unknown, T = unknown>(
return;
setKeyboardFocus(subject);
suppressed.current = null;
const r = e.currentTarget.getBoundingClientRect();
inspect(subject, r.right, r.top + r.height / 2, 'keyboard');
const anchor = anchorAt(e.currentTarget);
inspect(subject, anchor.x, anchor.y, 'keyboard');
},
style: { outline: 'none' } as CSSProperties,
};
Expand Down
Loading
Loading