packages/core/src/features/viz/lib/graph/chord.tsx
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import {
2 Group,
3 SvgPath,
4 resolveSignalValue,
5 PathGeometry,
6 toSvgPathData,
7 } from "@pibbl/core";
8 import type { PathSegment, PibblNode } from "@pibbl/core";
9 import type {
10 Accessor,
11 ChordBandGeometry,
12 ChordData,
13 ChordDiagramProps,
14 ChordLayout,
15 ChordOptions,
16 ChordRibbonGeometry,
17 EdgeStyle,
18 MarkInteraction,
19 Style,
20 VizKey,
21 } from "./types.js";
22 import {
23 defaultGraphLabelStyle,
24 GraphLabel,
25 resolveMarkStyle,
26 useGraphFrame,
27 } from "./shared.js";
28
29 function access<D, V>(input: Accessor<D, V>, datum: D): V {
30 return typeof input === "function"
31 ? input(datum)
32 : (datum as Record<PropertyKey, V>)[input];
33 }
34 function finite(value: number, name: string, zero = false) {
35 if (!Number.isFinite(value) || (zero && value < 0))
36 throw new RangeError(
37 `layoutChords: ${name} must be finite${zero ? " and nonnegative" : ""}.`,
38 );
39 return value;
40 }
41 function point(cx: number, cy: number, radius: number, degrees: number) {
42 const radians = ((degrees - 90) * Math.PI) / 180;
43 return {
44 x: cx + Math.cos(radians) * radius,
45 y: cy + Math.sin(radians) * radius,
46 };
47 }
48 function svg(segments: readonly PathSegment[]) {
49 const geometry = new PathGeometry();
50 geometry.spliceSegments(0, 0, segments);
51 return toSvgPathData(geometry);
52 }
53 function bandSegments(
54 cx: number,
55 cy: number,
56 outer: number,
57 inner: number,
58 start: number,
59 end: number,
60 ): readonly PathSegment[] {
61 const first = point(cx, cy, outer, start),
62 last = point(cx, cy, inner, end),
63 radians = Math.PI / 180;
64 return Object.freeze([
65 { type: "move", ...first },
66 {
67 type: "arc",
68 cx,
69 cy,
70 ux: outer,
71 uy: 0,
72 vx: 0,
73 vy: outer,
74 startAngle: (start - 90) * radians,
75 sweep: (end - start) * radians,
76 },
77 { type: "line", ...last },
78 {
79 type: "arc",
80 cx,
81 cy,
82 ux: inner,
83 uy: 0,
84 vx: 0,
85 vy: inner,
86 startAngle: (end - 90) * radians,
87 sweep: (start - end) * radians,
88 },
89 { type: "close" },
90 ] as PathSegment[]);
91 }
92
93 /** Computes a directed chord layout, aggregating repeated ordered transfer pairs.
94 * @param data - Ordered category transfers. See {@link ChordData}.
95 * @param options - Accessors, bounds, angular spacing, and unit. See {@link ChordOptions}.
96 * @returns Immutable bands and directed ribbon geometry. See {@link ChordLayout}.
97 */
98 export function layoutChords<C, T>(
99 data: ChordData<C, T>,
100 options: ChordOptions<C, T>,
101 ): ChordLayout<C, T> {
102 const b = options.bounds;
103 finite(b.x, "bounds.x");
104 finite(b.y, "bounds.y");
105 finite(b.width, "bounds.width", true);
106 finite(b.height, "bounds.height", true);
107 const width = finite(options.bandWidth ?? 20, "bandWidth", true),
108 pad = finite(options.padAngle ?? 2, "padAngle", true),
109 start = finite(options.startAngle ?? 0, "startAngle");
110 if (data.categories.length * pad >= 360 && data.categories.length)
111 throw new RangeError(
112 "layoutChords: total padAngle must be less than 360 degrees.",
113 );
114 const categories = new Map<VizKey, C>();
115 for (const category of data.categories) {
116 const key = access(options.categoryKey, category);
117 if (categories.has(key))
118 throw new Error(`layoutChords: duplicate category key ${String(key)}.`);
119 categories.set(key, category);
120 }
121 const groups = new Map<
122 string,
123 { source: VizKey; target: VizKey; records: T[]; value: number }
124 >();
125 const incoming = new Map<VizKey, number>(),
126 outgoing = new Map<VizKey, number>();
127 for (const key of categories.keys()) {
128 incoming.set(key, 0);
129 outgoing.set(key, 0);
130 }
131 for (const transfer of data.transfers) {
132 const source = access(options.source, transfer),
133 target = access(options.target, transfer),
134 amount = finite(access(options.value, transfer), "transfer value", true);
135 if (!categories.has(source) || !categories.has(target))
136 throw new RangeError(
137 "layoutChords: transfer endpoint is not a category key.",
138 );
139 incoming.set(
140 target,
141 finite(incoming.get(target)! + amount, "incoming total", true),
142 );
143 outgoing.set(
144 source,
145 finite(outgoing.get(source)! + amount, "outgoing total", true),
146 );
147 const id = `chord:${typeof source}:${String(source)}\u0000${typeof target}:${String(target)}`;
148 const prior = groups.get(id);
149 if (prior) {
150 prior.records.push(transfer);
151 prior.value = finite(prior.value + amount, "transfer total", true);
152 } else
153 groups.set(id, { source, target, records: [transfer], value: amount });
154 }
155 const total = Array.from(groups.values()).reduce(
156 (sum, entry) => sum + entry.value,
157 0,
158 );
159 const cx = b.x + b.width / 2,
160 cy = b.y + b.height / 2,
161 radius = Math.max(0, Math.min(b.width, b.height) / 2 - 28),
162 inner = Math.max(0, radius - width);
163 const weight = Array.from(categories.keys()).map(
164 (key) => incoming.get(key)! + outgoing.get(key)!,
165 );
166 const sum = weight.reduce((a, n) => a + n, 0);
167 finite(total, "transfer total", true);
168 finite(sum, "incident total", true);
169 const usable = 360 - data.categories.length * pad;
170 let angle = start;
171 const bands: ChordBandGeometry<C>[] = [];
172 const arcs = new Map<
173 VizKey,
174 { start: number; end: number; cursor: number }
175 >();
176 for (let index = 0; index < data.categories.length; index++) {
177 const datum = data.categories[index],
178 key = access(options.categoryKey, datum),
179 span = sum === 0 ? 0 : (weight[index] / sum) * usable,
180 arc = Object.freeze({
181 center: Object.freeze({ x: cx, y: cy }),
182 radius,
183 startAngleDegrees: angle,
184 endAngleDegrees: angle + span,
185 });
186 const segments = bandSegments(cx, cy, radius, inner, angle, angle + span);
187 const mid = angle + span / 2,
188 labelPoint = point(cx, cy, radius + 18, mid);
189 const label = Object.freeze({
190 text: options.label ? access(options.label, datum) : String(key),
191 bounds: Object.freeze({
192 x: labelPoint.x - 45,
193 y: labelPoint.y - 10,
194 width: 90,
195 height: 20,
196 }),
197 rotationDegrees: 0,
198 });
199 bands.push(
200 Object.freeze({
201 key,
202 datum,
203 incomingValue: incoming.get(key)!,
204 outgoingValue: outgoing.get(key)!,
205 arc,
206 innerRadius: inner,
207 segments,
208 path: svg(segments),
209 label,
210 }),
211 );
212 arcs.set(key, { start: angle, end: angle + span, cursor: angle });
213 angle += span + pad;
214 }
215 const ribbons: ChordRibbonGeometry<T>[] = [];
216 for (const entry of groups.values()) {
217 if (entry.value === 0) continue;
218 const source = arcs.get(entry.source)!,
219 target = arcs.get(entry.target)!;
220 const sourceWeight =
221 incoming.get(entry.source)! + outgoing.get(entry.source)!,
222 targetWeight = incoming.get(entry.target)! + outgoing.get(entry.target)!;
223 const sourceSpan =
224 sourceWeight === 0
225 ? 0
226 : ((source.end - source.start) * entry.value) / sourceWeight,
227 targetSpan =
228 targetWeight === 0
229 ? 0
230 : ((target.end - target.start) * entry.value) / targetWeight;
231 const sourceArc = Object.freeze({
232 center: Object.freeze({ x: cx, y: cy }),
233 radius: inner,
234 startAngleDegrees: source.cursor,
235 endAngleDegrees: source.cursor + sourceSpan,
236 });
237 source.cursor += sourceSpan;
238 const targetStart = target.cursor;
239 const targetArc = Object.freeze({
240 center: Object.freeze({ x: cx, y: cy }),
241 radius: inner,
242 startAngleDegrees: targetStart,
243 endAngleDegrees: targetStart + targetSpan,
244 });
245 target.cursor += targetSpan;
246 const a = point(cx, cy, inner, sourceArc.startAngleDegrees),
247 d = point(cx, cy, inner, targetArc.startAngleDegrees);
248 const segments = Object.freeze([
249 { type: "move" as const, ...a },
250 {
251 type: "arc" as const,
252 cx,
253 cy,
254 ux: inner,
255 uy: 0,
256 vx: 0,
257 vy: inner,
258 startAngle: ((sourceArc.startAngleDegrees - 90) * Math.PI) / 180,
259 sweep:
260 ((sourceArc.endAngleDegrees - sourceArc.startAngleDegrees) *
261 Math.PI) /
262 180,
263 },
264 {
265 type: "quadratic" as const,
266 cpx: cx,
267 cpy: cy,
268 x: d.x,
269 y: d.y,
270 },
271 {
272 type: "arc" as const,
273 cx,
274 cy,
275 ux: inner,
276 uy: 0,
277 vx: 0,
278 vy: inner,
279 startAngle: ((targetArc.startAngleDegrees - 90) * Math.PI) / 180,
280 sweep:
281 ((targetArc.endAngleDegrees - targetArc.startAngleDegrees) *
282 Math.PI) /
283 180,
284 },
285 {
286 type: "quadratic" as const,
287 cpx: cx,
288 cpy: cy,
289 x: a.x,
290 y: a.y,
291 },
292 { type: "close" as const },
293 ]);
294 ribbons.push(
295 Object.freeze({
296 key: `${typeof entry.source}:${String(entry.source)}\u0000${typeof entry.target}:${String(entry.target)}`,
297 sourceKey: entry.source,
298 targetKey: entry.target,
299 records: Object.freeze(entry.records),
300 value: entry.value,
301 sourceArc,
302 targetArc,
303 segments,
304 path: svg(segments),
305 }),
306 );
307 }
308 return Object.freeze({
309 bounds: Object.freeze({ ...b }),
310 unit: options.unit,
311 total,
312 bands: Object.freeze(bands),
313 ribbons: Object.freeze(ribbons),
314 });
315 }
316
317 /** Default outer-band paint for custom chord compositions.
318 * @param _band - Band geometry.
319 * @returns Resolved band paint.
320 * @see {@link ChordBand}
321 */
322 export function defaultChordBandStyle<C>(
323 _band: ChordBandGeometry<C>,
324 ): EdgeStyle {
325 return { fill: "#0f766e" };
326 }
327 /** Default directed-ribbon paint for custom chord compositions.
328 * @param _ribbon - Ribbon geometry.
329 * @returns Resolved ribbon paint.
330 * @see {@link ChordRibbon}
331 */
332 export function defaultChordRibbonStyle<T>(
333 _ribbon: ChordRibbonGeometry<T>,
334 ): EdgeStyle {
335 return { fill: "rgba(15, 118, 110, 0.3)" };
336 }
337 /** Draw one supplied category band.
338 * @param argument - Band props.
339 * @returns Canvas node.
340 * @see {@link ChordBandGeometry}
341 */
342 export function ChordBand<C>({
343 band,
344 style: input,
345 ...events
346 }: MarkInteraction & {
347 readonly band: ChordBandGeometry<C>;
348 readonly style?: Style<EdgeStyle>;
349 }): PibblNode {
350 return (
351 <SvgPath
352 {...events}
353 style={{ ...(resolveSignalValue(input) ?? {}), d: band.path }}
354 />
355 );
356 }
357 /** Draw one supplied directed ribbon.
358 * @param argument - Ribbon props.
359 * @returns Canvas node.
360 * @see {@link ChordRibbonGeometry}
361 */
362 export function ChordRibbon<T>({
363 ribbon,
364 style: input,
365 ...events
366 }: MarkInteraction & {
367 readonly ribbon: ChordRibbonGeometry<T>;
368 readonly style?: Style<EdgeStyle>;
369 }): PibblNode {
370 return (
371 <SvgPath
372 {...events}
373 style={{ ...(resolveSignalValue(input) ?? {}), d: ribbon.path }}
374 />
375 );
376 }
377 /** Render a directed transfer chord diagram.
378 * @param props - Transfer data and presentation.
379 * @returns Canvas node.
380 * @see {@link layoutChords}
381 */
382 export function ChordDiagram<C, T>(props: ChordDiagramProps<C, T>): PibblNode {
383 const frame = useGraphFrame(props.style),
384 style = frame.style;
385 if (!frame.bounds.width || !frame.bounds.height)
386 return <Group style={frame.groupStyle}>{null}</Group>;
387 const layout = layoutChords(resolveSignalValue(props.data), {
388 ...props,
389 bounds: frame.bounds,
390 bandWidth: style.bandWidth,
391 padAngle: style.padAngle,
392 startAngle: style.startAngle,
393 });
394 return (
395 <Group style={frame.groupStyle}>
396 {layout.ribbons.map((ribbon) => (
397 <Group
398 key={ribbon.key}
399 onClick={(event) => props.onRibbonClick?.(ribbon, event)}
400 >
401 {props.renderRibbon ? (
402 props.renderRibbon(ribbon)
403 ) : (
404 <ChordRibbon
405 ribbon={ribbon}
406 keyboardFocusable={Boolean(props.onRibbonClick)}
407 style={{
408 ...defaultChordRibbonStyle(ribbon),
409 ...resolveMarkStyle(ribbon, props.ribbonStyle),
410 }}
411 />
412 )}
413 </Group>
414 ))}
415 {layout.bands.map((band) => (
416 <Group
417 key={String(band.key)}
418 onClick={(event) => props.onBandClick?.(band, event)}
419 >
420 {props.renderBand ? (
421 props.renderBand(band)
422 ) : (
423 <Group>
424 <ChordBand
425 band={band}
426 style={{
427 ...defaultChordBandStyle(band),
428 ...resolveMarkStyle(band, props.bandStyle),
429 }}
430 />
431 <GraphLabel
432 label={band.label}
433 style={{
434 ...defaultGraphLabelStyle(band.label),
435 ...resolveSignalValue(props.labelStyle),
436 }}
437 />
438 </Group>
439 )}
440 </Group>
441 ))}
442 </Group>
443 );
444 }
445
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.