From d205cec371ff3db56828a4c8d3af5efadf21fd6d Mon Sep 17 00:00:00 2001 From: Benjamin Winkler Date: Sun, 8 Nov 2026 12:34:07 +0100 Subject: [PATCH 1/3] Refactor duplicated subject, formatting and geometry helpers Share subject normalization, tooltip anchors, balance rows, ghost attribute scoping, fallback amount formatting, validation errors, minimum-width growth and crossing predicates. Reuse the demo formatter and showConverted helper, and share the test input-error assertion. --- demo/fixtures.ts | 3 +- demo/format.ts | 8 +++ demo/linked-table.tsx | 8 +-- demo/main.tsx | 11 ++-- src/SankeyDiagram.tsx | 129 +++++++++++++++++++++--------------------- src/layout.ts | 96 +++++++++++++++---------------- src/model.ts | 21 ++++--- src/paths.ts | 21 +++---- src/presentation.ts | 30 ++++++---- tests/core.test.ts | 14 +---- tests/helpers.ts | 17 ++++++ tests/units.test.ts | 8 +-- 12 files changed, 184 insertions(+), 182 deletions(-) create mode 100644 demo/format.ts create mode 100644 tests/helpers.ts diff --git a/demo/fixtures.ts b/demo/fixtures.ts index fcc8323..06a1a94 100644 --- a/demo/fixtures.ts +++ b/demo/fixtures.ts @@ -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 || diff --git a/demo/format.ts b/demo/format.ts new file mode 100644 index 0000000..b38e364 --- /dev/null +++ b/demo/format.ts @@ -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); diff --git a/demo/linked-table.tsx b/demo/linked-table.tsx index fe2482e..4d6e4a2 100644 --- a/demo/linked-table.tsx +++ b/demo/linked-table.tsx @@ -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}`; diff --git a/demo/main.tsx b/demo/main.tsx index 8829890..aa5115e 100644 --- a/demo/main.tsx +++ b/demo/main.tsx @@ -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, @@ -36,9 +36,6 @@ const title = (view: SankeyPresentation) => view.kind === 'node' ? view.node.title : `${view.fromNode.title} → ${view.toNode.title}`; -const hasCombined = (view: Extract) => - !!view.converted && - (view.totals.length > 1 || view.totals[0]?.unit !== view.converted.unit); const labels = (view: SankeyPresentation) => view.kind === 'node' ? [ @@ -46,7 +43,7 @@ const labels = (view: SankeyPresentation) => ...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 @@ -124,7 +121,7 @@ const details = ( ))} - {hasCombined(view) && ( + {showConverted(view) && (
Combined in {view.converted!.unit}
diff --git a/src/SankeyDiagram.tsx b/src/SankeyDiagram.tsx index 8081819..91d1ffb 100644 --- a/src/SankeyDiagram.tsx +++ b/src/SankeyDiagram.tsx @@ -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, @@ -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 @@ -110,6 +104,26 @@ function Text({ ); } +function BalanceRows({ + total, + incoming, + outgoing, +}: { + readonly total: string; + readonly incoming: string; + readonly outgoing: string; +}) { + return ( +
+
Total
+
{total}
+
Incoming
+
{incoming}
+
Outgoing
+
{outgoing}
+
+ ); +} function DefaultDetails({ view }: { view: SankeyPresentation }) { return ( <> @@ -130,27 +144,21 @@ function DefaultDetails({ view }: { view: SankeyPresentation }) { )} -
-
Total
-
{row.total}
-
Incoming
-
{row.incoming}
-
Outgoing
-
{row.outgoing}
-
+
))} {showConverted(view) && (
Combined in {view.converted!.unit} -
-
Total
-
{view.text.converted!.total}
-
Incoming
-
{view.text.converted!.incoming}
-
Outgoing
-
{view.text.converted!.outgoing}
-
+
)} @@ -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; @@ -376,10 +381,13 @@ function SankeyDiagramRender( ); 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; @@ -614,18 +622,15 @@ function SankeyDiagramRender( 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( @@ -681,11 +686,9 @@ function SankeyDiagramRender( 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) < @@ -916,8 +919,8 @@ function SankeyDiagramRender( 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); } } @@ -968,8 +971,8 @@ function SankeyDiagramRender( 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, }; diff --git a/src/layout.ts b/src/layout.ts index b52717d..c7b179d 100644 --- a/src/layout.ts +++ b/src/layout.ts @@ -89,6 +89,8 @@ const PAD = 24, const LANE_GAP = 4; /** Upper bound that keeps every SVG coordinate well inside browser float precision. */ const MAX_EXTENT = 10_000_000; +const invalidNumber = (message: string) => + new SankeyInputError([{ code: 'invalid-number', message }]); const clamp = (n: number, a: number, b: number) => Math.max(a, Math.min(b, n)); const sum = (arr: number[]) => arr.reduce((a, b) => a + b, 0); // Keep bounds checks out of the argument list so large graphs cannot exceed @@ -212,23 +214,17 @@ export function* layoutGraphSteps( lineHeight <= 0 || lineHeight > MAX_EXTENT ) - throw new SankeyInputError([ - { - code: 'invalid-number', - message: `Layout width, plotHeight and lineHeight must be finite, positive and at most ${MAX_EXTENT} pixels.`, - }, - ]); + throw invalidNumber( + `Layout width, plotHeight and lineHeight must be finite, positive and at most ${MAX_EXTENT} pixels.`, + ); if ( !Number.isFinite(minLinkWidth) || minLinkWidth < 0 || minLinkWidth > MAX_EXTENT ) - throw new SankeyInputError([ - { - code: 'invalid-number', - message: `minLinkWidth must be finite, between 0 and ${MAX_EXTENT} pixels.`, - }, - ]); + throw invalidNumber( + `minLinkWidth must be finite, between 0 and ${MAX_EXTENT} pixels.`, + ); yield; // Scoring revisits the same route pairs during port swaps and diagnostics. // Routes are replaced, never mutated, during one layout attempt. Keep this @@ -295,12 +291,9 @@ export function* layoutGraphSteps( const minWidth = stages.length ? 2 * PAD + BAR + slots * 112 : 180; const width = Math.max(requested, minWidth); if (!Number.isFinite(width) || width > MAX_EXTENT) - throw new SankeyInputError([ - { - code: 'invalid-number', - message: `The layout needs more than ${MAX_EXTENT} pixels of width. Reduce the number of stages.`, - }, - ]); + throw invalidNumber( + `The layout needs more than ${MAX_EXTENT} pixels of width. Reduce the number of stages.`, + ); const step = (width - 2 * PAD - BAR) / slots; const axis = (index: number) => stages.length === 1 && !leftExtra && !rightExtra @@ -355,12 +348,9 @@ export function* layoutGraphSteps( ), ); if (!Number.isFinite(centralHeight) || centralHeight > MAX_EXTENT) - throw new SankeyInputError([ - { - code: 'invalid-number', - message: `The layout needs more than ${MAX_EXTENT} pixels of height. Reduce plotHeight, minLinkWidth or the number of nodes.`, - }, - ]); + throw invalidNumber( + `The layout needs more than ${MAX_EXTENT} pixels of height. Reduce plotHeight, minLinkWidth or the number of nodes.`, + ); let scale = Infinity; for (const stage of stages) { const total = sum(stage.map(geomTotal)); @@ -386,6 +376,19 @@ export function* layoutGraphSteps( } scale = lo; }; + /** Grow the canvas when a fixed pixel floor cannot fit at any value scale. */ + const widthForMinimum = ( + minimum: number, + available: number, + factor: number, + message: string, + ) => { + if (minimum <= available) return null; + const nextWidth = width + (minimum - available + 1) * slots * factor; + if (!Number.isFinite(nextWidth) || nextWidth > MAX_EXTENT) + throw invalidNumber(message); + return nextWidth; + }; const limits = new Map< string, { @@ -413,22 +416,19 @@ export function* layoutGraphSteps( if (minLinkWidth > 0) { const available = Math.max(8, hi - lo - 28), minimum = nodeSize(n, 0); - if (minimum > available) { - // Even a zero value scale cannot fit this edge's port stack. - const nextWidth = width + (minimum - available + 1) * slots * 2; - if (!Number.isFinite(nextWidth) || nextWidth > MAX_EXTENT) - throw new SankeyInputError([ - { - code: 'invalid-number', - message: `The layout needs more than ${MAX_EXTENT} pixels of width to fit minLinkWidth. Reduce minLinkWidth or the number of edge links.`, - }, - ]); + // Even a zero value scale cannot fit this edge's port stack. + const nextWidth = widthForMinimum( + minimum, + available, + 2, + `The layout needs more than ${MAX_EXTENT} pixels of width to fit minLinkWidth. Reduce minLinkWidth or the number of edge links.`, + ); + if (nextWidth !== null) return yield* layoutGraphSteps( model, { ...options, width: nextWidth }, attempt, ); - } fitScale((valueScale) => nodeSize(n, valueScale), available); } else if (geomTotal(n) > 0) scale = Math.min(scale, Math.max(8, hi - lo - 28) / geomTotal(n)); @@ -482,21 +482,18 @@ export function* layoutGraphSteps( ); if (minLinkWidth > 0) { const minimum = links.length * minLinkWidth; - if (minimum > channelWidth) { - const nextWidth = width + (minimum - channelWidth + 1) * slots * 4; - if (!Number.isFinite(nextWidth) || nextWidth > MAX_EXTENT) - throw new SankeyInputError([ - { - code: 'invalid-number', - message: `The layout needs more than ${MAX_EXTENT} pixels of width to fit minLinkWidth. Reduce minLinkWidth or the number of wrapped fan links.`, - }, - ]); + const nextWidth = widthForMinimum( + minimum, + channelWidth, + 4, + `The layout needs more than ${MAX_EXTENT} pixels of width to fit minLinkWidth. Reduce minLinkWidth or the number of wrapped fan links.`, + ); + if (nextWidth !== null) return yield* layoutGraphSteps( model, { ...options, width: nextWidth }, attempt, ); - } fitScale( (valueScale) => sum(links.map((f) => linkWidth(f, valueScale))), channelWidth, @@ -756,12 +753,9 @@ export function* layoutGraphSteps( centralTop = PAD + topBand, height = PAD + topBand + centralHeight + bottomBand + PAD; if (!Number.isFinite(height) || height > MAX_EXTENT) - throw new SankeyInputError([ - { - code: 'invalid-number', - message: `The layout needs more than ${MAX_EXTENT} pixels of height. Reduce plotHeight, minLinkWidth or the number of edge nodes.`, - }, - ]); + throw invalidNumber( + `The layout needs more than ${MAX_EXTENT} pixels of height. Reduce plotHeight, minLinkWidth or the number of edge nodes.`, + ); for (const n of nodes) { if (!n.edge) { n.y += centralTop; diff --git a/src/model.ts b/src/model.ts index 49c8867..75a4045 100644 --- a/src/model.ts +++ b/src/model.ts @@ -389,6 +389,16 @@ export function resolveGraph( ], }; } +/** Normalize one subject or a list into a stable readonly list. */ +export function subjectList( + subject: SankeySubject | readonly SankeySubject[] | null | undefined, +): readonly SankeySubject[] { + return subject == null + ? [] + : Array.isArray(subject) + ? (subject as readonly SankeySubject[]) + : [subject as SankeySubject]; +} export function subjectExists( model: ResolvedGraph, subject: SankeySubject | null | undefined, @@ -407,15 +417,8 @@ export function emphasis( ) { const nodes = new Set(), links = new Set(); - const subjects = !subject - ? [] - : Array.isArray(subject) - ? (subject as readonly SankeySubject[]) - : [subject as SankeySubject]; - const valid = subjects.filter((item) => - item.kind === 'node' - ? model.nodes.has(item.key) - : model.links.has(item.key), + const valid = subjectList(subject).filter((item) => + subjectExists(model, item), ); if (!valid.length) { for (const k of model.nodes.keys()) nodes.add(k); diff --git a/src/paths.ts b/src/paths.ts index 3fe3bb1..13cd84b 100644 --- a/src/paths.ts +++ b/src/paths.ts @@ -15,6 +15,11 @@ export interface Route { length: number; } const near = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y) < 1e-5; +const side = (p: Point, q: Point, r: Point) => + (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x); +const crosses = (p: Point, q: Point, r: Point, s: Point) => + side(p, q, r) * side(p, q, s) < -1e-7 && + side(r, s, p) * side(r, s, q) < -1e-7; export const inside = (p: Point, r: Rect) => p.x > r.x + 1e-5 && p.x < r.x + r.w - 1e-5 && @@ -505,8 +510,6 @@ export function routeCollisions( } export function crossings(a: Route, b: Route): number { if (!intersects(a.bounds, b.bounds)) return 0; - const side = (p: Point, q: Point, r: Point) => - (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x); const monotoneX = (points: Point[]): number => { let direction = 0; for (let i = 1; i < points.length; i++) { @@ -535,13 +538,7 @@ export function crossings(a: Route, b: Route): number { aMax = Math.max(p.x, q.x); const bMin = Math.min(r.x, s.x), bMax = Math.max(r.x, s.x); - if ( - aMax >= bMin && - bMax >= aMin && - side(p, q, r) * side(p, q, s) < -1e-7 && - side(r, s, p) * side(r, s, q) < -1e-7 - ) - return 1; + if (aMax >= bMin && bMax >= aMin && crosses(p, q, r, s)) return 1; // Equal interval ends can only meet at endpoints, or along // collinear vertical segments; neither counts as a crossing. if (aMax <= bMax) i += aDirection; @@ -568,11 +565,7 @@ export function crossings(a: Route, b: Route): number { (r.y > maxY && s.y > maxY) ) continue; - if ( - side(p, q, r) * side(p, q, s) < -1e-7 && - side(r, s, p) * side(r, s, q) < -1e-7 - ) - return 1; + if (crosses(p, q, r, s)) return 1; } } return 0; diff --git a/src/presentation.ts b/src/presentation.ts index 95442a4..1dec1b2 100644 --- a/src/presentation.ts +++ b/src/presentation.ts @@ -40,6 +40,14 @@ function scopeHashReference(value: string, prefix: string) { const match = /^(?:#|�*35;|�*23;)/i.exec(value); return match ? `#${prefix}${value.slice(match[0].length)}` : value; } +function scopeGhostAttribute(name: string, value: string, prefix: string) { + const lower = name.toLowerCase(); + return lower === 'id' + ? `${prefix}${value}` + : lower === 'href' || lower === 'xlink:href' + ? scopeHashReference(value, prefix) + : scopeUrlReferences(value, prefix); +} function scopeUrlReferences(value: string, prefix: string) { return value.replace(/url\(([^)]*)\)/gi, (token, body: string) => { const decoded = decodeAttributeReferences(body).trim(), @@ -63,10 +71,7 @@ function scopeGhostMarkupWithDom(markup: string, prefix: string) { for (const attribute of Array.from(element.attributes)) { const name = attribute.name.toLowerCase(); if (name === 'id' || name === 'tabindex') continue; - attribute.value = - name === 'href' || name === 'xlink:href' - ? scopeHashReference(attribute.value, prefix) - : scopeUrlReferences(attribute.value, prefix); + attribute.value = scopeGhostAttribute(name, attribute.value, prefix); } } return root.innerHTML; @@ -131,10 +136,7 @@ function scopeGhostTag(tag: string, prefix: string) { } const lower = attributeName.toLowerCase(); if (lower === 'tabindex') continue; - if (lower === 'id') value = prefix + value; - else if (lower === 'href' || lower === 'xlink:href') - value = scopeHashReference(value, prefix); - else value = scopeUrlReferences(value, prefix); + value = scopeGhostAttribute(lower, value, prefix); result += tag.slice(attributeStart, nameStart) + attributeName + @@ -185,6 +187,8 @@ export function scopeGhostMarkup(markup: string, prefix: string) { const numeric = new Intl.NumberFormat(undefined, { maximumSignificantDigits: 15, }); +const fallbackAmount = (value: number, unit: string | undefined) => + `${numeric.format(value)}${unit ? ` ${unit}` : ''}`; export function presentation( model: ResolvedGraph, subject: SankeySubject, @@ -206,7 +210,7 @@ export function presentation( unit: row.unit, isConverted, }) - : `${numeric.format(row[field])}${row.unit ? ` ${row.unit}` : ''}`; + : fallbackAmount(row[field], row.unit); return { unit: row.unit, total: number('total'), @@ -233,7 +237,7 @@ export function presentation( ) => format ? format(amount, { ...facts, field, surface, unit, isConverted }) - : `${numeric.format(amount)}${unit ? ` ${unit}` : ''}`; + : fallbackAmount(amount, unit); return { ...facts, text: { @@ -301,8 +305,10 @@ export function defaultLabel( ]; } export const identity = (s: SankeySubject) => JSON.stringify([s.kind, s.key]); -export const same = (a: SankeySubject | null, b: SankeySubject | null) => - a?.kind === b?.kind && a?.key === b?.key; +export const same = ( + a: SankeySubject | null | undefined, + b: SankeySubject | null | undefined, +) => a?.kind === b?.kind && a?.key === b?.key; /** Resolve replay-on-attach and identity-change dedupe for one inspection report. */ export function inspectionReport( reported: string | null, diff --git a/tests/core.test.ts b/tests/core.test.ts index 8a90f5f..f8f351e 100644 --- a/tests/core.test.ts +++ b/tests/core.test.ts @@ -19,12 +19,9 @@ import { ribbonBounds, routeCollisions, } from '../src/paths.js'; -import { - SankeyInputError, - type SankeyGraph, - type SankeyIssueCode, -} from '../src/types.js'; +import { SankeyInputError, type SankeyGraph } from '../src/types.js'; import { obstacleGraph, stressGraph } from '../fixtures/stress.js'; +import { error } from './helpers.js'; const full = JSON.parse( readFileSync( new URL('../../demo/feature-demo.json', import.meta.url), @@ -44,13 +41,6 @@ const base: SankeyGraph = { ], links: [{ key: 'ab', from: 'a', to: 'b', amount: 500 }], }; -const error = (graph: SankeyGraph, code: SankeyIssueCode) => - assert.throws( - () => resolveGraph(graph), - (e: unknown) => - e instanceof SankeyInputError && - e.issues.some((issue) => issue.code === code), - ); function fan(edge: 'top' | 'bottom' = 'bottom', count = 3): SankeyGraph { return { stages: ['a'], diff --git a/tests/helpers.ts b/tests/helpers.ts new file mode 100644 index 0000000..6944fda --- /dev/null +++ b/tests/helpers.ts @@ -0,0 +1,17 @@ +import assert from 'node:assert/strict'; +import { resolveGraph } from '../src/model.js'; +import { + SankeyInputError, + type SankeyGraph, + type SankeyIssueCode, +} from '../src/types.js'; + +/** Assert that a graph is rejected with the expected issue code. */ +export function error(graph: SankeyGraph, code: SankeyIssueCode) { + assert.throws( + () => resolveGraph(graph), + (e: unknown) => + e instanceof SankeyInputError && + e.issues.some((issue) => issue.code === code), + ); +} diff --git a/tests/units.test.ts b/tests/units.test.ts index 6746d42..7c3f7da 100644 --- a/tests/units.test.ts +++ b/tests/units.test.ts @@ -15,9 +15,9 @@ import { SankeyInputError, type SankeyGraph, type SankeyIssue, - type SankeyIssueCode, type SankeyAmountContext, } from '../src/types.js'; +import { error } from './helpers.js'; const graph: SankeyGraph = { defaultUnit: 'USD', @@ -70,12 +70,6 @@ const graph: SankeyGraph = { }; const approx = (actual: number, expected: number) => assert.ok(Math.abs(actual - expected) < 1e-8, `${actual} ≠ ${expected}`); -const error = (g: SankeyGraph, code: SankeyIssueCode) => - assert.throws( - () => resolveGraph(g), - (e: unknown) => - e instanceof SankeyInputError && e.issues.some((i) => i.code === code), - ); const fx = (rate = 4000): SankeyGraph => ({ defaultUnit: 'USD', From 4fe81745f0b9463dc9376b1ac53c97cfda8dc759 Mon Sep 17 00:00:00 2001 From: Benjamin Winkler Date: Sun, 8 Nov 2026 12:34:11 +0100 Subject: [PATCH 2/3] Ignore local Claude worktrees in lint and format checks ESLint and Prettier were traversing ignored .claude/worktrees copies, producing unrelated failures. Ignore that directory plus generated Playwright output. --- .prettierignore | 1 + eslint.config.js | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.prettierignore b/.prettierignore index 9ce0410..bdab41c 100644 --- a/.prettierignore +++ b/.prettierignore @@ -2,6 +2,7 @@ dist/ demo-dist/ .tests/ +.claude/ node_modules/ playwright-report/ test-results/ diff --git a/eslint.config.js b/eslint.config.js index 273f1a0..75bf3bc 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -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], From a7920723d023893ce6ea5909f5d6e6279be16f35 Mon Sep 17 00:00:00 2001 From: Benjamin Winkler Date: Sun, 8 Nov 2026 15:43:46 +0100 Subject: [PATCH 3/3] Harden subject identity and defer layout error allocation Treat absent subjects as distinct in same(), keep emphasis() strict for malformed entries while retaining shared existence logic, and build minLinkWidth error messages only after a failed width check. Add regression coverage for the subject helpers. --- src/layout.ts | 15 ++++++--------- src/model.ts | 17 ++++++++++------- src/presentation.ts | 2 +- tests/core.test.ts | 31 +++++++++++++++++++++++++++++-- 4 files changed, 46 insertions(+), 19 deletions(-) diff --git a/src/layout.ts b/src/layout.ts index c7b179d..6c2b505 100644 --- a/src/layout.ts +++ b/src/layout.ts @@ -381,12 +381,14 @@ export function* layoutGraphSteps( minimum: number, available: number, factor: number, - message: string, + target: string, ) => { if (minimum <= available) return null; const nextWidth = width + (minimum - available + 1) * slots * factor; if (!Number.isFinite(nextWidth) || nextWidth > MAX_EXTENT) - throw invalidNumber(message); + throw invalidNumber( + `The layout needs more than ${MAX_EXTENT} pixels of width to fit minLinkWidth. Reduce minLinkWidth or the number of ${target}.`, + ); return nextWidth; }; const limits = new Map< @@ -417,12 +419,7 @@ export function* layoutGraphSteps( const available = Math.max(8, hi - lo - 28), minimum = nodeSize(n, 0); // Even a zero value scale cannot fit this edge's port stack. - const nextWidth = widthForMinimum( - minimum, - available, - 2, - `The layout needs more than ${MAX_EXTENT} pixels of width to fit minLinkWidth. Reduce minLinkWidth or the number of edge links.`, - ); + const nextWidth = widthForMinimum(minimum, available, 2, 'edge links'); if (nextWidth !== null) return yield* layoutGraphSteps( model, @@ -486,7 +483,7 @@ export function* layoutGraphSteps( minimum, channelWidth, 4, - `The layout needs more than ${MAX_EXTENT} pixels of width to fit minLinkWidth. Reduce minLinkWidth or the number of wrapped fan links.`, + 'wrapped fan links', ); if (nextWidth !== null) return yield* layoutGraphSteps( diff --git a/src/model.ts b/src/model.ts index 75a4045..a7b61a5 100644 --- a/src/model.ts +++ b/src/model.ts @@ -399,16 +399,19 @@ export function subjectList( ? (subject as readonly SankeySubject[]) : [subject as SankeySubject]; } +/** Non-null objects are dereferenced so malformed array entries fail fast. */ +const knownSubject = ( + model: ResolvedGraph, + subject: SankeySubject, +) => + subject.kind === 'node' + ? model.nodes.has(subject.key) + : model.links.has(subject.key); export function subjectExists( model: ResolvedGraph, subject: SankeySubject | null | undefined, ): subject is SankeySubject { - return ( - !!subject && - (subject.kind === 'node' - ? model.nodes.has(subject.key) - : model.links.has(subject.key)) - ); + return !!subject && knownSubject(model, subject); } /** Strong sets for one or more subjects. Empty input preserves the all-strong default. */ export function emphasis( @@ -418,7 +421,7 @@ export function emphasis( const nodes = new Set(), links = new Set(); const valid = subjectList(subject).filter((item) => - subjectExists(model, item), + knownSubject(model, item), ); if (!valid.length) { for (const k of model.nodes.keys()) nodes.add(k); diff --git a/src/presentation.ts b/src/presentation.ts index 1dec1b2..14901bd 100644 --- a/src/presentation.ts +++ b/src/presentation.ts @@ -308,7 +308,7 @@ export const identity = (s: SankeySubject) => JSON.stringify([s.kind, s.key]); export const same = ( a: SankeySubject | null | undefined, b: SankeySubject | null | undefined, -) => a?.kind === b?.kind && a?.key === b?.key; +) => a != null && b != null && a.kind === b.kind && a.key === b.key; /** Resolve replay-on-attach and identity-change dedupe for one inspection report. */ export function inspectionReport( reported: string | null, diff --git a/tests/core.test.ts b/tests/core.test.ts index f8f351e..9e06da9 100644 --- a/tests/core.test.ts +++ b/tests/core.test.ts @@ -6,10 +6,11 @@ import { emphasis, nodeColor, subjectExists, + subjectList, } from '../src/model.js'; import { validateGraph } from '../src/validate.js'; import { layoutGraph, hitTest } from '../src/layout.js'; -import { defaultLabel, presentation } from '../src/presentation.js'; +import { defaultLabel, presentation, same } from '../src/presentation.js'; import { crossings, distanceToRoute, @@ -19,7 +20,11 @@ import { ribbonBounds, routeCollisions, } from '../src/paths.js'; -import { SankeyInputError, type SankeyGraph } from '../src/types.js'; +import { + SankeyInputError, + type SankeyGraph, + type SankeySubject, +} from '../src/types.js'; import { obstacleGraph, stressGraph } from '../fixtures/stress.js'; import { error } from './helpers.js'; const full = JSON.parse( @@ -386,6 +391,28 @@ test('subject retention rejects subjects missing from the current model', () => assert.equal(subjectExists(model, { kind: 'link', key: 'ab' }), true); assert.equal(subjectExists(model, { kind: 'link', key: 'missing' }), false); assert.equal(subjectExists(model, null), false); + assert.equal(subjectExists(model, undefined), false); +}); +test('subject normalization and identity treat absence as no subject', () => { + assert.deepEqual(subjectList(null), []); + assert.deepEqual(subjectList(undefined), []); + assert.deepEqual(subjectList({ kind: 'node', key: 'a' }), [ + { kind: 'node', key: 'a' }, + ]); + const node: SankeySubject = { kind: 'node', key: 'a' }; + assert.equal(same(node, node), true); + assert.equal(same(node, { kind: 'link', key: 'a' }), false); + assert.equal(same(node, { kind: 'node', key: 'b' }), false); + assert.equal(same(null, null), false); + assert.equal(same(undefined, undefined), false); + assert.equal(same(undefined, null), false); +}); +test('emphasis fails fast on malformed subject entries', () => { + const model = resolveGraph(base); + assert.throws( + () => emphasis(model, [null] as unknown as SankeySubject[]), + TypeError, + ); }); test('hover is exactly one hop, not the induced subgraph of strong nodes', () => { const model = resolveGraph(full),