Skip to content

packages/core/src/features/viz/lib/graph/tree.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   GraphEdgeGeometry,
14   TidyTreeProps,
15   TreeEdge,
16   TreeLayout,
17   TreeNodeGeometry,
18   TreeOptions,
19   TreeStyle,
20 } from "./types.js";
21 import {
22   checkedBounds,
23   finiteGap,
24   finiteSize,
25   hierarchy,
26   hierarchyLabel,
27   type HierarchyRecord,
28 } from "./hierarchy.js";
29 
30 interface Positioned<D> {
31   record: HierarchyRecord<D>;
32   width: number;
33   x: number;
34 }
35 
36 /** Lay out a validated hierarchy with stable child order and variable node dimensions.
37  * @param root - Hierarchy root.
38  * @param options - Named hierarchy accessors and finite bounds.
39  * @returns Immutable node and edge geometry. @see {@link TreeLayout} */
40 export function layoutTree<D>(root: D, options: TreeOptions<D>): TreeLayout<D> {
41   const bounds = checkedBounds(options.bounds, "layoutTree");
42   const siblingGap = finiteGap(options.siblingGap, 24, "layoutTree siblingGap");
43   const levelGap = finiteGap(options.levelGap, 48, "layoutTree levelGap");
44   const tree = hierarchy(root, options, "layoutTree");
45   const visible = (record: HierarchyRecord<D>) =>
46     record.collapsed ? [] : record.children;
47   const sizes = new Map<
48     HierarchyRecord<D>,
49     { width: number; height: number }
50   >();
51   const spans = new Map<HierarchyRecord<D>, number>();
52   const depthHeights: number[] = [];
53   const measure = (record: HierarchyRecord<D>): number => {
54     const size = finiteSize(record.datum, options.nodeSize, "layoutTree");
55     sizes.set(record, size);
56     depthHeights[record.depth] = Math.max(
57       depthHeights[record.depth] ?? 0,
58       size.height,
59     );
60     const kids = visible(record);
61     const childSpan = kids.reduce(
62       (sum, child, index) => sum + measure(child) + (index ? siblingGap : 0),
63       0,
64     );
65     const span = Math.max(size.width, childSpan);
66     spans.set(record, span);
67     return span;
68   };
69   const totalWidth = measure(tree);
70   const totalHeight = depthHeights.reduce(
71     (sum, height, index) => sum + height + (index ? levelGap : 0),
72     0,
73   );
74   if (totalWidth > bounds.width || totalHeight > bounds.height)
75     throw new RangeError(
76       "layoutTree: bounds are too small for nodes and gaps.",
77     );
78   const yAt: number[] = [];
79   let y = bounds.y;
80   for (let depth = 0; depth < depthHeights.length; depth++) {
81     yAt.push(y);
82     y += depthHeights[depth] + levelGap;
83   }
84   const positions: Positioned<D>[] = [];
85   const place = (record: HierarchyRecord<D>, left: number) => {
86     const span = spans.get(record)!;
87     const size = sizes.get(record)!;
88     const x = left + (span - size.width) / 2;
89     positions.push({ record, width: size.width, x });
90     let childLeft = left;
91     for (const child of visible(record)) {
92       place(child, childLeft);
93       childLeft += spans.get(child)! + siblingGap;
94     }
95   };
96   place(tree, bounds.x + (bounds.width - totalWidth) / 2);
97   const nodes = positions.map(({ record, x }) => {
98     const size = sizes.get(record)!;
99     const box = Object.freeze({
100       x,
101       y: yAt[record.depth],
102       width: size.width,
103       height: size.height,
104     });
105     return Object.freeze({
106       key: record.key,
107       datum: record.datum,
108       bounds: box,
109       label: hierarchyLabel(
110         record.datum,
111         options.label,
112         {
113           x: x + 10,
114           y: box.y + 10,
115           width: size.width - 20,
116           height: 18,
117         },
118         String(record.key),
119       ),
120       detail:
121         options.detail === undefined
122           ? null
123           : hierarchyLabel(record.datum, options.detail, {
124               x: x + 10,
125               y: box.y + 31,
126               width: size.width - 20,
127               height: 16,
128             }),
129       depth: record.depth,
130       parentKey: record.parent?.key ?? null,
131       hiddenChildren: record.hiddenChildren,
132     } satisfies TreeNodeGeometry<D>);
133   });
134   const byKey = new Map(nodes.map((node) => [node.key, node]));
135   const edges: GraphEdgeGeometry<TreeEdge<D>>[] = [];
136   for (const node of nodes)
137     if (node.parentKey !== null) {
138       const parent = byKey.get(node.parentKey)!;
139       const sourceAnchor = {
140         x: parent.bounds.x + parent.bounds.width / 2,
141         y: parent.bounds.y + parent.bounds.height,
142       };
143       const targetAnchor = {
144         x: node.bounds.x + node.bounds.width / 2,
145         y: node.bounds.y,
146       };
147       const bend = (sourceAnchor.y + targetAnchor.y) / 2;
148       const segments = Object.freeze([
149         { type: "move" as const, ...sourceAnchor },
150         { type: "line" as const, x: sourceAnchor.x, y: bend },
151         { type: "line" as const, x: targetAnchor.x, y: bend },
152         { type: "line" as const, ...targetAnchor },
153       ]);
154       edges.push(
155         Object.freeze({
156           key: `${String(parent.key)}→${String(node.key)}`,
157           datum: { parent: parent.datum, child: node.datum },
158           sourceKey: parent.key,
159           targetKey: node.key,
160           route: Object.freeze({
161             sourceAnchor: Object.freeze(sourceAnchor),
162             targetAnchor: Object.freeze(targetAnchor),
163             segments,
164             arrowSegments: null,
165           }),
166           path: `M ${sourceAnchor.x} ${sourceAnchor.y} L ${sourceAnchor.x} ${bend} L ${targetAnchor.x} ${bend} L ${targetAnchor.x} ${targetAnchor.y}`,
167           arrowPath: null,
168         }),
169       );
170     }
171   return Object.freeze({
172     bounds,
173     nodes: Object.freeze(nodes),
174     edges: Object.freeze(edges),
175   });
176 }
177 
178 /** Render a tidy hierarchy from ordinary data using default marks or caller compositions.
179  * @param props - Reactive hierarchy data, presentation, and frame style.
180  * @returns Canvas composition. @see {@link layoutTree} */
181 export function TidyTree<D>(props: TidyTreeProps<D>): PibblNode {
182   const frame = useGraphFrame<TreeStyle>(props.style);
183   const root = resolveSignalValue(props.root);
184   if (frame.bounds.width === 0 || frame.bounds.height === 0)
185     return <Group style={frame.groupStyle}>{null}</Group>;
186   const layout = layoutTree(root, {
187     ...props,
188     bounds: frame.bounds,
189     levelGap: frame.style.levelGap,
190     siblingGap: frame.style.siblingGap,
191   });
192   return (
193     <Group style={frame.groupStyle}>
194       {layout.edges.map((edge) =>
195         props.renderEdge ? (
196           <Group
197             key={edge.key}
198             onClick={(event) => props.onEdgeClick?.(edge, event)}
199           >
200             {props.renderEdge(edge)}
201           </Group>
202         ) : (
203           <GraphEdge
204             key={edge.key}
205             edge={edge}
206             style={{
207               ...defaultGraphEdgeStyle(edge),
208               ...resolveMarkStyle(edge, props.edgeStyle),
209             }}
210             onClick={(event) => props.onEdgeClick?.(edge, event)}
211           />
212         ),
213       )}
214       {layout.nodes.map((node) =>
215         props.renderNode ? (
216           <Group
217             key={node.key}
218             onClick={(event) => props.onNodeClick?.(node, event)}
219           >
220             {props.renderNode(node)}
221           </Group>
222         ) : (
223           <Group key={node.key}>
224             <GraphNode
225               node={node}
226               style={{
227                 ...defaultGraphNodeStyle(node),
228                 ...resolveMarkStyle(node, props.nodeStyle),
229               }}
230               onClick={(event) => props.onNodeClick?.(node, event)}
231             />
232             <GraphLabel
233               label={node.label}
234               style={{
235                 ...defaultGraphLabelStyle(node.label),
236                 ...resolveMarkStyle(node, props.labelStyle),
237               }}
238             />
239             {node.detail && (
240               <GraphLabel
241                 label={node.detail}
242                 style={{
243                   ...defaultGraphLabelStyle(node.detail),
244                   font: "11px sans-serif",
245                   ...resolveMarkStyle(node, props.labelStyle),
246                 }}
247               />
248             )}
249           </Group>
250         ),
251       )}
252     </Group>
253   );
254 }
255 

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