packages/core/src/features/viz/lib/graph/sankey.tsx
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import type { NodeStyle } from "./types.js";
2 import { Group, SvgPath, resolveSignalValue } from "@pibbl/core";
3 import type { PibblNode, PathSegment } from "@pibbl/core";
4 import type {
5 Accessor,
6 GraphData,
7 GraphNodeProps,
8 MarkInteraction,
9 SankeyFlowGeometry,
10 SankeyLayout,
11 SankeyNodeGeometry,
12 SankeyOptions,
13 SankeyProps,
14 Style,
15 EdgeStyle,
16 VizKey,
17 } from "./types.js";
18 import {
19 defaultGraphLabelStyle,
20 GraphLabel,
21 GraphNode,
22 resolveMarkStyle,
23 useGraphFrame,
24 } from "./shared.js";
25
26 function access<D, V>(input: Accessor<D, V>, datum: D): V {
27 return typeof input === "function"
28 ? input(datum)
29 : (datum as Record<PropertyKey, V>)[input];
30 }
31 function finite(value: number, name: string, zero = false) {
32 if (!Number.isFinite(value) || (zero && value < 0))
33 throw new RangeError(
34 `layoutSankey: ${name} must be finite${zero ? " and nonnegative" : ""}.`,
35 );
36 return value;
37 }
38 function path(segments: readonly PathSegment[]) {
39 return segments
40 .map((segment) =>
41 segment.type === "move"
42 ? `M ${segment.x} ${segment.y}`
43 : segment.type === "line"
44 ? `L ${segment.x} ${segment.y}`
45 : segment.type === "cubic"
46 ? `C ${segment.cp1x} ${segment.cp1y} ${segment.cp2x} ${segment.cp2y} ${segment.x} ${segment.y}`
47 : segment.type === "close"
48 ? "Z"
49 : "",
50 )
51 .join(" ");
52 }
53
54 /** Places an acyclic weighted flow graph in deterministic left-to-right ranks.
55 * @param graph - Nodes and acyclic weighted edges. See {@link GraphData}.
56 * @param options - Accessors, bounds, and display unit. See {@link SankeyOptions}.
57 * @returns Immutable nodes and proportional flow geometry. See {@link SankeyLayout}.
58 */
59 export function layoutSankey<N, E>(
60 graph: GraphData<N, E>,
61 options: SankeyOptions<N, E>,
62 ): SankeyLayout<N, E> {
63 const b = options.bounds;
64 finite(b.x, "bounds.x");
65 finite(b.y, "bounds.y");
66 finite(b.width, "bounds.width", true);
67 finite(b.height, "bounds.height", true);
68 const nodeWidth = finite(options.nodeWidth ?? 18, "nodeWidth", true),
69 nodeGap = finite(options.nodeGap ?? 12, "nodeGap", true);
70 const nodes = new Map<VizKey, N>();
71 for (const node of graph.nodes) {
72 const key = access(options.nodeKey, node);
73 if (nodes.has(key))
74 throw new Error(`layoutSankey: duplicate node key ${String(key)}.`);
75 nodes.set(key, node);
76 }
77 const edges = graph.edges.map((edge) => {
78 const key = access(options.edgeKey, edge),
79 sourceKey = access(options.source, edge),
80 targetKey = access(options.target, edge),
81 value = finite(access(options.value, edge), "edge value", true);
82 if (!nodes.has(sourceKey) || !nodes.has(targetKey))
83 throw new RangeError("layoutSankey: edge endpoint is not a node key.");
84 return { key, edge, sourceKey, targetKey, value };
85 });
86 const incoming = new Map<VizKey, number>(),
87 outgoing = new Map<VizKey, number>(),
88 targets = new Map<VizKey, VizKey[]>();
89 for (const key of nodes.keys()) {
90 incoming.set(key, 0);
91 outgoing.set(key, 0);
92 targets.set(key, []);
93 }
94 for (const edge of edges) {
95 incoming.set(
96 edge.targetKey,
97 finite(
98 incoming.get(edge.targetKey)! + edge.value,
99 "incoming total",
100 true,
101 ),
102 );
103 outgoing.set(
104 edge.sourceKey,
105 finite(
106 outgoing.get(edge.sourceKey)! + edge.value,
107 "outgoing total",
108 true,
109 ),
110 );
111 targets.get(edge.sourceKey)!.push(edge.targetKey);
112 }
113 const ranks = new Map<VizKey, number>();
114 const visit = (key: VizKey, visiting = new Set<VizKey>()): number => {
115 if (ranks.has(key)) return ranks.get(key)!;
116 if (visiting.has(key))
117 throw new RangeError("layoutSankey: flows must be acyclic.");
118 visiting.add(key);
119 let rank = 0;
120 for (const target of targets.get(key)!)
121 rank = Math.max(rank, visit(target, visiting) + 1);
122 visiting.delete(key);
123 ranks.set(key, rank);
124 return rank;
125 };
126 for (const key of nodes.keys()) visit(key);
127 const maxRank = Math.max(...ranks.values(), 0);
128 for (const [key, rank] of ranks) ranks.set(key, maxRank - rank);
129 const columns = Array.from({ length: maxRank + 1 }, () => [] as VizKey[]);
130 for (const key of nodes.keys()) columns[ranks.get(key)!].push(key);
131 const candidateScale = Math.min(
132 ...columns
133 .map((column) => {
134 const sum = column.reduce<number>(
135 (total, key) =>
136 total + Math.max(incoming.get(key)!, outgoing.get(key)!),
137 0,
138 );
139 finite(sum, "column total", true);
140 return sum > 0
141 ? Math.max(
142 0,
143 (b.height - Math.max(0, column.length - 1) * nodeGap) / sum,
144 )
145 : Infinity;
146 })
147 .filter(Number.isFinite),
148 );
149 const scale = Number.isFinite(candidateScale) ? candidateScale : 0;
150 const geometry = new Map<VizKey, SankeyNodeGeometry<N>>();
151 columns.forEach((column, rank) => {
152 let y = b.y;
153 for (const key of column) {
154 const datum = nodes.get(key)!;
155 const size = Math.max(incoming.get(key)!, outgoing.get(key)!) * scale;
156 const bounds = Object.freeze({
157 x: b.x + rank * (maxRank === 0 ? 0 : (b.width - nodeWidth) / maxRank),
158 y,
159 width: nodeWidth,
160 height: size,
161 });
162 const name = options.label ? access(options.label, datum) : String(key);
163 const quantity = Math.max(incoming.get(key)!, outgoing.get(key)!);
164 const labelBounds = Object.freeze({
165 x: bounds.x + bounds.width + 8,
166 y: bounds.y + Math.max(0, bounds.height / 2 - 14),
167 width: 132,
168 height: 16,
169 });
170 const detailBounds = Object.freeze({
171 x: labelBounds.x,
172 y: labelBounds.y + 16,
173 width: labelBounds.width,
174 height: 16,
175 });
176 const detailText = options.detail
177 ? access(options.detail, datum)
178 : options.formatValue
179 ? options.formatValue(quantity)
180 : `${quantity} ${options.unit}`;
181 geometry.set(
182 key,
183 Object.freeze({
184 key,
185 datum,
186 bounds,
187 incomingValue: incoming.get(key)!,
188 outgoingValue: outgoing.get(key)!,
189 netValue: outgoing.get(key)! - incoming.get(key)!,
190 label: Object.freeze({
191 text: name,
192 bounds: labelBounds,
193 rotationDegrees: 0,
194 }),
195 detail: Object.freeze({
196 text: detailText,
197 bounds: detailBounds,
198 rotationDegrees: 0,
199 }),
200 }),
201 );
202 y += size + nodeGap;
203 }
204 });
205 const sourceOffsets = new Map<VizKey, number>(),
206 targetOffsets = new Map<VizKey, number>();
207 for (const key of nodes.keys()) {
208 sourceOffsets.set(key, 0);
209 targetOffsets.set(key, 0);
210 }
211 const flows: SankeyFlowGeometry<E>[] = edges.map(
212 ({ key, edge, sourceKey, targetKey, value }) => {
213 const source = geometry.get(sourceKey)!,
214 target = geometry.get(targetKey)!,
215 thickness = value * scale;
216 const sourceTop = source.bounds.y + sourceOffsets.get(sourceKey)!;
217 const targetTop = target.bounds.y + targetOffsets.get(targetKey)!;
218 sourceOffsets.set(sourceKey, sourceOffsets.get(sourceKey)! + thickness);
219 targetOffsets.set(targetKey, targetOffsets.get(targetKey)! + thickness);
220 const sourceSpan = Object.freeze({
221 top: Object.freeze({
222 x: source.bounds.x + source.bounds.width,
223 y: sourceTop,
224 }),
225 bottom: Object.freeze({
226 x: source.bounds.x + source.bounds.width,
227 y: sourceTop + thickness,
228 }),
229 });
230 const targetSpan = Object.freeze({
231 top: Object.freeze({ x: target.bounds.x, y: targetTop }),
232 bottom: Object.freeze({ x: target.bounds.x, y: targetTop + thickness }),
233 });
234 const middle = (sourceSpan.top.x + targetSpan.top.x) / 2;
235 const segments = Object.freeze([
236 { type: "move" as const, x: sourceSpan.top.x, y: sourceSpan.top.y },
237 {
238 type: "cubic" as const,
239 cp1x: middle,
240 cp1y: sourceSpan.top.y,
241 cp2x: middle,
242 cp2y: targetSpan.top.y,
243 x: targetSpan.top.x,
244 y: targetSpan.top.y,
245 },
246 {
247 type: "line" as const,
248 x: targetSpan.bottom.x,
249 y: targetSpan.bottom.y,
250 },
251 {
252 type: "cubic" as const,
253 cp1x: middle,
254 cp1y: targetSpan.bottom.y,
255 cp2x: middle,
256 cp2y: sourceSpan.bottom.y,
257 x: sourceSpan.bottom.x,
258 y: sourceSpan.bottom.y,
259 },
260 { type: "close" as const },
261 ]);
262 return Object.freeze({
263 key,
264 datum: edge,
265 sourceKey,
266 targetKey,
267 value,
268 unit: options.unit,
269 thickness,
270 sourceSpan,
271 targetSpan,
272 route: Object.freeze({
273 sourceAnchor: sourceSpan.top,
274 targetAnchor: targetSpan.top,
275 segments,
276 arrowSegments: null,
277 }),
278 segments,
279 path: path(segments),
280 arrowPath: null,
281 });
282 },
283 );
284 return Object.freeze({
285 bounds: Object.freeze({ ...b }),
286 unit: options.unit,
287 nodes: Object.freeze(Array.from(geometry.values())),
288 flows: Object.freeze(flows),
289 });
290 }
291
292 /** Default node paint for custom Sankey compositions.
293 * @param _node - Node geometry.
294 * @returns Resolved node paint.
295 * @see {@link SankeyNode}
296 */
297 export function defaultSankeyNodeStyle<N>(
298 _node: SankeyNodeGeometry<N>,
299 ): NodeStyle {
300 return { fill: "#0f766e", cornerRadius: 3 };
301 }
302 /** Default flow paint for custom Sankey compositions.
303 * @param _flow - Flow geometry.
304 * @returns Resolved flow paint.
305 * @see {@link SankeyFlow}
306 */
307 export function defaultSankeyFlowStyle<E>(
308 _flow: SankeyFlowGeometry<E>,
309 ): EdgeStyle {
310 return { fill: "rgba(15, 118, 110, 0.34)" };
311 }
312 /** Draw one supplied Sankey node.
313 * @param argument - Node props.
314 * @returns Canvas node.
315 * @see {@link SankeyNodeGeometry}
316 */
317 export function SankeyNode<N>({
318 node,
319 style: input,
320 children,
321 ...events
322 }: GraphNodeProps<N> & { readonly node: SankeyNodeGeometry<N> }): PibblNode {
323 return (
324 <GraphNode node={node} style={input} {...events}>
325 {children}
326 </GraphNode>
327 );
328 }
329 /** Draw one supplied Sankey flow.
330 * @param argument - Flow props.
331 * @returns Canvas node.
332 * @see {@link SankeyFlowGeometry}
333 */
334 export function SankeyFlow<E>({
335 flow,
336 style: input,
337 ...events
338 }: MarkInteraction & {
339 readonly flow: SankeyFlowGeometry<E>;
340 readonly style?: Style<EdgeStyle>;
341 }): PibblNode {
342 return (
343 <SvgPath
344 {...events}
345 style={{ ...(resolveSignalValue(input) ?? {}), d: flow.path }}
346 />
347 );
348 }
349 /** Render a weighted acyclic flow graph.
350 * @param props - Graph data and presentation.
351 * @returns Canvas node.
352 * @see {@link layoutSankey}
353 */
354 export function Sankey<N, E>(props: SankeyProps<N, E>): PibblNode {
355 const frame = useGraphFrame(props.style),
356 style = frame.style;
357 if (!frame.bounds.width || !frame.bounds.height)
358 return <Group style={frame.groupStyle}>{null}</Group>;
359 const layout = layoutSankey(resolveSignalValue(props.graph), {
360 ...props,
361 bounds: frame.bounds,
362 nodeWidth: style.nodeWidth,
363 nodeGap: style.nodeGap,
364 });
365 return (
366 <Group style={frame.groupStyle}>
367 {layout.flows.map((flow) => (
368 <Group
369 key={String(flow.key)}
370 onClick={(event) => props.onFlowClick?.(flow, event)}
371 >
372 {props.renderFlow ? (
373 props.renderFlow(flow)
374 ) : (
375 <SankeyFlow
376 flow={flow}
377 style={{
378 ...defaultSankeyFlowStyle(flow),
379 ...resolveMarkStyle(flow, props.flowStyle),
380 }}
381 />
382 )}
383 </Group>
384 ))}
385 {layout.nodes.map((node) => (
386 <Group
387 key={String(node.key)}
388 onClick={(event) => props.onNodeClick?.(node, event)}
389 >
390 {props.renderNode ? (
391 props.renderNode(node)
392 ) : (
393 <Group>
394 <SankeyNode
395 node={node}
396 style={{
397 ...defaultSankeyNodeStyle(node),
398 ...resolveMarkStyle(node, props.nodeStyle),
399 }}
400 />
401 <GraphLabel
402 label={node.label}
403 style={{
404 ...defaultGraphLabelStyle(node.label),
405 ...resolveSignalValue(props.labelStyle),
406 }}
407 />
408 <GraphLabel
409 label={node.detail!}
410 style={{
411 ...defaultGraphLabelStyle(node.detail!),
412 font: "11px sans-serif",
413 ...resolveSignalValue(props.labelStyle),
414 }}
415 />
416 </Group>
417 )}
418 </Group>
419 ))}
420 </Group>
421 );
422 }
423
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.