packages/core/src/features/viz/lib/graph/dependency.tsx
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import type { PibblNode } from "@pibbl/core";
2 import { Group, resolveSignalValue } from "@pibbl/core";
3 import type {
4 GraphData,
5 GraphAccessors,
6 GraphLayout,
7 DependencyOptions,
8 DependencyGraphProps,
9 VizKey,
10 Size,
11 } from "./types.js";
12 import {
13 readAccessor,
14 validateBounds,
15 validKey,
16 graphNodeGeometry,
17 useGraphFrame,
18 GraphView,
19 } from "./shared.js";
20 import { orthogonalGraphRoute, routePath } from "./routes.js";
21 export function graphRecords<N, E>(
22 graph: GraphData<N, E>,
23 options: GraphAccessors<N, E>,
24 ) {
25 const nodes = new Map<VizKey, N>();
26 for (const node of graph.nodes) {
27 const key = validKey(readAccessor(node, options.nodeKey));
28 if (nodes.has(key)) throw new Error(`Duplicate graph node key ${key}.`);
29 nodes.set(key, node);
30 }
31 const edgeKeys = new Set<VizKey>();
32 const edges = graph.edges.map((datum) => {
33 const key = validKey(readAccessor(datum, options.edgeKey)),
34 sourceKey = validKey(readAccessor(datum, options.source)),
35 targetKey = validKey(readAccessor(datum, options.target));
36 if (edgeKeys.has(key)) throw new Error(`Duplicate graph edge key ${key}.`);
37 edgeKeys.add(key);
38 if (!nodes.has(sourceKey) || !nodes.has(targetKey))
39 throw new Error(`Unknown endpoint for graph edge ${key}.`);
40 return { key, datum, sourceKey, targetKey };
41 });
42 return { nodes, edges };
43 }
44 export function nodeSize<N>(
45 node: N,
46 input: Size | ((node: N) => Size) | undefined,
47 fallback: Size,
48 ): Size {
49 const size = typeof input === "function" ? input(node) : (input ?? fallback);
50 if (
51 !Number.isFinite(size.width) ||
52 !Number.isFinite(size.height) ||
53 size.width <= 0 ||
54 size.height <= 0
55 )
56 throw new RangeError("Node sizes must be finite and positive.");
57 return size;
58 }
59 /**
60 * Place a DAG in longest-path ranks with editable orthogonal routes. Cycles and insufficient bounds throw.
61 * @param graph - Original node and edge records. See {@link GraphData}.
62 * @param options - Typed accessors, finite bounds, node sizes and nonnegative gaps. See {@link DependencyOptions}.
63 * @returns Original-record node geometry and routes in local logical units. See {@link GraphLayout}.
64 */
65 export function layoutDependencies<N, E>(
66 graph: GraphData<N, E>,
67 options: DependencyOptions<N, E>,
68 ): GraphLayout<N, E> {
69 const bounds = validateBounds(options.bounds),
70 { nodes, edges } = graphRecords(graph, options);
71 const rankGap = options.rankGap ?? 72,
72 gap = options.nodeGap ?? 24;
73 if ((!Number.isFinite(rankGap) || rankGap < 0) || (!Number.isFinite(gap) || gap < 0))
74 throw new RangeError("Graph gaps must be finite and nonnegative.");
75 const incoming = new Map<VizKey, number>(
76 [...nodes.keys()].map((key) => [key, 0]),
77 ),
78 outgoing = new Map([...nodes.keys()].map((key) => [key, [] as VizKey[]]));
79 for (const edge of edges) {
80 incoming.set(edge.targetKey, incoming.get(edge.targetKey)! + 1);
81 outgoing.get(edge.sourceKey)!.push(edge.targetKey);
82 }
83 const queue = [...nodes.keys()].filter((key) => incoming.get(key) === 0),
84 ranks = new Map<VizKey, number>([...nodes.keys()].map((key) => [key, 0]));
85 for (let index = 0; index < queue.length; index++) {
86 const key = queue[index];
87 for (const target of outgoing.get(key)!) {
88 ranks.set(target, Math.max(ranks.get(target)!, ranks.get(key)! + 1));
89 incoming.set(target, incoming.get(target)! - 1);
90 if (!incoming.get(target)) queue.push(target);
91 }
92 }
93 if (queue.length !== nodes.size)
94 throw new Error("Dependency layout requires a DAG; cycle detected.");
95 const sizes = new Map(
96 [...nodes].map(([key, datum]) => [
97 key,
98 nodeSize(datum, options.nodeSize, { width: 160, height: 56 }),
99 ]),
100 );
101 const columns: VizKey[][] = [];
102 for (const key of nodes.keys()) (columns[ranks.get(key)!] ??= []).push(key);
103 const widths = columns.map((column) =>
104 Math.max(...column.map((key) => sizes.get(key)!.width)),
105 );
106 const requiredWidth =
107 widths.reduce((a, b) => a + b, 0) +
108 Math.max(0, columns.length - 1) * rankGap;
109 const heights = columns.map(
110 (column) =>
111 column.reduce<number>((sum, key) => sum + sizes.get(key)!.height, 0) +
112 Math.max(0, column.length - 1) * gap,
113 );
114 if (bounds.width === 0 || bounds.height === 0)
115 return { bounds, nodes: [], edges: [] };
116 if (
117 requiredWidth > bounds.width ||
118 heights.some((height) => height > bounds.height)
119 )
120 throw new RangeError(
121 "Dependency graph bounds are insufficient for node sizes and gaps.",
122 );
123 let x = bounds.x + (bounds.width - requiredWidth) / 2;
124 const geometry = new Map<VizKey, ReturnType<typeof graphNodeGeometry<N>>>();
125 columns.forEach((column, index) => {
126 let y = bounds.y + (bounds.height - heights[index]) / 2;
127 for (const key of column) {
128 const datum = nodes.get(key)!,
129 size = sizes.get(key)!;
130 geometry.set(
131 key,
132 graphNodeGeometry(
133 datum,
134 key,
135 { x, y, ...size },
136 options.label ? readAccessor(datum, options.label) : String(key),
137 options.detail ? readAccessor(datum, options.detail) : undefined,
138 ),
139 );
140 y += size.height + gap;
141 }
142 x += widths[index] + rankGap;
143 });
144 return {
145 bounds,
146 nodes: [...nodes.keys()].map((key) => geometry.get(key)!),
147 edges: edges.map((edge) => {
148 const source = geometry.get(edge.sourceKey)!.bounds,
149 target = geometry.get(edge.targetKey)!.bounds;
150 const route = orthogonalGraphRoute(
151 {
152 sourceAnchor: {
153 x: source.x + source.width,
154 y: source.y + source.height / 2,
155 },
156 targetAnchor: { x: target.x, y: target.y + target.height / 2 },
157 },
158 { arrowLength: 7 },
159 );
160 return {
161 ...edge,
162 route,
163 path: routePath(route.segments),
164 arrowPath: route.arrowSegments ? routePath(route.arrowSegments) : null,
165 };
166 }),
167 };
168 }
169 /**
170 * Compose the public dependency layout helper and graph marks with useful defaults.
171 * @param props - Graph input, accessors, presentation and definite allocation. See {@link DependencyGraphProps}.
172 * @returns The same graph composition available through layoutDependencies and GraphView. See {@link GraphView}.
173 */
174 export function DependencyGraph<N, E>(
175 props: DependencyGraphProps<N, E>,
176 ): PibblNode {
177 const frame = useGraphFrame(props.style);
178 const layout = layoutDependencies(resolveSignalValue(props.graph), {
179 ...props,
180 bounds: frame.bounds,
181 rankGap: frame.style.rankGap,
182 nodeGap: frame.style.nodeGap,
183 });
184 return (
185 <Group style={frame.groupStyle}>
186 <GraphView {...props} style={undefined} layout={layout} />
187 </Group>
188 );
189 }
190
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.