Skip to content

packages/core/src/features/viz/lib/graph/neighborhood.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, resolveSignalValue, type PibblNode } from "@pibbl/core";
2 import {
3   defaultGraphEdgeStyle,
4   defaultGraphLabelStyle,
5   defaultGraphNodeStyle,
6   GraphEdge,
7   GraphLabel,
8   GraphNode,
9   resolveMarkStyle,
10   useGraphFrame,
11 } from "./shared.js";
12 import type {
13   GraphData,
14   GraphEdgeGeometry,
15   NeighborhoodLayout,
16   NeighborhoodNodeGeometry,
17   NeighborhoodOptions,
18   NeighborhoodStyle,
19   RadialNeighborhoodProps,
20   VizKey,
21 } from "./types.js";
22 import {
23   checkedBounds,
24   finiteGap,
25   finiteSize,
26   hierarchyLabel,
27 } from "./hierarchy.js";
28 import { readAccessor } from "./shared.js";
29 
30 function key(value: unknown, name: string): VizKey {
31   if (
32     typeof value === "string" ||
33     (typeof value === "number" && Number.isFinite(value))
34   )
35     return value;
36   throw new TypeError(`${name}: key must be a string or finite number.`);
37 }
38 
39 /** Lay out the reachable neighborhood around one stable key in concentric rings.
40  * @param graph - Nodes and edges in source order.
41  * @param options - Accessors, center, hops, and finite bounds.
42  * @returns Immutable neighborhood geometry. @see {@link NeighborhoodLayout} */
43 export function layoutNeighborhood<N, E>(
44   graph: GraphData<N, E>,
45   options: NeighborhoodOptions<N, E>,
46 ): NeighborhoodLayout<N, E> {
47   const bounds = checkedBounds(options.bounds, "layoutNeighborhood");
48   const hops = options.hops ?? 2;
49   if (!Number.isSafeInteger(hops) || hops < 0)
50     throw new RangeError(
51       "layoutNeighborhood: hops must be a nonnegative safe integer.",
52     );
53   const ringGap = finiteGap(options.ringGap, 120, "layoutNeighborhood ringGap");
54   const nodeGap = finiteGap(options.nodeGap, 12, "layoutNeighborhood nodeGap");
55   const nodes = new Map<VizKey, N>();
56   const order = new Map<VizKey, number>();
57   graph.nodes.forEach((node, index) => {
58     const id = key(
59       readAccessor(node, options.nodeKey),
60       "layoutNeighborhood nodeKey",
61     );
62     if (nodes.has(id))
63       throw new Error(`layoutNeighborhood: duplicate node key ${String(id)}.`);
64     nodes.set(id, node);
65     order.set(id, index);
66   });
67   if (!nodes.has(options.centerKey))
68     throw new Error(
69       `layoutNeighborhood: unknown centerKey ${String(options.centerKey)}.`,
70     );
71   const edges = graph.edges.map((edge) => {
72     const sourceKey = key(
73       readAccessor(edge, options.source),
74       "layoutNeighborhood source",
75     );
76     const targetKey = key(
77       readAccessor(edge, options.target),
78       "layoutNeighborhood target",
79     );
80     const edgeKey = key(
81       readAccessor(edge, options.edgeKey),
82       "layoutNeighborhood edgeKey",
83     );
84     if (!nodes.has(sourceKey) || !nodes.has(targetKey))
85       throw new Error(
86         `layoutNeighborhood: edge ${String(edgeKey)} references an unknown node.`,
87       );
88     return { edge, edgeKey, sourceKey, targetKey };
89   });
90   const direction = options.direction ?? "outbound";
91   const adjacency = new Map<VizKey, VizKey[]>();
92   for (const { sourceKey, targetKey } of edges) {
93     const add = (a: VizKey, b: VizKey) => {
94       const list = adjacency.get(a) ?? [];
95       list.push(b);
96       adjacency.set(a, list);
97     };
98     if (direction !== "inbound") add(sourceKey, targetKey);
99     if (direction !== "outbound") add(targetKey, sourceKey);
100   }
101   const hop = new Map<VizKey, number>([[options.centerKey, 0]]);
102   const queue = [options.centerKey];
103   for (let index = 0; index < queue.length; index++) {
104     const current = queue[index];
105     const depth = hop.get(current)!;
106     if (depth === hops) continue;
107     for (const next of adjacency.get(current) ?? [])
108       if (!hop.has(next)) {
109         hop.set(next, depth + 1);
110         queue.push(next);
111       }
112   }
113   const rings = Array.from({ length: hops + 1 }, () => [] as VizKey[]);
114   for (const [id, depth] of hop) rings[depth].push(id);
115   for (const ring of rings) ring.sort((a, b) => order.get(a)! - order.get(b)!);
116   const sizes = new Map<VizKey, ReturnType<typeof finiteSize>>();
117   let maxFootprint = 0;
118   for (const id of hop.keys()) {
119     const size = finiteSize(
120       nodes.get(id)!,
121       options.nodeSize ?? { width: 48, height: 48 },
122       "layoutNeighborhood",
123     );
124     sizes.set(id, size);
125     maxFootprint = Math.max(maxFootprint, Math.hypot(size.width, size.height));
126   }
127   const center = {
128     x: bounds.x + bounds.width / 2,
129     y: bounds.y + bounds.height / 2,
130   };
131   const usedHops = Math.max(0, ...hop.values());
132   const outer =
133     usedHops === 0 ? maxFootprint / 2 : maxFootprint + usedHops * ringGap;
134   if (outer * 2 > Math.min(bounds.width, bounds.height))
135     throw new RangeError(
136       "layoutNeighborhood: bounds are too small for the requested rings.",
137     );
138   const geometry: NeighborhoodNodeGeometry<N>[] = [];
139   for (let depth = 0; depth < rings.length; depth++) {
140     const ring = rings[depth];
141     const radius = depth === 0 ? 0 : maxFootprint / 2 + depth * ringGap;
142     if (
143       depth > 0 &&
144       ring.length > 1 &&
145       2 * radius * Math.sin(Math.PI / ring.length) < maxFootprint + nodeGap
146     )
147       throw new RangeError(
148         "layoutNeighborhood: ring is too crowded for nodeGap and nodeSize.",
149       );
150     ring.forEach((id, index) => {
151       const angle =
152         depth === 0
153           ? -Math.PI / 2
154           : -Math.PI / 2 + (Math.PI * 2 * index) / ring.length;
155       const size = sizes.get(id)!;
156       const x = center.x + Math.cos(angle) * radius - size.width / 2;
157       const y = center.y + Math.sin(angle) * radius - size.height / 2;
158       const datum = nodes.get(id)!;
159       const box = Object.freeze({
160         x,
161         y,
162         width: size.width,
163         height: size.height,
164       });
165       geometry.push(
166         Object.freeze({
167           key: id,
168           datum,
169           bounds: box,
170           label: hierarchyLabel(
171             datum,
172             options.label,
173             {
174               x,
175               y: y + size.height + 4,
176               width: size.width,
177               height: 18,
178             },
179             String(id),
180           ),
181           detail:
182             options.detail === undefined
183               ? null
184               : hierarchyLabel(datum, options.detail, {
185                   x,
186                   y: y + size.height + 22,
187                   width: size.width,
188                   height: 16,
189                 }),
190           hop: depth,
191         }),
192       );
193     });
194   }
195   const byKey = new Map(geometry.map((node) => [node.key, node]));
196   const resultEdges: GraphEdgeGeometry<E>[] = [];
197   for (const entry of edges)
198     if (byKey.has(entry.sourceKey) && byKey.has(entry.targetKey)) {
199       const source = byKey.get(entry.sourceKey)!;
200       const target = byKey.get(entry.targetKey)!;
201       const sourceAnchor = {
202         x: source.bounds.x + source.bounds.width / 2,
203         y: source.bounds.y + source.bounds.height / 2,
204       };
205       const targetAnchor = {
206         x: target.bounds.x + target.bounds.width / 2,
207         y: target.bounds.y + target.bounds.height / 2,
208       };
209       const segments = Object.freeze([
210         { type: "move" as const, ...sourceAnchor },
211         { type: "line" as const, ...targetAnchor },
212       ]);
213       resultEdges.push(
214         Object.freeze({
215           key: entry.edgeKey,
216           datum: entry.edge,
217           sourceKey: entry.sourceKey,
218           targetKey: entry.targetKey,
219           route: Object.freeze({
220             sourceAnchor: Object.freeze(sourceAnchor),
221             targetAnchor: Object.freeze(targetAnchor),
222             segments,
223             arrowSegments: null,
224           }),
225           path: `M ${sourceAnchor.x} ${sourceAnchor.y} L ${targetAnchor.x} ${targetAnchor.y}`,
226           arrowPath: null,
227         }),
228       );
229     }
230   return Object.freeze({
231     bounds,
232     centerKey: options.centerKey,
233     nodes: Object.freeze(geometry),
234     edges: Object.freeze(resultEdges),
235     omittedKeys: Object.freeze([...nodes.keys()].filter((id) => !hop.has(id))),
236   });
237 }
238 
239 /** Render an interactive radial neighborhood from ordinary graph records.
240  * @param props - Reactive graph, center, presentation, and frame style.
241  * @returns Canvas composition. @see {@link layoutNeighborhood} */
242 export function RadialNeighborhood<N, E>(
243   props: RadialNeighborhoodProps<N, E>,
244 ): PibblNode {
245   const frame = useGraphFrame<NeighborhoodStyle>(props.style);
246   const graph = resolveSignalValue(props.graph);
247   const centerKey = resolveSignalValue(props.centerKey);
248   const hops =
249     props.hops === undefined ? undefined : resolveSignalValue(props.hops);
250   if (frame.bounds.width === 0 || frame.bounds.height === 0)
251     return <Group style={frame.groupStyle}>{null}</Group>;
252   const layout = layoutNeighborhood(graph, {
253     ...props,
254     bounds: frame.bounds,
255     centerKey,
256     hops,
257     ringGap: frame.style.ringGap,
258     nodeGap: frame.style.nodeGap,
259   });
260   return (
261     <Group style={frame.groupStyle}>
262       {layout.edges.map((edge) =>
263         props.renderEdge ? (
264           <Group
265             key={edge.key}
266             onClick={(event) => props.onEdgeClick?.(edge, event)}
267           >
268             {props.renderEdge(edge)}
269           </Group>
270         ) : (
271           <GraphEdge
272             key={edge.key}
273             edge={edge}
274             style={{
275               ...defaultGraphEdgeStyle(edge),
276               ...resolveMarkStyle(edge, props.edgeStyle),
277             }}
278             onClick={(event) => props.onEdgeClick?.(edge, event)}
279           />
280         ),
281       )}
282       {layout.nodes.map((node) =>
283         props.renderNode ? (
284           <Group
285             key={node.key}
286             onClick={(event) => props.onNodeClick?.(node, event)}
287           >
288             {props.renderNode(node)}
289           </Group>
290         ) : (
291           <Group key={node.key}>
292             <GraphNode
293               node={node}
294               style={{
295                 ...defaultGraphNodeStyle(node),
296                 ...resolveMarkStyle(node, props.nodeStyle),
297               }}
298               onClick={(event) => props.onNodeClick?.(node, event)}
299             />
300             <GraphLabel
301               label={node.label}
302               style={{
303                 ...defaultGraphLabelStyle(node.label),
304                 ...resolveMarkStyle(node, props.labelStyle),
305               }}
306             />
307           </Group>
308         ),
309       )}
310     </Group>
311   );
312 }
313 

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