Skip to content

packages/core/src/features/viz/lib/graph/bipartite.tsx

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import { Group, SvgPath, resolveSignalValue } from "@pibbl/core";
2 import type { PathSegment, PibblNode } from "@pibbl/core";
3 import type {
4   Accessor,
5   BipartiteData,
6   BipartiteGraphProps,
7   BipartiteLayout,
8   BipartiteOptions,
9   GraphNodeGeometry,
10   Size,
11   VizKey,
12 } from "./types.js";
13 import {
14   defaultGraphEdgeStyle,
15   defaultGraphLabelStyle,
16   defaultGraphNodeStyle,
17   GraphLabel,
18   GraphNode,
19   resolveMarkStyle,
20   useGraphFrame,
21 } from "./shared.js";
22 
23 function access<D, V>(input: Accessor<D, V>, datum: D): V {
24   return typeof input === "function"
25     ? input(datum)
26     : (datum as Record<PropertyKey, V>)[input];
27 }
28 function finite(value: number, name: string, zero = false) {
29   if (!Number.isFinite(value) || (zero && value < 0))
30     throw new RangeError(
31       `layoutBipartite: ${name} must be finite${zero ? " and nonnegative" : ""}.`,
32     );
33   return value;
34 }
35 function label(
36   text: string,
37   bounds: { x: number; y: number; width: number; height: number },
38 ) {
39   return Object.freeze({
40     text,
41     bounds: Object.freeze(bounds),
42     rotationDegrees: 0,
43   });
44 }
45 function route(a: { x: number; y: number }, b: { x: number; y: number }) {
46   const middle = (a.x + b.x) / 2;
47   const segments = Object.freeze([
48     { type: "move" as const, x: a.x, y: a.y },
49     {
50       type: "cubic" as const,
51       cp1x: middle,
52       cp1y: a.y,
53       cp2x: middle,
54       cp2y: b.y,
55       x: b.x,
56       y: b.y,
57     },
58   ]);
59   return Object.freeze({
60     sourceAnchor: Object.freeze(a),
61     targetAnchor: Object.freeze(b),
62     segments,
63     arrowSegments: null,
64   });
65 }
66 function path(route: { segments: readonly PathSegment[] }) {
67   return route.segments
68     .map((segment) =>
69       segment.type === "move"
70         ? `M ${segment.x} ${segment.y}`
71         : segment.type === "cubic"
72           ? `C ${segment.cp1x} ${segment.cp1y} ${segment.cp2x} ${segment.cp2y} ${segment.x} ${segment.y}`
73           : "",
74     )
75     .join(" ");
76 }
77 function placed<D>(
78   data: readonly D[],
79   keyBy: Accessor<D, VizKey>,
80   labelBy: Accessor<D, string> | undefined,
81   atX: number,
82   bounds: { y: number; height: number },
83   size: ((datum: D) => Size) | undefined,
84   gap: number,
85 ): readonly GraphNodeGeometry<D>[] {
86   const total =
87     data.reduce((sum, datum) => sum + (size?.(datum).height ?? 34), 0) +
88     Math.max(0, data.length - 1) * gap;
89   let y = bounds.y + Math.max(0, (bounds.height - total) / 2);
90   const seen = new Set<VizKey>();
91   return Object.freeze(
92     data.map((datum) => {
93       const key = access(keyBy, datum);
94       if (seen.has(key))
95         throw new Error(
96           `layoutBipartite: duplicate node key ${String(key)} on one side.`,
97         );
98       seen.add(key);
99       const dimensions = size?.(datum) ?? { width: 150, height: 34 };
100       const box = {
101         x: atX,
102         y,
103         width: dimensions.width,
104         height: dimensions.height,
105       };
106       y += dimensions.height + gap;
107       return Object.freeze({
108         key,
109         datum,
110         bounds: Object.freeze(box),
111         label: label(labelBy ? access(labelBy, datum) : String(key), box),
112         detail: null,
113       });
114     }),
115   );
116 }
117 
118 /** Arranges two explicit entity sets in columns, retaining side-qualified identity.
119  * @param graph - Explicit left and right entities with cross-set edges. See {@link BipartiteData}.
120  * @param options - Accessors, dimensions, and column spacing. See {@link BipartiteOptions}.
121  * @returns Immutable side-aware nodes and routed edges. See {@link BipartiteLayout}.
122  */
123 export function layoutBipartite<L, R, E>(
124   graph: BipartiteData<L, R, E>,
125   options: BipartiteOptions<L, R, E>,
126 ): BipartiteLayout<L, R, E> {
127   const b = options.bounds;
128   finite(b.x, "bounds.x");
129   finite(b.y, "bounds.y");
130   finite(b.width, "bounds.width", true);
131   finite(b.height, "bounds.height", true);
132   const gap = finite(options.nodeGap ?? 12, "nodeGap", true),
133     columnGap = finite(options.columnGap ?? 120, "columnGap", true);
134   const leftSize = options.leftSize,
135     leftResolver: ((datum: L) => Size) | undefined =
136       typeof leftSize === "function"
137         ? leftSize
138         : leftSize === undefined
139           ? undefined
140           : () => leftSize;
141   const rightSize = options.rightSize,
142     rightResolver: ((datum: R) => Size) | undefined =
143       typeof rightSize === "function"
144         ? rightSize
145         : rightSize === undefined
146           ? undefined
147           : () => rightSize;
148   const left = placed(
149     graph.left,
150     options.leftKey,
151     options.leftLabel,
152     b.x,
153     b,
154     leftResolver,
155     gap,
156   );
157   const rightWidth =
158     typeof rightSize === "function" ? 150 : (rightSize?.width ?? 150);
159   const right = placed(
160     graph.right,
161     options.rightKey,
162     options.rightLabel,
163     Math.max(b.x, b.x + b.width - rightWidth),
164     b,
165     rightResolver,
166     gap,
167   );
168   const leftByKey = new Map(left.map((node) => [node.key, node])),
169     rightByKey = new Map(right.map((node) => [node.key, node]));
170   const edgeKeys = new Set<VizKey>();
171   const edges = graph.edges.map((edge) => {
172     const key = access(options.edgeKey, edge);
173     if (edgeKeys.has(key))
174       throw new Error(`layoutBipartite: duplicate edge key ${String(key)}.`);
175     edgeKeys.add(key);
176     const source = access(options.source, edge),
177       target = access(options.target, edge),
178       leftNode = leftByKey.get(source),
179       rightNode = rightByKey.get(target);
180     if (!leftNode || !rightNode)
181       throw new RangeError(
182         "layoutBipartite: every edge must point from a known left key to a known right key.",
183       );
184     const r = route(
185       {
186         x: leftNode.bounds.x + leftNode.bounds.width,
187         y: leftNode.bounds.y + leftNode.bounds.height / 2,
188       },
189       {
190         x: rightNode.bounds.x,
191         y: rightNode.bounds.y + rightNode.bounds.height / 2,
192       },
193     );
194     return Object.freeze({
195       key,
196       datum: edge,
197       sourceKey: source,
198       targetKey: target,
199       left: leftNode,
200       right: rightNode,
201       route: r,
202       path: path(r),
203       arrowPath: null,
204     });
205   });
206   if (
207     left.length &&
208     right.length &&
209     right[0].bounds.x - (left[0].bounds.x + left[0].bounds.width) < columnGap
210   )
211     throw new RangeError(
212       "layoutBipartite: bounds are too narrow for node sizes and columnGap.",
213     );
214   return Object.freeze({
215     bounds: Object.freeze({ ...b }),
216     left,
217     right,
218     edges: Object.freeze(edges),
219   });
220 }
221 
222 /** Render left/right entity sets and their cross-set relationships.
223  * @param props - Entity data and presentation.
224  * @returns Canvas node.
225  * @see {@link layoutBipartite}
226  */
227 export function BipartiteGraph<L, R, E>(
228   props: BipartiteGraphProps<L, R, E>,
229 ): PibblNode {
230   const frame = useGraphFrame(props.style),
231     style = frame.style;
232   if (!frame.bounds.width || !frame.bounds.height)
233     return <Group style={frame.groupStyle}>{null}</Group>;
234   const layout = layoutBipartite(resolveSignalValue(props.graph), {
235     ...props,
236     bounds: frame.bounds,
237     columnGap: style.columnGap,
238     nodeGap: style.nodeGap,
239   });
240   return (
241     <Group style={frame.groupStyle}>
242       {layout.edges.map((edge) => (
243         <Group
244           key={String(edge.key)}
245           onClick={(event) => props.onEdgeClick?.(edge, event)}
246         >
247           {props.renderEdge ? (
248             props.renderEdge(edge)
249           ) : (
250             <SvgPath
251               style={{
252                 ...defaultGraphEdgeStyle(edge),
253                 ...resolveMarkStyle(edge, props.edgeStyle),
254                 d: edge.path,
255               }}
256             />
257           )}
258         </Group>
259       ))}
260       {layout.left.map((node) => (
261         <Group
262           key={`left-${String(node.key)}`}
263           onClick={(event) => props.onLeftNodeClick?.(node, event)}
264         >
265           {props.renderLeftNode ? (
266             props.renderLeftNode(node)
267           ) : (
268             <Group>
269               <GraphNode
270                 node={node}
271                 style={{
272                   ...defaultGraphNodeStyle(node),
273                   ...resolveMarkStyle(node, props.leftNodeStyle),
274                 }}
275               />
276               <GraphLabel
277                 label={node.label}
278                 style={{
279                   ...defaultGraphLabelStyle(node.label),
280                   ...resolveSignalValue(props.labelStyle),
281                 }}
282               />
283             </Group>
284           )}
285         </Group>
286       ))}
287       {layout.right.map((node) => (
288         <Group
289           key={`right-${String(node.key)}`}
290           onClick={(event) => props.onRightNodeClick?.(node, event)}
291         >
292           {props.renderRightNode ? (
293             props.renderRightNode(node)
294           ) : (
295             <Group>
296               <GraphNode
297                 node={node}
298                 style={{
299                   ...defaultGraphNodeStyle(node),
300                   ...resolveMarkStyle(node, props.rightNodeStyle),
301                 }}
302               />
303               <GraphLabel
304                 label={node.label}
305                 style={{
306                   ...defaultGraphLabelStyle(node.label),
307                   ...resolveSignalValue(props.labelStyle),
308                 }}
309               />
310             </Group>
311           )}
312         </Group>
313       ))}
314     </Group>
315   );
316 }
317 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.