packages/core/src/features/viz/lib/graph/shared.tsx
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import {
2 Group,
3 Rectangle,
4 SvgPath,
5 Text,
6 resolveSignalValue,
7 resolveBox,
8 useLayoutBox,
9 } from "@pibbl/core";
10 import type {
11 GStyle,
12 SystemStyle,
13 PibblResponsiveStyle,
14 PibblNode,
15 } from "@pibbl/core";
16 import type {
17 Accessor,
18 Bounds,
19 Style,
20 MarkStyle,
21 GraphNodeGeometry,
22 GraphNodeProps,
23 GraphEdgeGeometry,
24 GraphEdgeProps,
25 GraphLabelProps,
26 GraphViewProps,
27 LabelGeometry,
28 NodeStyle,
29 EdgeStyle,
30 LabelStyle,
31 VizKey,
32 } from "./types.js";
33 const boundsKeys = ["x", "y", "width", "height"] as const;
34 const graphLayoutKeys = [
35 "rankGap",
36 "nodeGap",
37 "levelGap",
38 "siblingGap",
39 "cellGap",
40 "rowLabelWidth",
41 "columnLabelHeight",
42 "nodeWidth",
43 "columnGap",
44 "headerHeight",
45 "ringGap",
46 "bandWidth",
47 "padAngle",
48 "startAngle",
49 ] as const;
50
51 /** Read an application's typed property or accessor without normalizing away its record. */
52 export function readAccessor<D, V>(datum: D, accessor: Accessor<D, V>): V {
53 return typeof accessor === "function"
54 ? accessor(datum)
55 : (datum[accessor] as V);
56 }
57 /** Validate a finite rectangle in local logical units. */
58 export function validateBounds(bounds: Bounds): Bounds {
59 for (let keyIndex = 0; keyIndex < boundsKeys.length; keyIndex++) {
60 const key = boundsKeys[keyIndex];
61 if (
62 !Number.isFinite(bounds[key]) ||
63 ((key === "width" || key === "height") && bounds[key] < 0)
64 )
65 throw new RangeError(
66 `Graph bounds.${key} must be finite${key === "width" || key === "height" ? " and nonnegative" : ""}.`,
67 );
68 }
69 if (
70 !Number.isFinite(bounds.x + bounds.width) ||
71 !Number.isFinite(bounds.y + bounds.height)
72 )
73 throw new RangeError("Graph bounds overflow.");
74 return bounds;
75 }
76 export function validKey(key: VizKey): VizKey {
77 if (
78 (typeof key !== "string" && typeof key !== "number") ||
79 (typeof key === "number" && !Number.isFinite(key))
80 )
81 throw new TypeError("Graph keys must be strings or finite numbers.");
82 return key;
83 }
84 /** Resolve ordinary responsive frame style through public sizing and allocation. */
85 export function useGraphFrame<S extends GStyle>(
86 input?: Style<S>,
87 ): { bounds: Bounds; style: S; groupStyle: GStyle } {
88 const allocation = useLayoutBox();
89 const authored = (resolveSignalValue(input) ?? {}) as PibblResponsiveStyle<S>;
90 const merged = { ...authored } as Record<string, unknown>;
91 for (const rule of authored.when ?? []) {
92 const q = rule.query;
93 if (
94 (q.minWidth === undefined || allocation.width >= q.minWidth) &&
95 (q.maxWidth === undefined || allocation.width <= q.maxWidth) &&
96 (q.minHeight === undefined || allocation.height >= q.minHeight) &&
97 (q.maxHeight === undefined || allocation.height <= q.maxHeight)
98 )
99 Object.assign(merged, rule.style);
100 }
101 delete merged.when;
102 for (const key of Object.keys(merged))
103 merged[key] = resolveSignalValue(merged[key]);
104 if (merged.width === "auto" || merged.height === "auto")
105 throw new RangeError(
106 "Graph frames require definite width and height or a finite parent allocation.",
107 );
108 const style = merged as S;
109 const box = resolveBox(
110 {
111 ...style,
112 width: style.width ?? allocation.width,
113 height: style.height ?? allocation.height,
114 },
115 {
116 minWidth: 0,
117 minHeight: 0,
118 maxWidth: allocation.width,
119 maxHeight: allocation.height,
120 },
121 );
122 const bounds = validateBounds({
123 x: 0,
124 y: 0,
125 width: box.borderBox.width,
126 height: box.borderBox.height,
127 });
128 const groupStyle = { ...style, width: bounds.width, height: bounds.height };
129 for (let keyIndex = 0; keyIndex < graphLayoutKeys.length; keyIndex++) {
130 const key = graphLayoutKeys[keyIndex];
131 delete (groupStyle as unknown as Record<string, unknown>)[key];
132 }
133 return { bounds, style, groupStyle };
134 }
135 /** Resolve a per-item paint callback without hiding its signal reads. */
136 export function resolveMarkStyle<G, S extends SystemStyle>(
137 geometry: G,
138 input?: MarkStyle<G, S>,
139 ): PibblResponsiveStyle<S> | undefined {
140 return resolveSignalValue(
141 typeof input === "function" ? input(geometry) : input,
142 );
143 }
144 /** Build inspectable label regions and original-record node geometry. */
145 export function graphNodeGeometry<N>(
146 datum: N,
147 key: VizKey,
148 bounds: Bounds,
149 label = String(key),
150 detail?: string,
151 ): GraphNodeGeometry<N> {
152 return {
153 key,
154 datum,
155 bounds,
156 label: {
157 text: label,
158 bounds: {
159 x: bounds.x + 10,
160 y: bounds.y + 4,
161 width: Math.max(0, bounds.width - 20),
162 height: detail ? bounds.height / 2 : Math.max(0, bounds.height - 8),
163 },
164 rotationDegrees: 0,
165 },
166 detail:
167 detail === undefined
168 ? null
169 : {
170 text: detail,
171 bounds: {
172 x: bounds.x + 10,
173 y: bounds.y + bounds.height / 2,
174 width: Math.max(0, bounds.width - 20),
175 height: bounds.height / 2 - 4,
176 },
177 rotationDegrees: 0,
178 },
179 };
180 }
181 /**
182 * Return the built-in node paint as an ordinary reusable style.
183 * @param _node - The node being painted. See {@link GraphNodeGeometry}.
184 * @returns Default fill, stroke and corner radius. See {@link NodeStyle}.
185 */
186 export function defaultGraphNodeStyle<N>(
187 _node: GraphNodeGeometry<N>,
188 ): NodeStyle {
189 return {
190 fill: "#edf5f2",
191 stroke: "#8eb6aa",
192 strokeWidth: 1,
193 cornerRadius: 7,
194 };
195 }
196 /**
197 * Return the built-in edge paint as an ordinary reusable style.
198 * @param _edge - The edge being painted. See {@link GraphEdgeGeometry}.
199 * @returns Default stroke and logical stroke width. See {@link EdgeStyle}.
200 */
201 export function defaultGraphEdgeStyle<E>(
202 _edge: GraphEdgeGeometry<E>,
203 ): EdgeStyle {
204 return { stroke: "#91a9a3", strokeWidth: 1.5 };
205 }
206 /**
207 * Return the built-in label paint as an ordinary reusable style.
208 * @param _label - The label being painted. See {@link LabelGeometry}.
209 * @returns Default Canvas font, fill and middle baseline. See {@link LabelStyle}.
210 */
211 export function defaultGraphLabelStyle(_label: LabelGeometry): LabelStyle {
212 return { fill: "#203d39", font: "13px sans-serif", textBaseline: "middle" };
213 }
214 /**
215 * Draw a node box; children use node-local coordinates and ordinary Pibbl events.
216 * @param props - Box geometry, paint and event handlers. See {@link GraphNodeProps}.
217 * @returns A group containing the box and authored children. See {@link GraphNodeProps}.
218 */
219 export function GraphNode<N>({
220 node,
221 style,
222 children,
223 ...events
224 }: GraphNodeProps<N>): PibblNode {
225 const { x, y, width, height } = node.bounds;
226 const {
227 keyboardFocusable,
228 keyboardNavigationBounds,
229 pointerEvents,
230 ...handlers
231 } = events;
232 return (
233 <Group {...handlers} style={{ translateX: x, translateY: y }}>
234 <Rectangle
235 keyboardFocusable={
236 keyboardFocusable ??
237 Boolean(handlers.onClick || handlers.onKeyDown || handlers.onKeyUp)
238 }
239 keyboardNavigationBounds={keyboardNavigationBounds}
240 pointerEvents={pointerEvents}
241 style={{ ...resolveSignalValue(style), width, height }}
242 />
243 {children}
244 </Group>
245 );
246 }
247 /**
248 * Draw an edge path and optional arrow with ordinary path targeting.
249 * @param props - Edge geometry, paint and event handlers. See {@link GraphEdgeProps}.
250 * @returns Path content in diagram-local coordinates. See {@link GraphEdgeProps}.
251 */
252 export function GraphEdge<E>({
253 edge,
254 style,
255 ...events
256 }: GraphEdgeProps<E>): PibblNode {
257 const paint = resolveSignalValue(style);
258 const {
259 keyboardFocusable,
260 keyboardNavigationBounds,
261 pointerEvents,
262 ...handlers
263 } = events;
264 return (
265 <Group {...handlers}>
266 <SvgPath
267 keyboardFocusable={
268 keyboardFocusable ??
269 Boolean(handlers.onClick || handlers.onKeyDown || handlers.onKeyUp)
270 }
271 keyboardNavigationBounds={keyboardNavigationBounds}
272 pointerEvents={pointerEvents}
273 style={{ ...paint, d: edge.path }}
274 />
275 {edge.arrowPath && (
276 <SvgPath
277 pointerEvents={pointerEvents}
278 style={{
279 ...paint,
280 fill: paint?.stroke ?? "#91a9a3",
281 d: edge.arrowPath,
282 }}
283 />
284 )}
285 </Group>
286 );
287 }
288 /**
289 * Draw decorative label text at its supplied box and rotation.
290 * @param props - Text geometry and optional text paint. See {@link GraphLabelProps}.
291 * @returns A transformed decorative Text component. See {@link GraphLabelProps}.
292 */
293 export function GraphLabel({ label, style }: GraphLabelProps): PibblNode {
294 const { x, y, width, height } = label.bounds;
295 const paint = resolveSignalValue(style);
296 const align = resolveSignalValue(paint?.textAlign);
297 const anchor =
298 align === "center"
299 ? width / 2
300 : align === "right" || align === "end"
301 ? width
302 : 0;
303 return (
304 <Group
305 style={{
306 translateX: x + anchor,
307 translateY: y + height / 2,
308 rotationDegrees: label.rotationDegrees,
309 }}
310 >
311 <Text
312 pointerEvents="none"
313 style={{ textBaseline: "middle", fit: "ellipsis", ...paint, width }}
314 >
315 {label.text}
316 </Text>
317 </Group>
318 );
319 }
320 /**
321 * Render supplied graph geometry without layout, fitting, or simulation.
322 * @param props - A snapshot or signal, item overrides and events. See {@link GraphViewProps}.
323 * @returns An ordinary Pibbl composition preserving source paint order. See {@link GraphViewProps}.
324 */
325 export function GraphView<N, E>(props: GraphViewProps<N, E>): PibblNode {
326 const layout = resolveSignalValue(props.layout);
327 return (
328 <Group style={props.style}>
329 {layout.edges.map((edge) => (
330 <Group
331 key={`e:${typeof edge.key}:${edge.key}`}
332 onClick={(event) => props.onEdgeClick?.(edge, event)}
333 >
334 {props.renderEdge ? (
335 props.renderEdge(edge)
336 ) : (
337 <GraphEdge
338 edge={edge}
339 keyboardFocusable={Boolean(props.onEdgeClick)}
340 style={{
341 ...defaultGraphEdgeStyle(edge),
342 ...resolveMarkStyle(edge, props.edgeStyle),
343 }}
344 />
345 )}
346 </Group>
347 ))}
348 {layout.nodes.map((node) => (
349 <Group
350 key={`n:${typeof node.key}:${node.key}`}
351 onClick={(event) => props.onNodeClick?.(node, event)}
352 >
353 {props.renderNode ? (
354 props.renderNode(node)
355 ) : (
356 <Group>
357 <GraphNode
358 node={node}
359 keyboardFocusable={Boolean(props.onNodeClick)}
360 style={{
361 ...defaultGraphNodeStyle(node),
362 ...resolveMarkStyle(node, props.nodeStyle),
363 }}
364 />
365 <GraphLabel
366 label={node.label}
367 style={{
368 ...defaultGraphLabelStyle(node.label),
369 ...resolveMarkStyle(node, props.labelStyle),
370 }}
371 />
372 {node.detail && (
373 <GraphLabel
374 label={node.detail}
375 style={{
376 ...defaultGraphLabelStyle(node.detail),
377 font: "11px sans-serif",
378 ...resolveMarkStyle(node, props.labelStyle),
379 }}
380 />
381 )}
382 </Group>
383 )}
384 </Group>
385 ))}
386 </Group>
387 );
388 }
389
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.