@vitavision/workbench 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitavision/workbench",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "Studio-app building blocks on @vitavision/ui: app shell, split panes, tree view, playback bar and playhead store, file drop (toasts re-exported from @vitavision/ui).",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "repository": {
@@ -46,7 +46,7 @@
46
46
  "react-dom": "^19.2.0"
47
47
  },
48
48
  "dependencies": {
49
- "@vitavision/ui": "^0.14.0",
49
+ "@vitavision/ui": "^0.14.2",
50
50
  "lucide-react": "^1.48.0"
51
51
  },
52
52
  "devDependencies": {
@@ -0,0 +1,493 @@
1
+ /*
2
+ * A two-dimensional grid of captures: views down, cameras across, one cell each.
3
+ *
4
+ * Built for the overview of a calibration dataset, where ten cameras by several hundred views
5
+ * must stay light and a person must be able to walk it cell by cell. A `Table` windows rows and
6
+ * moves focus by row; this windows both axes and moves focus by cell. The caller draws each cell
7
+ * (a thumbnail, a count, a state); the matrix owns the geometry, the sticky headers, the
8
+ * keyboard, the selection and the grid roles.
9
+ *
10
+ * Only the cells in view, plus a margin and the focused cell, are in the DOM. Every handler is
11
+ * on the scroller and finds its cell from the event's target, so there is no listener per cell.
12
+ */
13
+
14
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
15
+ import type { CSSProperties, KeyboardEvent, MouseEvent, ReactNode } from "react";
16
+
17
+ import { cn, focusRingInset } from "@vitavision/ui";
18
+
19
+ import { inRect, moveFocus, rectBetween, revealScroll, windowRange, type GridPos } from "./matrixModel";
20
+
21
+ /** One row of a `SequenceMatrix`: a view, a frame. */
22
+ export interface SequenceMatrixRow {
23
+ /** Its identity, unique among the rows. */
24
+ id: string;
25
+ /** What the row header shows. */
26
+ label: ReactNode;
27
+ /** The row's name for assistive technology, when `label` is not text. Defaults to `label` as text, else `id`. */
28
+ name?: string | undefined;
29
+ }
30
+
31
+ /** One column of a `SequenceMatrix`: a camera, a channel. */
32
+ export interface SequenceMatrixColumn {
33
+ /** Its identity, unique among the columns. */
34
+ id: string;
35
+ /** What the column header shows. */
36
+ label: ReactNode;
37
+ /** The column's name for assistive technology, when `label` is not text. Defaults to `label` as text, else `id`. */
38
+ name?: string | undefined;
39
+ }
40
+
41
+ /**
42
+ * A selection: the cell `row` / `col`, or the rectangle from it to `rowTo` / `colTo`.
43
+ *
44
+ * `row` and `col` are the anchor (where the selection started); a range extends from there, in
45
+ * either direction. A whole row is `{ row, col: firstColumn, colTo: lastColumn }`.
46
+ */
47
+ export interface SequenceMatrixSelection {
48
+ /** The anchor's row id. */
49
+ row: string;
50
+ /** The anchor's column id. */
51
+ col: string;
52
+ /** The row id the range extends to. Omitted: the anchor's row. */
53
+ rowTo?: string | undefined;
54
+ /** The column id the range extends to. Omitted: the anchor's column. */
55
+ colTo?: string | undefined;
56
+ }
57
+
58
+ /** What `renderCell` is told about the cell it draws. */
59
+ export interface SequenceMatrixCellState {
60
+ /** The cell has the keyboard focus. */
61
+ focused: boolean;
62
+ /** The cell is in the selection. */
63
+ selected: boolean;
64
+ }
65
+
66
+ /** Props of `SequenceMatrix`. */
67
+ export interface SequenceMatrixProps {
68
+ /** The rows, top to bottom. */
69
+ rows: readonly SequenceMatrixRow[];
70
+ /** The columns, left to right. */
71
+ columns: readonly SequenceMatrixColumn[];
72
+ /**
73
+ * Draws a cell's content. It fills the cell's box (`colWidth` by `rowHeight`) and is called for
74
+ * the cells in view only, so it may be as rich as a thumbnail. The cell is a `gridcell`; give
75
+ * it an accessible name with `cellLabel` when its content is not text.
76
+ */
77
+ renderCell: (row: SequenceMatrixRow, column: SequenceMatrixColumn, state: SequenceMatrixCellState) => ReactNode;
78
+ /** The cell's accessible name (`aria-label`), e.g. `"view 12, camera 3, 48 corners"`. Omitted: the cell's content names it. */
79
+ cellLabel?: ((row: SequenceMatrixRow, column: SequenceMatrixColumn) => string | undefined) | undefined;
80
+ /** Draws a row header's content. Defaults to `row.label`. Interactive content here is the caller's to make focusable. */
81
+ renderRowHeader?: ((row: SequenceMatrixRow) => ReactNode) | undefined;
82
+ /** Draws a column header's content. Defaults to `column.label`. */
83
+ renderColumnHeader?: ((column: SequenceMatrixColumn) => ReactNode) | undefined;
84
+ /** The corner's text. Defaults to nothing visible; the corner is named "Rows". */
85
+ corner?: ReactNode;
86
+ /** A row's height in CSS pixels. Defaults to 36. */
87
+ rowHeight?: number | undefined;
88
+ /** Every column's width in CSS pixels. Defaults to 72. */
89
+ colWidth?: number | undefined;
90
+ /** The column headers' height. Defaults to 32. */
91
+ headerHeight?: number | undefined;
92
+ /** The row headers' width. Defaults to 96. */
93
+ rowHeaderWidth?: number | undefined;
94
+ /** Rows and columns rendered beyond the viewport on each side. Defaults to 3. */
95
+ overscan?: number | undefined;
96
+ /** Render only the cells in view. Defaults to true; off, every cell is rendered (a small matrix). */
97
+ windowed?: boolean | undefined;
98
+ /** The selection, controlled: `null` for none. Pair with `onValueChange`. */
99
+ value?: SequenceMatrixSelection | null | undefined;
100
+ /** The initial selection, when uncontrolled. */
101
+ defaultValue?: SequenceMatrixSelection | null | undefined;
102
+ /** Called with the new selection on a click, Space, Enter, or Shift + a move, and on a header click. */
103
+ onValueChange?: ((value: SequenceMatrixSelection) => void) | undefined;
104
+ /** Select the cell the arrow keys land on, as well as focus it. Defaults to false: arrows move, Space or Enter selects. */
105
+ selectionFollowsFocus?: boolean | undefined;
106
+ /** Allow a range (Shift + click or move, header click, Ctrl + A). Defaults to true; off, selection is one cell. */
107
+ multiple?: boolean | undefined;
108
+ /** Called with the cell's row and column ids on Enter and on a double click. */
109
+ onCellAction?: ((row: string, column: string) => void) | undefined;
110
+ /** Names the grid. */
111
+ "aria-label": string;
112
+ /** Merged onto the scroller with `cn`. Give the matrix a height (and a width): it scrolls inside its box. */
113
+ className?: string | undefined;
114
+ /** Inline style of the scroller, after the matrix's own: its size when a class is not at hand. */
115
+ style?: CSSProperties | undefined;
116
+ }
117
+
118
+ const DEFAULTS = { rowHeight: 36, colWidth: 72, headerHeight: 32, rowHeaderWidth: 96, overscan: 3 } as const;
119
+ /** The room assumed before the scroller is measured, and on the server. */
120
+ const INITIAL_VIEWPORT = { width: 640, height: 400 } as const;
121
+
122
+ interface Win {
123
+ rows: [number, number];
124
+ cols: [number, number];
125
+ }
126
+
127
+ const sameWin = (a: Win, b: Win) =>
128
+ a.rows[0] === b.rows[0] && a.rows[1] === b.rows[1] && a.cols[0] === b.cols[0] && a.cols[1] === b.cols[1];
129
+
130
+ const nameOf = (item: { id: string; label: ReactNode; name?: string | undefined }) =>
131
+ item.name ?? (typeof item.label === "string" || typeof item.label === "number" ? String(item.label) : item.id);
132
+
133
+ /** The grid cell, row header or column header an event came from, with its position. */
134
+ function locate(target: EventTarget | null): { kind: "cell" | "row" | "col"; row: number; col: number; element: HTMLElement } | null {
135
+ const element = (target as Element | null)?.closest?.<HTMLElement>("[data-cell],[data-row-header],[data-col-header]");
136
+ if (!element) return null;
137
+ const row = Number(element.dataset["r"] ?? -1);
138
+ const col = Number(element.dataset["c"] ?? -1);
139
+ if (element.hasAttribute("data-cell")) return { kind: "cell", row, col, element };
140
+ return element.hasAttribute("data-row-header") ? { kind: "row", row, col, element } : { kind: "col", row, col, element };
141
+ }
142
+
143
+ /**
144
+ * A windowed rows-by-columns grid with sticky headers and cell-level keyboard focus.
145
+ *
146
+ * - **Windowed in both axes**: only the cells in view (plus `overscan`, plus the focused cell) are
147
+ * in the DOM, so ten columns by several hundred rows are a few dozen elements. Row height and
148
+ * column width are uniform.
149
+ * - **Keyboard**: the grid is one Tab stop (roving `tabindex` on the focused cell). Arrows move by
150
+ * cell, Home/End to the ends of the row, Ctrl + Home/End to the corners, PageUp/PageDown by a
151
+ * screenful of rows. Space or Enter selects the focused cell and Enter also calls `onCellAction`;
152
+ * Shift + a move or Shift + click extends the selection to a rectangle; Shift + Space selects
153
+ * the focused row, Ctrl + Space its column, Ctrl + A everything.
154
+ * - **Selection**: one cell or a rectangle, controlled (`value`) or not. A click on a row or
155
+ * column header selects that whole row or column.
156
+ * - **Roles**: `grid` with `aria-rowcount` and `aria-colcount` (counting the headers), `row`s with
157
+ * `aria-rowindex`, `columnheader`, `rowheader` and `gridcell`s with `aria-colindex` and
158
+ * `aria-selected`; the whole rectangle is `aria-multiselectable`. Cells carry `data-selected`
159
+ * and `data-focused`.
160
+ * - **No listeners per cell**: clicks, keys and focus are handled once, on the scroller.
161
+ *
162
+ * Server rendering draws the first screenful of an assumed 640 by 400 px, without measuring.
163
+ */
164
+ export function SequenceMatrix({
165
+ rows,
166
+ columns,
167
+ renderCell,
168
+ cellLabel,
169
+ renderRowHeader,
170
+ renderColumnHeader,
171
+ corner,
172
+ rowHeight = DEFAULTS.rowHeight,
173
+ colWidth = DEFAULTS.colWidth,
174
+ headerHeight = DEFAULTS.headerHeight,
175
+ rowHeaderWidth = DEFAULTS.rowHeaderWidth,
176
+ overscan = DEFAULTS.overscan,
177
+ windowed = true,
178
+ value: controlled,
179
+ defaultValue = null,
180
+ onValueChange,
181
+ selectionFollowsFocus = false,
182
+ multiple = true,
183
+ onCellAction,
184
+ "aria-label": ariaLabel,
185
+ className,
186
+ style,
187
+ }: SequenceMatrixProps) {
188
+ const scrollerRef = useRef<HTMLDivElement>(null);
189
+ const [inner, setInner] = useState<SequenceMatrixSelection | null>(defaultValue);
190
+ const value = controlled === undefined ? inner : controlled;
191
+ const [focus, setFocus] = useState<GridPos | null>(null);
192
+ const [hasFocus, setHasFocus] = useState(false);
193
+ const focusPending = useRef(false);
194
+
195
+ const rowIndex = useMemo(() => new Map(rows.map((row, i) => [row.id, i])), [rows]);
196
+ const colIndex = useMemo(() => new Map(columns.map((column, i) => [column.id, i])), [columns]);
197
+ const nRows = rows.length;
198
+ const nCols = columns.length;
199
+
200
+ const initialWin = (): Win =>
201
+ windowed
202
+ ? {
203
+ rows: windowRange(0, INITIAL_VIEWPORT.height - headerHeight, rowHeight, nRows, overscan),
204
+ cols: windowRange(0, INITIAL_VIEWPORT.width - rowHeaderWidth, colWidth, nCols, overscan),
205
+ }
206
+ : { rows: [0, nRows], cols: [0, nCols] };
207
+ const [win, setWin] = useState<Win>(initialWin);
208
+
209
+ const measure = useCallback(() => {
210
+ const el = scrollerRef.current;
211
+ if (!el) return;
212
+ const next: Win = windowed
213
+ ? {
214
+ rows: windowRange(el.scrollTop, el.clientHeight - headerHeight, rowHeight, nRows, overscan),
215
+ cols: windowRange(el.scrollLeft, el.clientWidth - rowHeaderWidth, colWidth, nCols, overscan),
216
+ }
217
+ : { rows: [0, nRows], cols: [0, nCols] };
218
+ setWin((prev) => (sameWin(prev, next) ? prev : next));
219
+ }, [windowed, headerHeight, rowHeight, nRows, overscan, rowHeaderWidth, colWidth, nCols]);
220
+
221
+ // The window follows the geometry and the data; the scroller's size is observed.
222
+ useLayoutEffect(() => {
223
+ measure();
224
+ }, [measure]);
225
+ useEffect(() => {
226
+ const el = scrollerRef.current;
227
+ if (!el || typeof ResizeObserver === "undefined") return;
228
+ const observer = new ResizeObserver(() => measure());
229
+ observer.observe(el);
230
+ return () => observer.disconnect();
231
+ }, [measure]);
232
+
233
+ const range = useMemo(() => {
234
+ if (!value) return null;
235
+ const a = { row: rowIndex.get(value.row), col: colIndex.get(value.col) };
236
+ const b = { row: rowIndex.get(value.rowTo ?? value.row), col: colIndex.get(value.colTo ?? value.col) };
237
+ if (a.row === undefined || a.col === undefined || b.row === undefined || b.col === undefined) return null;
238
+ return rectBetween({ row: a.row, col: a.col }, { row: b.row, col: b.col });
239
+ }, [value, rowIndex, colIndex]);
240
+
241
+ const anchor: GridPos | null = useMemo(() => {
242
+ if (!value) return null;
243
+ const row = rowIndex.get(value.row);
244
+ const col = colIndex.get(value.col);
245
+ return row === undefined || col === undefined ? null : { row, col };
246
+ }, [value, rowIndex, colIndex]);
247
+
248
+ // The one cell in the tab order: the focused one, else the selection's anchor, else the first.
249
+ const clampPos = (pos: GridPos): GridPos => ({
250
+ row: Math.min(Math.max(0, pos.row), Math.max(0, nRows - 1)),
251
+ col: Math.min(Math.max(0, pos.col), Math.max(0, nCols - 1)),
252
+ });
253
+ const tabStop = clampPos(focus ?? anchor ?? { row: 0, col: 0 });
254
+
255
+ const commit = (next: SequenceMatrixSelection) => {
256
+ if (controlled === undefined) setInner(next);
257
+ onValueChange?.(next);
258
+ };
259
+ const selectRange = (from: GridPos, to: GridPos) => {
260
+ const a = rows[from.row];
261
+ const b = rows[to.row];
262
+ const c = columns[from.col];
263
+ const d = columns[to.col];
264
+ if (!a || !b || !c || !d) return;
265
+ const one = from.row === to.row && from.col === to.col;
266
+ commit(one || !multiple ? { row: b.id, col: d.id } : { row: a.id, col: c.id, rowTo: b.id, colTo: d.id });
267
+ };
268
+
269
+ const bodyViewport = () => {
270
+ const el = scrollerRef.current;
271
+ return {
272
+ height: (el?.clientHeight ?? INITIAL_VIEWPORT.height) - headerHeight,
273
+ width: (el?.clientWidth ?? INITIAL_VIEWPORT.width) - rowHeaderWidth,
274
+ };
275
+ };
276
+
277
+ /** Moves the cursor to `pos`: scrolls it into view and gives it the DOM focus once rendered. */
278
+ const moveTo = (pos: GridPos) => {
279
+ const el = scrollerRef.current;
280
+ if (el) {
281
+ const viewport = bodyViewport();
282
+ el.scrollTop = revealScroll(el.scrollTop, viewport.height, pos.row, rowHeight);
283
+ el.scrollLeft = revealScroll(el.scrollLeft, viewport.width, pos.col, colWidth);
284
+ }
285
+ focusPending.current = true;
286
+ setFocus(pos);
287
+ };
288
+
289
+ useEffect(() => {
290
+ if (!focusPending.current) return;
291
+ const el = scrollerRef.current?.querySelector<HTMLElement>(`[data-cell][data-r="${tabStop.row}"][data-c="${tabStop.col}"]`);
292
+ if (!el) return;
293
+ focusPending.current = false;
294
+ el.focus({ preventScroll: true });
295
+ });
296
+
297
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
298
+ const hit = locate(event.target);
299
+ // Keys typed into something inside a cell (an input, a menu) are not the grid's.
300
+ if (!hit || hit.kind !== "cell" || hit.element !== event.target || nRows === 0 || nCols === 0) return;
301
+ const here = { row: hit.row, col: hit.col };
302
+ const ctrl = event.ctrlKey || event.metaKey;
303
+ if (event.altKey) return;
304
+
305
+ if (event.key === " ") {
306
+ event.preventDefault();
307
+ if (event.shiftKey && multiple) selectRange({ row: here.row, col: 0 }, { row: here.row, col: nCols - 1 });
308
+ else if (ctrl && multiple) selectRange({ row: 0, col: here.col }, { row: nRows - 1, col: here.col });
309
+ else selectRange(here, here);
310
+ return;
311
+ }
312
+ if (event.key === "Enter") {
313
+ event.preventDefault();
314
+ selectRange(here, here);
315
+ onCellAction?.(rows[here.row]!.id, columns[here.col]!.id);
316
+ return;
317
+ }
318
+ if (ctrl && event.key.toLowerCase() === "a") {
319
+ if (!multiple) return;
320
+ event.preventDefault();
321
+ selectRange({ row: 0, col: 0 }, { row: nRows - 1, col: nCols - 1 });
322
+ return;
323
+ }
324
+ const page = Math.max(1, Math.floor(bodyViewport().height / rowHeight) - 1);
325
+ const next = moveFocus(here, event.key, { rows: nRows, cols: nCols }, page, ctrl);
326
+ if (next === null) return;
327
+ event.preventDefault();
328
+ moveTo(next);
329
+ if (event.shiftKey && multiple) selectRange(anchor ?? here, next);
330
+ else if (selectionFollowsFocus) selectRange(next, next);
331
+ };
332
+
333
+ const onClick = (event: MouseEvent<HTMLDivElement>) => {
334
+ const hit = locate(event.target);
335
+ if (!hit) return;
336
+ // A button or menu the caller put in a header is its own: it does not also select the row.
337
+ if (hit.kind !== "cell" && (event.target as Element).closest("button,a,input,select,textarea,[role=menu]")) return;
338
+ if (hit.kind === "cell") {
339
+ setFocus({ row: hit.row, col: hit.col });
340
+ const here = { row: hit.row, col: hit.col };
341
+ if (event.shiftKey && multiple && anchor) selectRange(anchor, here);
342
+ else selectRange(here, here);
343
+ } else if (multiple && hit.kind === "row") selectRange({ row: hit.row, col: 0 }, { row: hit.row, col: nCols - 1 });
344
+ else if (multiple && hit.kind === "col") selectRange({ row: 0, col: hit.col }, { row: nRows - 1, col: hit.col });
345
+ };
346
+
347
+ const onDoubleClick = (event: MouseEvent<HTMLDivElement>) => {
348
+ const hit = locate(event.target);
349
+ if (hit?.kind === "cell") onCellAction?.(rows[hit.row]!.id, columns[hit.col]!.id);
350
+ };
351
+
352
+ // Rows and columns to render: the window, and the focused ones wherever they are, so the tab stop never unmounts.
353
+ const withFocus = (window: [number, number], at: number, count: number): number[] => {
354
+ const out: number[] = [];
355
+ let placed = at < 0 || at >= count || (at >= window[0] && at < window[1]);
356
+ for (let i = window[0]; i < window[1]; i++) {
357
+ if (!placed && at < i) {
358
+ out.push(at);
359
+ placed = true;
360
+ }
361
+ out.push(i);
362
+ }
363
+ if (!placed) out.push(at);
364
+ return out;
365
+ };
366
+ const rowsShown = withFocus(win.rows, tabStop.row, nRows);
367
+ const colsShown = withFocus(win.cols, tabStop.col, nCols);
368
+
369
+ const totalWidth = rowHeaderWidth + nCols * colWidth;
370
+ const totalHeight = headerHeight + nRows * rowHeight;
371
+ const fullRow = (i: number) => range !== null && range.row0 <= i && i <= range.row1 && range.col0 === 0 && range.col1 === nCols - 1;
372
+ const fullCol = (j: number) => range !== null && range.col0 <= j && j <= range.col1 && range.row0 === 0 && range.row1 === nRows - 1;
373
+
374
+ return (
375
+ <div
376
+ ref={scrollerRef}
377
+ role="grid"
378
+ aria-label={ariaLabel}
379
+ aria-rowcount={nRows + 1}
380
+ aria-colcount={nCols + 1}
381
+ aria-multiselectable={multiple ? true : undefined}
382
+ // With no cell to focus, the scroller itself is the keyboard stop.
383
+ tabIndex={nRows === 0 || nCols === 0 ? 0 : undefined}
384
+ onScroll={measure}
385
+ onKeyDown={onKeyDown}
386
+ onClick={onClick}
387
+ onDoubleClick={onDoubleClick}
388
+ onFocus={(event) => {
389
+ setHasFocus(true);
390
+ const hit = locate(event.target);
391
+ if (hit?.kind === "cell") setFocus({ row: hit.row, col: hit.col });
392
+ }}
393
+ onBlur={(event) => {
394
+ if (!event.currentTarget.contains(event.relatedTarget)) setHasFocus(false);
395
+ }}
396
+ // Native focus scrolling keeps a cell clear of the sticky headers.
397
+ style={{ position: "relative", overflow: "auto", scrollPaddingTop: headerHeight, scrollPaddingLeft: rowHeaderWidth, ...style }}
398
+ className={cn("rounded-control border border-line bg-surface text-fg select-none", className)}
399
+ >
400
+ <div style={{ position: "relative", width: totalWidth, height: totalHeight }}>
401
+ <div role="row" aria-rowindex={1} style={{ position: "sticky", top: 0, zIndex: 20, height: headerHeight, width: totalWidth }}>
402
+ <div
403
+ role="columnheader"
404
+ aria-colindex={1}
405
+ className="flex items-center border-r border-b border-line bg-raised px-2 text-xs text-fg-muted"
406
+ style={{ position: "sticky", left: 0, zIndex: 30, width: rowHeaderWidth, height: headerHeight }}
407
+ >
408
+ {corner ?? <span className="sr-only">Rows</span>}
409
+ </div>
410
+ {colsShown.map((j) => {
411
+ const column = columns[j]!;
412
+ return (
413
+ <div
414
+ key={column.id}
415
+ role="columnheader"
416
+ aria-colindex={j + 2}
417
+ aria-label={nameOf(column)}
418
+ aria-selected={fullCol(j) ? true : undefined}
419
+ data-col-header=""
420
+ data-c={j}
421
+ data-selected={fullCol(j) ? "" : undefined}
422
+ className={cn(
423
+ "flex items-center justify-center overflow-hidden border-r border-b border-line px-1 text-xs",
424
+ fullCol(j) ? "bg-signal/12 text-fg" : "bg-raised text-fg-muted",
425
+ )}
426
+ style={{ position: "absolute", top: 0, left: rowHeaderWidth + j * colWidth, width: colWidth, height: headerHeight }}
427
+ >
428
+ {renderColumnHeader ? renderColumnHeader(column) : column.label}
429
+ </div>
430
+ );
431
+ })}
432
+ </div>
433
+ {rowsShown.map((i) => {
434
+ const row = rows[i]!;
435
+ return (
436
+ <div
437
+ key={row.id}
438
+ role="row"
439
+ aria-rowindex={i + 2}
440
+ style={{ position: "absolute", top: headerHeight + i * rowHeight, left: 0, height: rowHeight, width: totalWidth }}
441
+ >
442
+ <div
443
+ role="rowheader"
444
+ aria-colindex={1}
445
+ aria-label={nameOf(row)}
446
+ aria-selected={fullRow(i) ? true : undefined}
447
+ data-row-header=""
448
+ data-r={i}
449
+ data-selected={fullRow(i) ? "" : undefined}
450
+ className={cn(
451
+ "flex items-center overflow-hidden border-r border-b border-line px-2 text-xs",
452
+ fullRow(i) ? "bg-signal/12 text-fg" : "bg-raised text-fg-muted",
453
+ )}
454
+ style={{ position: "sticky", left: 0, zIndex: 10, width: rowHeaderWidth, height: rowHeight }}
455
+ >
456
+ {renderRowHeader ? renderRowHeader(row) : row.label}
457
+ </div>
458
+ {colsShown.map((j) => {
459
+ const column = columns[j]!;
460
+ const selected = inRect(range, i, j);
461
+ const isStop = i === tabStop.row && j === tabStop.col;
462
+ const focused = hasFocus && isStop;
463
+ return (
464
+ <div
465
+ key={column.id}
466
+ role="gridcell"
467
+ aria-colindex={j + 2}
468
+ aria-selected={selected}
469
+ aria-label={cellLabel?.(row, column)}
470
+ tabIndex={isStop ? 0 : -1}
471
+ data-cell=""
472
+ data-r={i}
473
+ data-c={j}
474
+ data-selected={selected ? "" : undefined}
475
+ data-focused={focused ? "" : undefined}
476
+ className={cn(
477
+ "overflow-hidden border-r border-b border-line",
478
+ selected ? "bg-signal/12" : "hover:bg-raised",
479
+ focusRingInset,
480
+ )}
481
+ style={{ position: "absolute", top: 0, left: rowHeaderWidth + j * colWidth, width: colWidth, height: rowHeight }}
482
+ >
483
+ {renderCell(row, column, { focused, selected })}
484
+ </div>
485
+ );
486
+ })}
487
+ </div>
488
+ );
489
+ })}
490
+ </div>
491
+ </div>
492
+ );
493
+ }
@@ -0,0 +1,126 @@
1
+ /*
2
+ * The arithmetic of `SequenceMatrix`, apart from the DOM: where the cursor goes on a key, which
3
+ * rows and columns a scroll position shows, how far to scroll to reveal a cell, and the rectangle
4
+ * of a selection. Pure, so the edges (an empty grid, a page past the end) are tested without a browser.
5
+ */
6
+
7
+ /** A cell by position: zero-based row and column indices. */
8
+ export interface GridPos {
9
+ /** The row index. */
10
+ row: number;
11
+ /** The column index. */
12
+ col: number;
13
+ }
14
+
15
+ /** The grid's size in cells. */
16
+ export interface GridSize {
17
+ /** The number of rows. */
18
+ rows: number;
19
+ /** The number of columns. */
20
+ cols: number;
21
+ }
22
+
23
+ /** A rectangle of cells, both ends inclusive. */
24
+ export interface GridRect {
25
+ /** The first row. */
26
+ row0: number;
27
+ /** The last row. */
28
+ row1: number;
29
+ /** The first column. */
30
+ col0: number;
31
+ /** The last column. */
32
+ col1: number;
33
+ }
34
+
35
+ const clamp = (value: number, low: number, high: number) => Math.min(high, Math.max(low, value));
36
+
37
+ /**
38
+ * Where a navigation key takes the cursor.
39
+ *
40
+ * - Arrows move one cell and stop at the edge.
41
+ * - `Home` and `End` go to the first and last column of the row; with `ctrl`, to the first and
42
+ * last cell of the grid.
43
+ * - `PageUp` and `PageDown` move `page` rows.
44
+ *
45
+ * @param from - The cursor.
46
+ * @param key - A `KeyboardEvent.key`.
47
+ * @param size - The grid.
48
+ * @param page - Rows in a page, at least 1.
49
+ * @param ctrl - Whether Ctrl (or Cmd) is held.
50
+ * @returns The new position, or `null` when the key is not a navigation key or the grid is empty.
51
+ * The position is clamped, so it may equal `from`.
52
+ */
53
+ export function moveFocus(from: GridPos, key: string, size: GridSize, page: number, ctrl = false): GridPos | null {
54
+ if (size.rows <= 0 || size.cols <= 0) return null;
55
+ const lastRow = size.rows - 1;
56
+ const lastCol = size.cols - 1;
57
+ const step = Math.max(1, Math.floor(page));
58
+ const at = (row: number, col: number): GridPos => ({ row: clamp(row, 0, lastRow), col: clamp(col, 0, lastCol) });
59
+ switch (key) {
60
+ case "ArrowUp":
61
+ return at(from.row - 1, from.col);
62
+ case "ArrowDown":
63
+ return at(from.row + 1, from.col);
64
+ case "ArrowLeft":
65
+ return at(from.row, from.col - 1);
66
+ case "ArrowRight":
67
+ return at(from.row, from.col + 1);
68
+ case "Home":
69
+ return ctrl ? at(0, 0) : at(from.row, 0);
70
+ case "End":
71
+ return ctrl ? at(lastRow, lastCol) : at(from.row, lastCol);
72
+ case "PageUp":
73
+ return at(from.row - step, from.col);
74
+ case "PageDown":
75
+ return at(from.row + step, from.col);
76
+ default:
77
+ return null;
78
+ }
79
+ }
80
+
81
+ /**
82
+ * The items of one axis to render for a scroll position, plus a margin.
83
+ *
84
+ * @param scroll - The scroll offset along the axis, in pixels, from the start of the body.
85
+ * @param viewport - The room the body has on that axis (the scroller's size less the sticky header).
86
+ * @param size - One item's size in pixels.
87
+ * @param count - The number of items.
88
+ * @param overscan - Extra items on each side.
89
+ * @returns `[start, end)`: indices to render. `[0, 0)` for no items or a non-positive size.
90
+ */
91
+ export function windowRange(scroll: number, viewport: number, size: number, count: number, overscan: number): [number, number] {
92
+ if (count <= 0 || !(size > 0)) return [0, 0];
93
+ const first = Math.floor(Math.max(0, scroll) / size);
94
+ const last = Math.ceil((Math.max(0, scroll) + Math.max(0, viewport)) / size);
95
+ // A scroll far past the end still shows the last item.
96
+ if (first >= count) return [Math.max(0, count - 1 - overscan), count];
97
+ const start = clamp(first - overscan, 0, count);
98
+ return [start, clamp(last + overscan, start, count)];
99
+ }
100
+
101
+ /**
102
+ * The scroll offset that brings an item fully into view, moving as little as possible.
103
+ *
104
+ * @param scroll - The current offset.
105
+ * @param viewport - The room the body has on this axis.
106
+ * @param index - The item.
107
+ * @param size - One item's size.
108
+ * @returns The offset: unchanged when the item is in view already, never negative.
109
+ */
110
+ export function revealScroll(scroll: number, viewport: number, index: number, size: number): number {
111
+ const start = index * size;
112
+ const end = start + size;
113
+ if (start < scroll) return Math.max(0, start);
114
+ if (end > scroll + viewport) return Math.max(0, end - viewport);
115
+ return scroll;
116
+ }
117
+
118
+ /** The rectangle between two cells, in whichever order they are given. */
119
+ export function rectBetween(a: GridPos, b: GridPos): GridRect {
120
+ return { row0: Math.min(a.row, b.row), row1: Math.max(a.row, b.row), col0: Math.min(a.col, b.col), col1: Math.max(a.col, b.col) };
121
+ }
122
+
123
+ /** Whether a cell is in a rectangle. */
124
+ export function inRect(rect: GridRect | null, row: number, col: number): boolean {
125
+ return rect !== null && row >= rect.row0 && row <= rect.row1 && col >= rect.col0 && col <= rect.col1;
126
+ }
package/src/index.ts CHANGED
@@ -44,6 +44,15 @@ export { acceptsFile, acceptsPath, collectDroppedFiles, type DropEntry } from ".
44
44
  export { SequenceNavigator, type SequenceItem, type SequenceItemStatus, type SequenceNavigatorProps } from "./components/SequenceNavigator";
45
45
  export { stepIndex } from "./components/sequence";
46
46
 
47
+ export {
48
+ SequenceMatrix,
49
+ type SequenceMatrixCellState,
50
+ type SequenceMatrixColumn,
51
+ type SequenceMatrixProps,
52
+ type SequenceMatrixRow,
53
+ type SequenceMatrixSelection,
54
+ } from "./components/SequenceMatrix";
55
+
47
56
  export { Stepper, type StepperProps, type StepperStep } from "./components/Stepper";
48
57
  export { type StepGate, type StepState, type StepView, stepStates } from "./components/stepperModel";
49
58