Skip to content

packages/core/src/features/viz/lib/graph/treemap.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 type { NodeStyle } from "./types.js";
2 import {
3   Group,
4   Rectangle,
5   resolveSignalValue,
6   type PibblNode,
7 } from "@pibbl/core";
8 import {
9   defaultGraphLabelStyle,
10   GraphLabel,
11   resolveMarkStyle,
12   useGraphFrame,
13 } from "./shared.js";
14 import type {
15   Bounds,
16   PartitionCellGeometry,
17   PartitionLayout,
18   PartitionCellProps,
19   TreemapOptions,
20   TreemapProps,
21   TreemapStyle,
22 } from "./types.js";
23 import {
24   checkedBounds,
25   finiteGap,
26   hierarchy,
27   partitionLabel,
28   partitionLabelFits,
29   type HierarchyRecord,
30 } from "./hierarchy.js";
31 
32 /** Return the built-in depth-aware partition paint.
33  * @param cell - Partition cell geometry.
34  * @returns Ordinary rectangle style. @see {@link PartitionCellGeometry} */
35 export function defaultPartitionCellStyle<D>(
36   cell: PartitionCellGeometry<D>,
37 ): NodeStyle {
38   const shade = 82 - Math.min(cell.depth, 4) * 8;
39   return {
40     fill: `hsl(174 42% ${shade}%)`,
41     stroke: "#fbfaf6",
42     strokeWidth: 1,
43     cornerRadius: 3,
44   };
45 }
46 
47 function inset(box: Bounds, amount: number): Bounds {
48   return {
49     x: box.x + amount,
50     y: box.y + amount,
51     width: Math.max(0, box.width - amount * 2),
52     height: Math.max(0, box.height - amount * 2),
53   };
54 }
55 
56 interface WeightedRecord<D> {
57   readonly record: HierarchyRecord<D>;
58   readonly area: number;
59 }
60 
61 function worstAspect<D>(
62   row: readonly WeightedRecord<D>[],
63   length: number,
64 ): number {
65   if (row.length === 0 || length <= 0) return Infinity;
66   const sum = row.reduce((total, item) => total + item.area, 0);
67   if (sum === 0) return Infinity;
68   const min = Math.min(...row.map((item) => item.area));
69   const max = Math.max(...row.map((item) => item.area));
70   const side2 = length * length;
71   return Math.max((side2 * max) / (sum * sum), (sum * sum) / (side2 * min));
72 }
73 
74 /** Stable squarification: append records while doing so improves the current row’s worst aspect ratio. */
75 function squarify<D>(
76   records: readonly HierarchyRecord<D>[],
77   box: Bounds,
78 ): ReadonlyMap<HierarchyRecord<D>, Bounds> {
79   const total = records.reduce((sum, record) => sum + record.value, 0);
80   const weighted = records.map((record) => ({
81     record,
82     area:
83       box.width *
84       box.height *
85       (total === 0 ? 1 / records.length : record.value / total),
86   }));
87   const boxes = new Map<HierarchyRecord<D>, Bounds>();
88   let remaining = { ...box };
89   let index = 0;
90   while (
91     index < weighted.length &&
92     remaining.width > 0 &&
93     remaining.height > 0
94   ) {
95     const row: WeightedRecord<D>[] = [weighted[index++]];
96     const length = Math.min(remaining.width, remaining.height);
97     while (
98       index < weighted.length &&
99       worstAspect([...row, weighted[index]], length) <= worstAspect(row, length)
100     )
101       row.push(weighted[index++]);
102     const area = row.reduce((sum, item) => sum + item.area, 0);
103     if (remaining.width >= remaining.height) {
104       const rowWidth = area / remaining.height;
105       let y = remaining.y;
106       for (const item of row) {
107         const height = rowWidth === 0 ? 0 : item.area / rowWidth;
108         boxes.set(item.record, { x: remaining.x, y, width: rowWidth, height });
109         y += height;
110       }
111       remaining = {
112         x: remaining.x + rowWidth,
113         y: remaining.y,
114         width: Math.max(0, remaining.width - rowWidth),
115         height: remaining.height,
116       };
117     } else {
118       const rowHeight = area / remaining.width;
119       let x = remaining.x;
120       for (const item of row) {
121         const width = rowHeight === 0 ? 0 : item.area / rowHeight;
122         boxes.set(item.record, { x, y: remaining.y, width, height: rowHeight });
123         x += width;
124       }
125       remaining = {
126         x: remaining.x,
127         y: remaining.y + rowHeight,
128         width: remaining.width,
129         height: Math.max(0, remaining.height - rowHeight),
130       };
131     }
132   }
133   return boxes;
134 }
135 
136 /** Squarify weighted hierarchy leaves into stable, compact rectangles.
137  * @param root - Hierarchy root.
138  * @param options - Accessors, units, and finite bounds.
139  * @returns Immutable partition geometry. @see {@link PartitionLayout} */
140 export function layoutTreemap<D>(
141   root: D,
142   options: TreemapOptions<D>,
143 ): PartitionLayout<D> {
144   const bounds = checkedBounds(options.bounds, "layoutTreemap");
145   const gap = finiteGap(options.cellGap, 4, "layoutTreemap cellGap");
146   const padding = finiteGap(options.padding, 6, "layoutTreemap padding");
147   const headerHeight = finiteGap(
148     options.headerHeight,
149     26,
150     "layoutTreemap headerHeight",
151   );
152   const tree = hierarchy(root, options, "layoutTreemap", options.value);
153   const cells: PartitionCellGeometry<D>[] = [];
154   const add = (
155     record: HierarchyRecord<D>,
156     box: Bounds,
157     depth: number,
158     parentKey: PartitionCellGeometry<D>["parentKey"],
159     rootItem: boolean,
160   ) => {
161     const children = record.collapsed ? [] : record.children;
162     const boxLabel = partitionLabel(record, options, {
163       x: box.x + 12,
164       y: box.y + 8,
165       width: Math.max(0, box.width - 24),
166       height: Math.max(0, box.height - 16),
167     });
168     if (!rootItem || record.isLeaf)
169       cells.push(
170         Object.freeze({
171           key: record.key,
172           datum: record.datum,
173           parentKey,
174           depth,
175           value: record.value,
176           fraction: tree.value === 0 ? 0 : record.value / tree.value,
177           isLeaf: record.isLeaf,
178           collapsed: record.collapsed,
179           bounds: Object.freeze(box),
180           label: partitionLabelFits(boxLabel, box) ? boxLabel : null,
181         }),
182       );
183     if (children.length === 0) return;
184     const content = inset(
185       {
186         x: box.x,
187         y: box.y + headerHeight,
188         width: box.width,
189         height: Math.max(0, box.height - headerHeight),
190       },
191       padding,
192     );
193     const laidOut = squarify(children, content);
194     for (const child of children) {
195       const raw = laidOut.get(child)!;
196       const childBox = inset(raw, gap / 2);
197       add(
198         child,
199         childBox,
200         rootItem ? 0 : depth + 1,
201         rootItem ? null : record.key,
202         false,
203       );
204     }
205   };
206   add(tree, bounds, 0, null, true);
207   return Object.freeze({
208     bounds,
209     rootKey: tree.key,
210     total: tree.value,
211     unit: options.unit,
212     cells: Object.freeze(cells),
213   });
214 }
215 
216 /** Paint one partition cell at its immutable geometry.
217  * @param props - Cell geometry, paint, events, and optional global-coordinate children.
218  * @returns Canvas composition. @see {@link PartitionCellGeometry} */
219 export function TreemapCell<D>(props: PartitionCellProps<D>): PibblNode {
220   const { bounds } = props.cell;
221   const { children, style, ...events } = props;
222   return (
223     <Group>
224       <Rectangle
225         {...events}
226         style={{
227           ...resolveSignalValue(style),
228           left: bounds.x,
229           top: bounds.y,
230           width: bounds.width,
231           height: bounds.height,
232         }}
233       />
234       {children}
235     </Group>
236   );
237 }
238 
239 /** Render a squarified hierarchy with visible quantitative labels.
240  * @param props - Reactive hierarchy data and presentation.
241  * @returns Canvas composition. @see {@link layoutTreemap} */
242 export function Treemap<D>(props: TreemapProps<D>): PibblNode {
243   const frame = useGraphFrame<TreemapStyle>(props.style);
244   const root = resolveSignalValue(props.root);
245   if (frame.bounds.width === 0 || frame.bounds.height === 0)
246     return <Group style={frame.groupStyle}>{null}</Group>;
247   const layout = layoutTreemap(root, {
248     ...props,
249     bounds: frame.bounds,
250     cellGap: frame.style.cellGap,
251     padding: frame.style.padding,
252     headerHeight: frame.style.headerHeight,
253   });
254   const labelStyle = resolveSignalValue(props.labelStyle);
255   return (
256     <Group style={frame.groupStyle}>
257       {layout.cells.map((cell) =>
258         props.renderCell ? (
259           <Group
260             key={cell.key}
261             onClick={(event) => props.onCellClick?.(cell, event)}
262           >
263             {props.renderCell(cell)}
264           </Group>
265         ) : (
266           <TreemapCell
267             key={cell.key}
268             cell={cell}
269             style={{
270               ...defaultPartitionCellStyle(cell),
271               ...resolveMarkStyle(cell, props.cellStyle),
272             }}
273             onClick={(event) => props.onCellClick?.(cell, event)}
274           >
275             {cell.label && (
276               <GraphLabel
277                 label={cell.label}
278                 style={{ ...defaultGraphLabelStyle(cell.label), ...labelStyle }}
279               />
280             )}
281           </TreemapCell>
282         ),
283       )}
284     </Group>
285   );
286 }
287 

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