Skip to content

packages/core/src/features/viz/lib/graph/matrix.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, Rectangle, resolveSignalValue } from "@pibbl/core";
2 import type { PibblNode } from "@pibbl/core";
3 import type {
4   Accessor,
5   AdjacencyMatrixProps,
6   MatrixCellGeometry,
7   MatrixCellProps,
8   MatrixData,
9   MatrixLayout,
10   MatrixOptions,
11   NodeStyle,
12   VizKey,
13 } from "./types.js";
14 import {
15   defaultGraphLabelStyle,
16   GraphLabel,
17   resolveMarkStyle,
18   useGraphFrame,
19 } from "./shared.js";
20 
21 function value<D, V>(accessor: Accessor<D, V>, datum: D): V {
22   return typeof accessor === "function"
23     ? accessor(datum)
24     : (datum as Record<PropertyKey, V>)[accessor];
25 }
26 function finite(input: number, name: string, nonnegative = false): number {
27   if (!Number.isFinite(input) || (nonnegative && input < 0))
28     throw new RangeError(
29       `layoutMatrix: ${name} must be finite${nonnegative ? " and nonnegative" : ""}.`,
30     );
31   return input;
32 }
33 function bounds(
34   input: MatrixOptions<unknown, unknown, unknown>["bounds"],
35 ): void {
36   finite(input.x, "bounds.x");
37   finite(input.y, "bounds.y");
38   finite(input.width, "bounds.width", true);
39   finite(input.height, "bounds.height", true);
40 }
41 function label(
42   text: string,
43   x: number,
44   y: number,
45   width: number,
46   height: number,
47   rotationDegrees = 0,
48 ) {
49   return Object.freeze({
50     text,
51     bounds: Object.freeze({ x, y, width, height }),
52     rotationDegrees,
53   });
54 }
55 
56 /** Computes ordered cells for an explicit row/column relation matrix.
57  * @param data - Explicit rows, columns, and ordered relations. See {@link MatrixData}.
58  * @param options - Typed accessors, dimensions, labels, and unit. See {@link MatrixOptions}.
59  * @returns Immutable cell and label geometry. See {@link MatrixLayout}.
60  */
61 export function layoutMatrix<R, C, E>(
62   data: MatrixData<R, C, E>,
63   options: MatrixOptions<R, C, E>,
64 ): MatrixLayout<R, C, E> {
65   bounds(options.bounds as MatrixOptions<unknown, unknown, unknown>["bounds"]);
66   const gap = finite(options.cellGap ?? 2, "cellGap", true);
67   const rowLabelWidth = finite(
68     options.rowLabelWidth ?? 96,
69     "rowLabelWidth",
70     true,
71   );
72   const columnLabelHeight = finite(
73     options.columnLabelHeight ?? 54,
74     "columnLabelHeight",
75     true,
76   );
77   const rowKeys = new Map<VizKey, R>(),
78     columnKeys = new Map<VizKey, C>();
79   for (const row of data.rows) {
80     const key = value(options.rowKey, row);
81     if (rowKeys.has(key))
82       throw new Error(`layoutMatrix: duplicate row key ${String(key)}.`);
83     rowKeys.set(key, row);
84   }
85   for (const column of data.columns) {
86     const key = value(options.columnKey, column);
87     if (columnKeys.has(key))
88       throw new Error(`layoutMatrix: duplicate column key ${String(key)}.`);
89     columnKeys.set(key, column);
90   }
91   const width = Math.max(
92     0,
93     (options.bounds.width -
94       rowLabelWidth -
95       Math.max(0, data.columns.length - 1) * gap) /
96       Math.max(1, data.columns.length),
97   );
98   const height = Math.max(
99     0,
100     (options.bounds.height -
101       columnLabelHeight -
102       Math.max(0, data.rows.length - 1) * gap) /
103       Math.max(1, data.rows.length),
104   );
105   const grouped = new Map<string, E[]>();
106   for (const relation of data.relations) {
107     const source = value(options.source, relation),
108       target = value(options.target, relation);
109     if (!rowKeys.has(source))
110       throw new RangeError(
111         `layoutMatrix: source ${String(source)} is not a row key.`,
112       );
113     if (!columnKeys.has(target))
114       throw new RangeError(
115         `layoutMatrix: target ${String(target)} is not a column key.`,
116       );
117     const amount = value(options.value, relation);
118     finite(amount, "relation value");
119     const key = `${typeof source}:${String(source)}\u0000${typeof target}:${String(target)}`;
120     const records = grouped.get(key);
121     if (records) records.push(relation);
122     else grouped.set(key, [relation]);
123   }
124   const cells: MatrixCellGeometry<R, C, E>[] = [];
125   const rowLabels = data.rows.map((row, index) =>
126     label(
127       options.rowLabel
128         ? value(options.rowLabel, row)
129         : String(value(options.rowKey, row)),
130       options.bounds.x,
131       options.bounds.y + columnLabelHeight + index * (height + gap),
132       rowLabelWidth - gap,
133       height,
134     ),
135   );
136   const columnLabels = data.columns.map((column, index) =>
137     label(
138       options.columnLabel
139         ? value(options.columnLabel, column)
140         : String(value(options.columnKey, column)),
141       options.bounds.x + rowLabelWidth + index * (width + gap),
142       options.bounds.y,
143       width,
144       columnLabelHeight - gap,
145     ),
146   );
147   for (let r = 0; r < data.rows.length; r++)
148     for (let c = 0; c < data.columns.length; c++) {
149       const row = data.rows[r],
150         column = data.columns[c],
151         rowKey = value(options.rowKey, row),
152         columnKey = value(options.columnKey, column);
153       const records =
154         grouped.get(
155           `${typeof rowKey}:${String(rowKey)}\u0000${typeof columnKey}:${String(columnKey)}`,
156         ) ?? [];
157       const total = records.reduce(
158         (sum, record) => sum + value(options.value, record),
159         0,
160       );
161       finite(total, "cell aggregate");
162       const cellBounds = Object.freeze({
163         x: options.bounds.x + rowLabelWidth + c * (width + gap),
164         y: options.bounds.y + columnLabelHeight + r * (height + gap),
165         width,
166         height,
167       });
168       cells.push(
169         Object.freeze({
170           row,
171           column,
172           rowKey,
173           columnKey,
174           records: Object.freeze(records),
175           value: records.length ? total : null,
176           bounds: cellBounds,
177           label: records.length
178             ? label(
179                 options.formatValue
180                   ? options.formatValue(total)
181                   : `${total} ${options.unit}`,
182                 cellBounds.x,
183                 cellBounds.y,
184                 width,
185                 height,
186               )
187             : null,
188         }),
189       );
190     }
191   return Object.freeze({
192     bounds: Object.freeze({ ...options.bounds }),
193     unit: options.unit,
194     cells: Object.freeze(cells),
195     rowLabels: Object.freeze(rowLabels),
196     columnLabels: Object.freeze(columnLabels),
197   });
198 }
199 
200 /** Default cell paint for custom matrix compositions.
201  * @param cell - Cell geometry.
202  * @param range - Observed numeric extent.
203  * @returns Resolved cell paint.
204  * @see {@link MatrixCell}
205  */
206 export function defaultMatrixCellStyle<R, C, E>(
207   cell: MatrixCellGeometry<R, C, E>,
208   range: Readonly<{ minimum: number; maximum: number }>,
209 ): NodeStyle {
210   const value = cell.value ?? 0,
211     span = range.maximum - range.minimum;
212   const alpha =
213     cell.value === null
214       ? 0.05
215       : span <= 0
216         ? 0.8
217         : 0.16 +
218           0.74 * Math.max(0, Math.min(1, (value - range.minimum) / span));
219   return { fill: `rgba(15, 118, 110, ${alpha})`, cornerRadius: 2 };
220 }
221 
222 /** Draw one supplied matrix cell geometry.
223  * @param argument - Cell props.
224  * @returns Canvas node.
225  * @see {@link MatrixCellProps}
226  */
227 export function MatrixCell<R, C, E>({
228   cell,
229   style: input,
230   children,
231   ...events
232 }: MatrixCellProps<R, C, E>): PibblNode {
233   const style = resolveSignalValue(input) ?? {};
234   return (
235     <Group>
236       <Rectangle
237         {...events}
238         style={{
239           ...style,
240           left: cell.bounds.x,
241           top: cell.bounds.y,
242           width: cell.bounds.width,
243           height: cell.bounds.height,
244         }}
245       />
246       {children}
247     </Group>
248   );
249 }
250 
251 /** Render an ordered relation matrix with default marks and labels.
252  * @param props - Matrix data and presentation.
253  * @returns Canvas node.
254  * @see {@link layoutMatrix}
255  */
256 export function AdjacencyMatrix<R, C, E>(
257   props: AdjacencyMatrixProps<R, C, E>,
258 ): PibblNode {
259   const frame = useGraphFrame(props.style);
260   if (!frame.bounds.width || !frame.bounds.height)
261     return <Group style={frame.groupStyle}>{null}</Group>;
262   const data = resolveSignalValue(props.data);
263   const style = frame.style;
264   const layout = layoutMatrix(data, {
265     ...props,
266     bounds: frame.bounds,
267     cellGap: style.cellGap,
268     rowLabelWidth: style.rowLabelWidth,
269     columnLabelHeight: style.columnLabelHeight,
270   });
271   const values = layout.cells
272     .map((cell) => cell.value)
273     .filter((entry): entry is number => entry !== null);
274   const minimum = Math.min(...values, 0),
275     maximum = Math.max(...values, 1);
276   return (
277     <Group style={frame.groupStyle}>
278       {layout.cells.map((cell) => (
279         <Group
280           key={JSON.stringify([cell.rowKey, cell.columnKey])}
281           onClick={(event) => props.onCellClick?.(cell, event)}
282         >
283           {props.renderCell ? (
284             props.renderCell(cell)
285           ) : (
286             <Group>
287               <MatrixCell
288                 cell={cell}
289                 keyboardFocusable={Boolean(props.onCellClick)}
290                 style={{
291                   ...defaultMatrixCellStyle(cell, { minimum, maximum }),
292                   ...resolveMarkStyle(cell, props.cellStyle),
293                 }}
294               />
295               {cell.label && (
296                 <GraphLabel
297                   label={cell.label}
298                   style={{
299                     ...defaultGraphLabelStyle(cell.label),
300                     fill:
301                       cell.value !== null &&
302                       (cell.value - minimum) / (maximum - minimum || 1) >= 0.5
303                         ? "#ffffff"
304                         : "#123c34",
305                     textAlign: "center",
306                     ...resolveSignalValue(props.labelStyle),
307                   }}
308                 />
309               )}
310             </Group>
311           )}
312         </Group>
313       ))}
314       {layout.rowLabels.concat(layout.columnLabels).map((entry, index) => (
315         <GraphLabel
316           key={`axis-${index}`}
317           label={entry}
318           style={{
319             ...defaultGraphLabelStyle(entry),
320             ...resolveSignalValue(props.labelStyle),
321           }}
322         />
323       ))}
324     </Group>
325   );
326 }
327 

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