@barqjs/aria 0.0.0-stage → 0.2.0-next.1

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.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +304 -2
  3. package/package.json +437 -4
  4. package/src/autocomplete.tsx +581 -0
  5. package/src/breadcrumbs.tsx +297 -0
  6. package/src/button.tsx +468 -0
  7. package/src/calendar.tsx +2316 -0
  8. package/src/checkbox.tsx +732 -0
  9. package/src/collections.ts +1059 -0
  10. package/src/color.ts +2119 -0
  11. package/src/colorpicker.tsx +2023 -0
  12. package/src/colorswatchpicker.tsx +240 -0
  13. package/src/combobox.tsx +3003 -0
  14. package/src/command.tsx +1203 -0
  15. package/src/date.ts +674 -0
  16. package/src/datefield.tsx +2066 -0
  17. package/src/datepicker.tsx +907 -0
  18. package/src/dialog.tsx +1077 -0
  19. package/src/disclosure.tsx +711 -0
  20. package/src/dnd/clipboard.ts +125 -0
  21. package/src/dnd/collection.ts +1265 -0
  22. package/src/dnd/data.ts +409 -0
  23. package/src/dnd/drag-drop.ts +801 -0
  24. package/src/dnd/index.ts +133 -0
  25. package/src/dnd/manager.ts +639 -0
  26. package/src/dnd/strings.ts +1279 -0
  27. package/src/dnd/targets.ts +726 -0
  28. package/src/dnd/types.ts +212 -0
  29. package/src/dom.ts +703 -0
  30. package/src/drag-and-drop.tsx +669 -0
  31. package/src/drawer.ts +674 -0
  32. package/src/dropzone.tsx +208 -0
  33. package/src/file-trigger.tsx +103 -0
  34. package/src/focus.ts +1370 -0
  35. package/src/form.tsx +94 -0
  36. package/src/gridlist.tsx +1354 -0
  37. package/src/group.tsx +146 -0
  38. package/src/i18n.ts +823 -0
  39. package/src/index.ts +1672 -0
  40. package/src/interactions/description.ts +73 -0
  41. package/src/interactions/flags.ts +35 -0
  42. package/src/interactions/focus-events.ts +226 -0
  43. package/src/interactions/focusable.ts +86 -0
  44. package/src/interactions/hover.ts +213 -0
  45. package/src/interactions/interact-outside.ts +123 -0
  46. package/src/interactions/keyboard.ts +298 -0
  47. package/src/interactions/listeners.ts +78 -0
  48. package/src/interactions/long-press.ts +160 -0
  49. package/src/interactions/modality.ts +428 -0
  50. package/src/interactions/move.ts +257 -0
  51. package/src/interactions/open-link.ts +226 -0
  52. package/src/interactions/press.ts +915 -0
  53. package/src/interactions/prevent-focus.ts +102 -0
  54. package/src/interactions/scroll-wheel.ts +43 -0
  55. package/src/interactions/text-selection.ts +77 -0
  56. package/src/interactions.ts +81 -0
  57. package/src/label.ts +140 -0
  58. package/src/link.tsx +477 -0
  59. package/src/listbox.tsx +1247 -0
  60. package/src/live.ts +208 -0
  61. package/src/menu.tsx +2383 -0
  62. package/src/menubar.tsx +579 -0
  63. package/src/navigation-tree.tsx +357 -0
  64. package/src/navigation.ts +735 -0
  65. package/src/numberfield.tsx +942 -0
  66. package/src/otp.ts +430 -0
  67. package/src/overlay-arrow.tsx +157 -0
  68. package/src/overlays.ts +1549 -0
  69. package/src/platform.ts +75 -0
  70. package/src/presence.ts +164 -0
  71. package/src/preview-trigger.tsx +582 -0
  72. package/src/progress-bar-context.ts +15 -0
  73. package/src/questionnaire.tsx +1717 -0
  74. package/src/radio.tsx +641 -0
  75. package/src/register-dom.ts +12 -0
  76. package/src/scroller.ts +1165 -0
  77. package/src/select.tsx +1745 -0
  78. package/src/selection-indicator.tsx +74 -0
  79. package/src/selection.ts +1472 -0
  80. package/src/shared-element-transition.tsx +316 -0
  81. package/src/sheet.tsx +1461 -0
  82. package/src/slider.tsx +1137 -0
  83. package/src/splitter.ts +1152 -0
  84. package/src/static-collection.ts +211 -0
  85. package/src/switch.tsx +212 -0
  86. package/src/table.tsx +2218 -0
  87. package/src/tabs.tsx +1127 -0
  88. package/src/tag.tsx +637 -0
  89. package/src/textarea.tsx +186 -0
  90. package/src/textfield.tsx +483 -0
  91. package/src/toast-components.tsx +589 -0
  92. package/src/toast.ts +658 -0
  93. package/src/toggle-button-group.tsx +175 -0
  94. package/src/toggle-input.tsx +86 -0
  95. package/src/toggle.ts +384 -0
  96. package/src/togglegroup.ts +365 -0
  97. package/src/tokenfield.tsx +1673 -0
  98. package/src/toolbar.tsx +184 -0
  99. package/src/tooltip.tsx +674 -0
  100. package/src/tree.tsx +2075 -0
  101. package/src/utils.ts +787 -0
  102. package/src/validation.ts +504 -0
  103. package/src/virtualizer.tsx +837 -0
package/src/table.tsx ADDED
@@ -0,0 +1,2218 @@
1
+ /**
2
+ * A table: rows and columns, navigated a CELL at a time.
3
+ *
4
+ * The difference from a grid list is where focus lives. A grid list has one
5
+ * column, so a row is a place to stand; a table has many, and a screen reader
6
+ * user reads it by moving across cells and hearing the column header with
7
+ * each one. So the arrows move between cells in two dimensions, the column
8
+ * headers are themselves focusable, and every cell carries `aria-colindex`.
9
+ *
10
+ * Three things a `<table>` of `<div>`s has to put back by hand:
11
+ *
12
+ * - **The row header.** One column identifies the row, and its cells are
13
+ * `role="rowheader"` rather than `gridcell`, so a screen reader announces
14
+ * "Budget, Modified, yesterday" instead of "column 3, yesterday".
15
+ * - **Sorting.** `aria-sort` goes on the sorted column header and NOWHERE
16
+ * else: it names the one column the table is ordered by, and two of them is
17
+ * a contradiction.
18
+ * - **The select-all checkbox** in the header, which is indeterminate when
19
+ * some but not all rows are selected — a state a plain checkbox has no way
20
+ * to be.
21
+ */
22
+
23
+ import {
24
+ cells,
25
+ type Accessor,
26
+ type Child,
27
+ For,
28
+ createMemo,
29
+ createContext,
30
+ createEffect,
31
+ createRenderEffect,
32
+ createSignal,
33
+ getContext,
34
+ getOwner,
35
+ type Incoming,
36
+ install,
37
+ provide,
38
+ Show,
39
+ untrack,
40
+ } from "@barqjs/core";
41
+ import { isServer } from "@barqjs/web";
42
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
43
+ import type {
44
+ ItemAccessors,
45
+ Key,
46
+ LayoutDelegate,
47
+ Node,
48
+ SelectionMode,
49
+ SelectionValue,
50
+ } from "./collections.ts";
51
+ import { ListCollection } from "./collections.ts";
52
+ import {
53
+ contentStyle,
54
+ measureRow,
55
+ rowStyle,
56
+ useVirtualizer,
57
+ type LayoutInfo,
58
+ type VirtualizerValue,
59
+ } from "./virtualizer.tsx";
60
+ import {
61
+ buildCollection,
62
+ multipleSelectionState,
63
+ SelectionManager,
64
+ type Collection,
65
+ type MultipleSelectionOptions,
66
+ type MultipleSelectionState,
67
+ } from "./collections.ts";
68
+ import { button, type ButtonOptions } from "./button.tsx";
69
+ import {
70
+ afterDropIndicatorTargets,
71
+ type DroppableCollectionActivateEvent,
72
+ type ItemDropTarget,
73
+ TreeDropTargetDelegate,
74
+ } from "./dnd/index.ts";
75
+ import {
76
+ type CollectionDragAndDrop,
77
+ collectionDragAndDrop,
78
+ type DragAndDropHooks,
79
+ draggableItemSlotProps,
80
+ type DropIndicatorProps,
81
+ provideDragButton,
82
+ provideDropIndicator,
83
+ useDragAndDropContext,
84
+ dropIndicatorStyle,
85
+ } from "./drag-and-drop.tsx";
86
+ import {
87
+ activeElement,
88
+ contains,
89
+ isScrollable,
90
+ ownerDocument,
91
+ PREVENT_FOCUS_ATTRIBUTE,
92
+ targetElement,
93
+ } from "./dom.ts";
94
+ import { focusableWalker, focusRing } from "./focus.ts";
95
+ import { SelectionIndicatorProvider } from "./selection-indicator.tsx";
96
+ import { SharedElementTransition } from "./shared-element-transition.tsx";
97
+ import { collator, StringDictionary, stringFormatter, useLocale } from "./i18n.ts";
98
+ import { focusSafely } from "./interactions/focusable.ts";
99
+ import { hover } from "./interactions/hover.ts";
100
+ import { press, type ElementRef } from "./interactions/press.ts";
101
+ import { visuallyHidden } from "./live.ts";
102
+ import {
103
+ DOMLayoutDelegate,
104
+ ListKeyboardDelegate,
105
+ selectableCollection,
106
+ selectableItem,
107
+ type Direction,
108
+ type KeyboardDelegate,
109
+ } from "./selection.ts";
110
+ import {
111
+ access,
112
+ callback,
113
+ controllable,
114
+ type DOMProps,
115
+ filterDOMProps,
116
+ fromProps,
117
+ id,
118
+ type MaybeAccessor,
119
+ mergeProps,
120
+ type StyleProps,
121
+ styleProps,
122
+ } from "./utils.ts";
123
+
124
+ // ---------------------------------------------------------------------------
125
+ // The collection
126
+ // ---------------------------------------------------------------------------
127
+
128
+ /**
129
+ * A cell's key, from its row's and its column's.
130
+ *
131
+ * A NUL between them, because a key is a string or a number and either may
132
+ * contain any printable character: `"a-b" + "c"` and `"a" + "b-c"` are
133
+ * different cells that a hyphen would give the same key.
134
+ */
135
+ export function cellKeyFor(rowKey: Key, columnKey: Key): string {
136
+ return `${String(rowKey)}\u0000${String(columnKey)}`;
137
+ }
138
+
139
+ export interface TableColumnProps {
140
+ /** Let the user sort by this column. */
141
+ allowsSorting?: boolean;
142
+ /** This column's cells identify their row. */
143
+ isRowHeader?: boolean;
144
+ [key: string]: unknown;
145
+ }
146
+
147
+ export interface SortDescriptor {
148
+ column: Key;
149
+ direction: "ascending" | "descending";
150
+ }
151
+
152
+ /**
153
+ * Rows and columns, presenting the ROWS as its items.
154
+ *
155
+ * Selection, "select all" and the focus repair all work in terms of what a
156
+ * user selects, which is a row; the cells exist for `getItem` and for the
157
+ * keyboard delegate, which walks them by index.
158
+ */
159
+ /**
160
+ * A cell's text, for typeahead.
161
+ *
162
+ * Anything that is not already a string or a number has no text a user could
163
+ * type: `String({})` is "[object Object]", which matches nothing and reads as
164
+ * garbage to a screen reader.
165
+ */
166
+ function cellText(props: unknown, column: Key): string {
167
+ const value = (props as Record<string, unknown> | undefined)?.[String(column)];
168
+ return typeof value === "string" || typeof value === "number" ? String(value) : "";
169
+ }
170
+
171
+ /** Where a row sits among its siblings, for a table whose rows nest. */
172
+ export interface TableRowPosition {
173
+ /** Counting from 1, as `aria-posinset` does. */
174
+ posinset: number;
175
+ setsize: number;
176
+ hasChildRows: boolean;
177
+ }
178
+
179
+ export interface TableCollectionOptions {
180
+ /** Where the footer's rows start in `rows`. @default `rows.length` */
181
+ footerStart?: number;
182
+ /** Each visible row's place among its siblings, when the rows nest. */
183
+ tree?: Map<Key, TableRowPosition>;
184
+ }
185
+
186
+ export class TableCollection<R, C> implements Collection<R> {
187
+ readonly columns: Node<C>[];
188
+ /** Every row that can be reached: the body's, expanded ones' children, then the footer's. */
189
+ readonly rows: Node<R>[];
190
+ readonly rowHeaderColumns: Node<C>[];
191
+ readonly footerStart: number;
192
+ #tree: Map<Key, TableRowPosition> | null;
193
+ #rowIndex = new Map<Key, number>();
194
+ #columnIndex = new Map<Key, number>();
195
+ #cells = new Map<Key, { row: Node<R>; column: Node<C>; index: number }>();
196
+
197
+ constructor(rows: Node<R>[], columns: Node<C>[], options: TableCollectionOptions = {}) {
198
+ this.rows = rows;
199
+ this.columns = columns;
200
+ this.footerStart = Math.min(options.footerStart ?? rows.length, rows.length);
201
+ this.#tree = options.tree ?? null;
202
+ rows.forEach((row, at) => this.#rowIndex.set(row.key, at));
203
+ columns.forEach((column, at) => this.#columnIndex.set(column.key, at));
204
+ // Composed once rather than parsed on every lookup, so a key that happens
205
+ // to contain the separator misses rather than resolving to the wrong cell.
206
+ for (const row of rows) {
207
+ columns.forEach((column, index) => {
208
+ this.#cells.set(cellKeyFor(row.key, column.key), { row, column, index });
209
+ });
210
+ }
211
+
212
+ const declared = columns.filter((column) => column.props?.isRowHeader === true);
213
+ // Without one declared, the FIRST column identifies the row. A table with
214
+ // no row header at all is one a screen reader reads as a wall of values.
215
+ this.rowHeaderColumns = declared.length > 0 ? declared : columns.slice(0, 1);
216
+ }
217
+
218
+ get size(): number {
219
+ return this.rows.length;
220
+ }
221
+
222
+ get bodyRows(): Node<R>[] {
223
+ return this.rows.slice(0, this.footerStart);
224
+ }
225
+
226
+ get footerRows(): Node<R>[] {
227
+ return this.rows.slice(this.footerStart);
228
+ }
229
+
230
+ /** Whether the rows nest, which is what makes the table a tree grid. */
231
+ get isTree(): boolean {
232
+ return this.#tree !== null;
233
+ }
234
+
235
+ rowPosition(key: Key): TableRowPosition | null {
236
+ return this.#tree?.get(key) ?? null;
237
+ }
238
+
239
+ *[Symbol.iterator](): IterableIterator<Node<R>> {
240
+ yield* this.rows;
241
+ }
242
+
243
+ *getKeys(): IterableIterator<Key> {
244
+ for (const row of this.rows) yield row.key;
245
+ }
246
+
247
+ rowIndexOf(key: Key): number {
248
+ return this.#rowIndex.get(key) ?? -1;
249
+ }
250
+
251
+ columnIndexOf(key: Key): number {
252
+ return this.#columnIndex.get(key) ?? -1;
253
+ }
254
+
255
+ /**
256
+ * The row and column a cell key names, or null if it names neither.
257
+ *
258
+ * Looked up rather than split: splitting gives back strings, and a row or
259
+ * column keyed by a number would then name no cell at all.
260
+ */
261
+ parseCellKey(key: Key): { row: Node<R>; column: Node<C>; index: number } | null {
262
+ return this.#cells.get(key) ?? null;
263
+ }
264
+
265
+ getItem(key: Key): Node<R> | null {
266
+ const at = this.#rowIndex.get(key);
267
+ if (at !== undefined) return this.rows[at] as Node<R>;
268
+
269
+ const cell = this.parseCellKey(key);
270
+ if (cell !== null) {
271
+ return {
272
+ type: "cell",
273
+ key,
274
+ value: cell.row.value,
275
+ textValue: cellText(cell.row.props, cell.column.key),
276
+ level: 1,
277
+ index: cell.index,
278
+ parentKey: cell.row.key,
279
+ hasChildNodes: false,
280
+ childNodes: [],
281
+ props: cell.row.props,
282
+ } as unknown as Node<R>;
283
+ }
284
+
285
+ const columnAt = this.#columnIndex.get(key);
286
+ if (columnAt !== undefined) return this.columns[columnAt] as unknown as Node<R>;
287
+ return null;
288
+ }
289
+
290
+ getKeyBefore(key: Key): Key | null {
291
+ const at = this.#rowIndex.get(key);
292
+ if (at === undefined || at === 0) return null;
293
+ return (this.rows[at - 1] as Node<R>).key;
294
+ }
295
+
296
+ getKeyAfter(key: Key): Key | null {
297
+ const at = this.#rowIndex.get(key);
298
+ if (at === undefined || at >= this.rows.length - 1) return null;
299
+ return (this.rows[at + 1] as Node<R>).key;
300
+ }
301
+
302
+ getFirstKey(): Key | null {
303
+ return this.rows[0]?.key ?? null;
304
+ }
305
+
306
+ getLastKey(): Key | null {
307
+ return this.rows[this.rows.length - 1]?.key ?? null;
308
+ }
309
+
310
+ getChildren(): Iterable<Node<R>> {
311
+ return [];
312
+ }
313
+
314
+ at(index: number): Node<R> | null {
315
+ return this.rows[index] ?? null;
316
+ }
317
+ }
318
+
319
+ // ---------------------------------------------------------------------------
320
+ // Navigation
321
+ // ---------------------------------------------------------------------------
322
+
323
+ export interface TableKeyboardDelegateOptions<R, C> {
324
+ collection: Accessor<TableCollection<R, C>>;
325
+ disabledKeys?: Accessor<Set<Key>>;
326
+ direction?: MaybeAccessor<Direction | undefined>;
327
+ collator?: Accessor<Intl.Collator>;
328
+ /** The grid element, for deciding whether a page is a page at all. */
329
+ ref?: ElementRef;
330
+ /**
331
+ * Where the rows are.
332
+ *
333
+ * The DOM when the table renders all of them. A VIRTUALISED table must pass
334
+ * its layout instead, because Page Down has to reach a row that is not in
335
+ * the document yet and no measurement of the document can find one.
336
+ */
337
+ layoutDelegate?: LayoutDelegate;
338
+ }
339
+
340
+ /**
341
+ * Two-dimensional navigation over cells and column headers.
342
+ *
343
+ * Up from the first row reaches the COLUMN HEADER, which is how a keyboard
344
+ * user sorts a table without a pointer. Left and right follow the writing
345
+ * direction and stop at the ends rather than wrapping: wrapping from the last
346
+ * column of one row to the first of the next reads as a jump nobody asked for.
347
+ */
348
+ export class TableKeyboardDelegate<R, C> implements KeyboardDelegate {
349
+ #options: TableKeyboardDelegateOptions<R, C>;
350
+
351
+ #layout: LayoutDelegate;
352
+
353
+ constructor(options: TableKeyboardDelegateOptions<R, C>) {
354
+ this.#options = options;
355
+ this.#layout =
356
+ options.layoutDelegate ?? new DOMLayoutDelegate(options.ref ?? ((): null => null));
357
+ }
358
+
359
+ get #collection(): TableCollection<R, C> {
360
+ return this.#options.collection();
361
+ }
362
+
363
+ get #rtl(): boolean {
364
+ return (access(this.#options.direction) ?? "ltr") === "rtl";
365
+ }
366
+
367
+ #isDisabled(row: Node<R>): boolean {
368
+ return this.#options.disabledKeys?.().has(row.key) === true || row.props?.isDisabled === true;
369
+ }
370
+
371
+ /** Where a key stands: a column header, or a cell at (row, column). */
372
+ #locate(key: Key): { rowAt: number; columnAt: number } | null {
373
+ const collection = this.#collection;
374
+ const columnAt = collection.columnIndexOf(key);
375
+ if (columnAt >= 0) return { rowAt: -1, columnAt };
376
+ const cell = collection.parseCellKey(key);
377
+ if (cell === null) return null;
378
+ return { rowAt: collection.rowIndexOf(cell.row.key), columnAt: cell.index };
379
+ }
380
+
381
+ #cellAt(rowAt: number, columnAt: number): Key | null {
382
+ const collection = this.#collection;
383
+ if (rowAt < 0) return collection.columns[columnAt]?.key ?? null;
384
+ const row = collection.rows[rowAt];
385
+ const column = collection.columns[columnAt];
386
+ if (row === undefined || column === undefined) return null;
387
+ return cellKeyFor(row.key, column.key);
388
+ }
389
+
390
+ /** The next row in a direction that is not disabled. */
391
+ #rowStep(from: number, by: 1 | -1): number | null {
392
+ const collection = this.#collection;
393
+ for (let at = from + by; at >= 0 && at < collection.rows.length; at += by) {
394
+ const row = collection.rows[at];
395
+ if (row !== undefined && !this.#isDisabled(row)) return at;
396
+ }
397
+ return null;
398
+ }
399
+
400
+ getKeyBelow(key: Key): Key | null {
401
+ const at = this.#locate(key);
402
+ if (at === null) return null;
403
+ // From a column header, into the first row of that column.
404
+ if (at.rowAt === -1) {
405
+ const first = this.#rowStep(-1, 1);
406
+ return first === null ? null : this.#cellAt(first, at.columnAt);
407
+ }
408
+ const next = this.#rowStep(at.rowAt, 1);
409
+ return next === null ? null : this.#cellAt(next, at.columnAt);
410
+ }
411
+
412
+ getKeyAbove(key: Key): Key | null {
413
+ const at = this.#locate(key);
414
+ if (at === null || at.rowAt === -1) return null;
415
+ const previous = this.#rowStep(at.rowAt, -1);
416
+ // Off the top of the body: the column header, so sorting is reachable.
417
+ if (previous === null) return this.#cellAt(-1, at.columnAt);
418
+ return this.#cellAt(previous, at.columnAt);
419
+ }
420
+
421
+ #sideways(key: Key, by: 1 | -1): Key | null {
422
+ const at = this.#locate(key);
423
+ if (at === null) return null;
424
+ const columnAt = at.columnAt + (this.#rtl ? -by : by);
425
+ if (columnAt < 0 || columnAt >= this.#collection.columns.length) return null;
426
+ return this.#cellAt(at.rowAt, columnAt);
427
+ }
428
+
429
+ getKeyRightOf(key: Key): Key | null {
430
+ return this.#sideways(key, 1);
431
+ }
432
+
433
+ getKeyLeftOf(key: Key): Key | null {
434
+ return this.#sideways(key, -1);
435
+ }
436
+
437
+ /**
438
+ * As far as the arrows can go from here, in one direction.
439
+ *
440
+ * Not `getFirstKey`/`getLastKey`: those land in the first COLUMN, and a page
441
+ * key must keep the column it started in. Walking with the arrow steps also
442
+ * skips a disabled row exactly as an arrow key does.
443
+ */
444
+ #edge(key: Key, step: (from: Key) => Key | null): Key {
445
+ let at = key;
446
+ for (;;) {
447
+ const next = step(at);
448
+ if (next === null || next === at) return at;
449
+ at = next;
450
+ }
451
+ }
452
+
453
+ /**
454
+ * A page up or down, measured in ROWS.
455
+ *
456
+ * The column is kept: Page Down from the third column lands on the third
457
+ * column of a row a viewport away, which is what makes paging through a wide
458
+ * table usable.
459
+ */
460
+ getKeyPageAbove(key: Key): Key | null {
461
+ const container = access(this.#options.ref) as HTMLElement | null;
462
+ const up = (from: Key): Key | null => this.getKeyAbove(from);
463
+
464
+ let rect = this.#layout.getItemRect(key);
465
+ // Nothing scrolls, or nothing can be measured: a page is the whole table.
466
+ if (rect === null || (container !== null && !isScrollable(container))) {
467
+ return this.#edge(key, up);
468
+ }
469
+
470
+ const visible = this.#layout.getVisibleRect();
471
+ const top = Math.max(0, rect.y + rect.height - visible.height);
472
+ let at: Key = key;
473
+
474
+ while (rect !== null && rect.y > top) {
475
+ const next = up(at);
476
+ if (next === null) break;
477
+ at = next;
478
+ rect = this.#layout.getItemRect(at);
479
+ }
480
+
481
+ return at;
482
+ }
483
+
484
+ getKeyPageBelow(key: Key): Key | null {
485
+ const container = access(this.#options.ref) as HTMLElement | null;
486
+ const down = (from: Key): Key | null => this.getKeyBelow(from);
487
+
488
+ let rect = this.#layout.getItemRect(key);
489
+ if (rect === null || (container !== null && !isScrollable(container))) {
490
+ return this.#edge(key, down);
491
+ }
492
+
493
+ const visible = this.#layout.getVisibleRect();
494
+ const content = this.#layout.getContentSize();
495
+ const bottom = Math.min(content.height, rect.y - rect.height + visible.height);
496
+ let at: Key = key;
497
+
498
+ while (rect !== null && rect.y < bottom) {
499
+ const next = down(at);
500
+ if (next === null) break;
501
+ at = next;
502
+ rect = this.#layout.getItemRect(at);
503
+ }
504
+
505
+ return at;
506
+ }
507
+
508
+ /**
509
+ * Home: the start of the row focus is in. With `global` (Control or
510
+ * Command held) or nowhere to start from, the first cell of the table.
511
+ *
512
+ * The writing direction does not enter into it: the first cell is the
513
+ * first column, whichever side of the screen that column is drawn on.
514
+ */
515
+ getFirstKey(fromKey?: Key | null, global?: boolean): Key | null {
516
+ const at = fromKey === undefined || fromKey === null ? null : this.#locate(fromKey);
517
+ if (at !== null && global !== true) return this.#cellAt(at.rowAt, 0);
518
+ const first = this.#rowStep(-1, 1);
519
+ if (first === null) return null;
520
+ return this.#cellAt(first, 0);
521
+ }
522
+
523
+ /** End: the end of the row focus is in, or with `global` the table's last cell. */
524
+ getLastKey(fromKey?: Key | null, global?: boolean): Key | null {
525
+ const at = fromKey === undefined || fromKey === null ? null : this.#locate(fromKey);
526
+ const lastColumn = this.#collection.columns.length - 1;
527
+ if (at !== null && global !== true) return this.#cellAt(at.rowAt, lastColumn);
528
+ const last = this.#rowStep(this.#collection.rows.length, -1);
529
+ if (last === null) return null;
530
+ return this.#cellAt(last, fromKey === undefined || fromKey === null ? 0 : lastColumn);
531
+ }
532
+
533
+ getKeyForSearch(search: string, fromKey?: Key | null): Key | null {
534
+ const compare = this.#options.collator?.();
535
+ if (compare === undefined) return null;
536
+ const collection = this.#collection;
537
+ const at = fromKey === undefined || fromKey === null ? null : this.#locate(fromKey);
538
+ const columnAt = at?.columnAt ?? 0;
539
+ const start = at === null || at.rowAt < 0 ? 0 : at.rowAt + 1;
540
+
541
+ for (let step = 0; step < collection.rows.length; step++) {
542
+ const rowAt = (start + step) % collection.rows.length;
543
+ const row = collection.rows[rowAt];
544
+ if (row === undefined || this.#isDisabled(row)) continue;
545
+ const text = row.textValue;
546
+ if (compare.compare(text.slice(0, search.length), search) === 0) {
547
+ return this.#cellAt(rowAt, columnAt);
548
+ }
549
+ }
550
+ return null;
551
+ }
552
+ }
553
+
554
+ // ---------------------------------------------------------------------------
555
+ // State
556
+ // ---------------------------------------------------------------------------
557
+
558
+ /**
559
+ * Whether keys inside a cell move between cells or between the controls the
560
+ * cell holds.
561
+ *
562
+ * `arrow` walks the arrows through a cell's controls on the way across the
563
+ * row. `tab` leaves the arrows to the cells and lets Tab reach the controls
564
+ * inside the focused one, so a text field in a cell keeps its own arrow keys.
565
+ */
566
+ export type TableKeyboardNavigationBehavior = "arrow" | "tab";
567
+
568
+ export interface TableStateOptions<R, C> extends MultipleSelectionOptions {
569
+ items?: MaybeAccessor<Iterable<R> | undefined>;
570
+ columns?: MaybeAccessor<Iterable<C> | undefined>;
571
+ /** The footer's rows, after the body's. */
572
+ footerItems?: MaybeAccessor<Iterable<R> | undefined>;
573
+ rowAccessors?: MaybeAccessor<ItemAccessors<R> | undefined>;
574
+ columnAccessors?: MaybeAccessor<ItemAccessors<C> | undefined>;
575
+ sortDescriptor?: MaybeAccessor<SortDescriptor | undefined>;
576
+ /** Show a checkbox column. @default true where selection is possible */
577
+ showSelectionCheckboxes?: MaybeAccessor<boolean | undefined>;
578
+ onSortChange?: (descriptor: SortDescriptor) => void;
579
+ /**
580
+ * The column whose cells expand and collapse their row.
581
+ *
582
+ * Setting it makes a row's children (`item.children`, or `getChildren`)
583
+ * rows of their own, shown while the row is expanded, and the table a tree
584
+ * grid. Without it the rows are flat and children are ignored.
585
+ */
586
+ treeColumn?: MaybeAccessor<Key | undefined>;
587
+ expandedKeys?: MaybeAccessor<Iterable<Key> | undefined>;
588
+ defaultExpandedKeys?: MaybeAccessor<Iterable<Key> | undefined>;
589
+ onExpandedChange?: (keys: Set<Key>) => void;
590
+ /** @default "arrow" */
591
+ keyboardNavigationBehavior?: MaybeAccessor<TableKeyboardNavigationBehavior | undefined>;
592
+ }
593
+
594
+ export interface TableState<R, C> {
595
+ collection: Accessor<TableCollection<R, C>>;
596
+ selectionManager: Accessor<SelectionManager>;
597
+ disabledKeys: Accessor<Set<Key>>;
598
+ sortDescriptor: Accessor<SortDescriptor | undefined>;
599
+ showSelectionCheckboxes: Accessor<boolean>;
600
+ /** Sort by a column, flipping the direction when it is already the one. */
601
+ sort(column: Key): void;
602
+ treeColumn?: Accessor<Key | null>;
603
+ expandedKeys?: Accessor<Set<Key>>;
604
+ /** Expand a collapsed row, or collapse an expanded one. */
605
+ toggleKey?(key: Key): void;
606
+ keyboardNavigationBehavior?: Accessor<TableKeyboardNavigationBehavior>;
607
+ }
608
+
609
+ /**
610
+ * Move the roving focus off a row that is gone.
611
+ *
612
+ * The focused key is a CELL, and a cell names its row. When the row is
613
+ * deleted nothing holds `tabindex="0"` any more while the grid itself still
614
+ * says -1, because something inside is focused, and Tab can no longer reach
615
+ * the table at all. The cell in the same column of the row that took its
616
+ * place takes focus instead: the next row that survives, or the one before
617
+ * when it was the last. With no rows left the key is cleared, which hands the
618
+ * Tab stop back to the grid.
619
+ */
620
+ function repairFocus<R, C>(
621
+ collection: Accessor<TableCollection<R, C>>,
622
+ selectionManager: Accessor<SelectionManager>,
623
+ selection: MultipleSelectionState,
624
+ ): void {
625
+ let previous: TableCollection<R, C> | null = null;
626
+
627
+ createRenderEffect(
628
+ (): { current: TableCollection<R, C>; repair: boolean; next: Key | null } => {
629
+ const current = collection();
630
+ const focused = selection.focusedKey();
631
+ if (focused === null || previous === null || current.getItem(focused) !== null) {
632
+ return { current, repair: false, next: null };
633
+ }
634
+
635
+ const old = previous;
636
+ const manager = selectionManager();
637
+ const columnKey = (): Key | null => {
638
+ const cell = old.parseCellKey(focused);
639
+ const at = cell?.index ?? Math.max(0, old.columnIndexOf(focused));
640
+ const kept = cell === null ? null : current.columnIndexOf(cell.column.key);
641
+ const column =
642
+ kept !== null && kept >= 0
643
+ ? current.columns[kept]
644
+ : current.columns[Math.min(at, current.columns.length - 1)];
645
+ return column?.key ?? null;
646
+ };
647
+
648
+ // A column that went away: its neighbour in the header.
649
+ if (old.columnIndexOf(focused) >= 0) {
650
+ return { current, repair: true, next: columnKey() };
651
+ }
652
+
653
+ const rowKey = old.parseCellKey(focused)?.row.key ?? focused;
654
+ const from = old.rowIndexOf(rowKey);
655
+ const survives = (row: Node<R> | undefined): row is Node<R> =>
656
+ row !== undefined && current.rowIndexOf(row.key) >= 0 && !manager.isDisabled(row.key);
657
+
658
+ let row: Node<R> | undefined;
659
+ for (let at = from + 1; at < old.rows.length && row === undefined; at++) {
660
+ if (survives(old.rows[at])) row = old.rows[at];
661
+ }
662
+ for (let at = from - 1; at >= 0 && row === undefined; at--) {
663
+ if (survives(old.rows[at])) row = old.rows[at];
664
+ }
665
+
666
+ const column = columnKey();
667
+ const next = row === undefined || column === null ? null : cellKeyFor(row.key, column);
668
+ return { current, repair: true, next };
669
+ },
670
+ ({ current, repair, next }) => {
671
+ if (repair) selection.setFocusedKey(next);
672
+ previous = current;
673
+ },
674
+ );
675
+ }
676
+
677
+ function namedText(item: unknown): string | null {
678
+ const record = item as Record<string, unknown> | null | undefined;
679
+ const text = record?.textValue ?? record?.label ?? record?.name ?? record?.title;
680
+ return typeof text === "string" ? text : null;
681
+ }
682
+
683
+ export function tableState<R, C>(options: TableStateOptions<R, C>): TableState<R, C> {
684
+ const selection = multipleSelectionState(options);
685
+
686
+ const toSet = (keys: Iterable<Key> | undefined): Set<Key> | undefined =>
687
+ keys === undefined ? undefined : new Set(keys);
688
+ const [expandedKeys, setExpandedKeys] = controllable<Set<Key>>(
689
+ () => toSet(access(options.expandedKeys)),
690
+ () => toSet(access(options.defaultExpandedKeys)) ?? new Set(),
691
+ options.onExpandedChange,
692
+ );
693
+ const treeColumn = (): Key | null => access(options.treeColumn) ?? null;
694
+
695
+ // Built apart from the flattening, so expanding a row keeps every node it
696
+ // already had: a list keyed by node would otherwise rebuild each row, and
697
+ // the cell holding focus with it.
698
+ const built = createMemo(() => {
699
+ // Accessors are a value like any other prop, so a component hands them
700
+ // over as a Cell around the object.
701
+ const columns = [
702
+ ...buildCollection(access(options.columns) ?? [], access(options.columnAccessors) ?? {}),
703
+ ];
704
+ const declared = columns.filter((column) => column.props?.isRowHeader === true);
705
+ const headers = declared.length > 0 ? declared : columns.slice(0, 1);
706
+
707
+ // A row has no text of its own to type: it is cells. Without a name on
708
+ // the item, what a user can type is what the row header cells show, and
709
+ // never `String(item)`, which is "[object Object]".
710
+ const given = access(options.rowAccessors) ?? {};
711
+ const getProps = callback(given.getProps);
712
+ const rowAccessors: ItemAccessors<R> = {
713
+ ...given,
714
+ // A row with children is a row that nests, never a section. The
715
+ // parameter is declared because `callback` reads a function of no
716
+ // arguments as a Cell around one.
717
+ getType: callback(given.getType) ?? ((_row: R): "item" => "item"),
718
+ getTextValue:
719
+ callback(given.getTextValue) ??
720
+ ((item: R): string =>
721
+ namedText(item) ??
722
+ headers
723
+ .map((column) => cellText(getProps?.(item) ?? item, column.key))
724
+ .filter((text) => text !== "")
725
+ .join(" ")),
726
+ };
727
+
728
+ return {
729
+ columns,
730
+ body: [...buildCollection(access(options.items) ?? [], rowAccessors)],
731
+ footer: [...buildCollection(access(options.footerItems) ?? [], rowAccessors)],
732
+ };
733
+ });
734
+
735
+ const collection = createMemo(() => {
736
+ const { columns, body, footer } = built();
737
+ const isTree = treeColumn() !== null;
738
+ const expanded = isTree ? expandedKeys() : new Set<Key>();
739
+ const tree = isTree ? new Map<Key, TableRowPosition>() : undefined;
740
+ const rows: Node<R>[] = [];
741
+ const visit = (siblings: Node<R>[]): void => {
742
+ siblings.forEach((node, at) => {
743
+ rows.push(node);
744
+ tree?.set(node.key, {
745
+ posinset: at + 1,
746
+ setsize: siblings.length,
747
+ hasChildRows: node.childNodes.length > 0,
748
+ });
749
+ if (expanded.has(node.key)) visit(node.childNodes);
750
+ });
751
+ };
752
+ visit(body);
753
+
754
+ const footerStart = rows.length;
755
+ rows.push(...footer);
756
+
757
+ return new TableCollection<R, C>(rows, columns, { footerStart, tree });
758
+ });
759
+
760
+ const selectionManager = createMemo(
761
+ () => new SelectionManager(collection() as unknown as Collection<unknown>, selection),
762
+ );
763
+
764
+ repairFocus(collection, selectionManager, selection);
765
+
766
+ return {
767
+ collection,
768
+ selectionManager,
769
+ disabledKeys: selection.disabledKeys,
770
+ treeColumn,
771
+ expandedKeys,
772
+ toggleKey: (key) => {
773
+ const next = new Set(expandedKeys());
774
+ if (next.has(key)) next.delete(key);
775
+ else next.add(key);
776
+ setExpandedKeys(next);
777
+ },
778
+ keyboardNavigationBehavior: () => access(options.keyboardNavigationBehavior) ?? "arrow",
779
+ sortDescriptor: () => access(options.sortDescriptor),
780
+ showSelectionCheckboxes: () =>
781
+ access(options.showSelectionCheckboxes) ?? selection.selectionMode() === "multiple",
782
+ sort: (column) => {
783
+ const current = access(options.sortDescriptor);
784
+ // The same column again flips the direction; a different one starts
785
+ // ascending, because that is what a first click on a column means.
786
+ const direction =
787
+ current?.column === column && current.direction === "ascending"
788
+ ? "descending"
789
+ : "ascending";
790
+ options.onSortChange?.({ column, direction });
791
+ },
792
+ };
793
+ }
794
+
795
+ // ---------------------------------------------------------------------------
796
+ // Hooks
797
+ // ---------------------------------------------------------------------------
798
+
799
+ export interface TableOptions {
800
+ ref: ElementRef;
801
+ /** Where the rows are, when the DOM cannot answer because they are not in it. */
802
+ layoutDelegate?: LayoutDelegate;
803
+ isVirtualized?: MaybeAccessor<boolean | undefined>;
804
+ disallowEmptySelection?: MaybeAccessor<boolean | undefined>;
805
+ disallowTypeAhead?: MaybeAccessor<boolean | undefined>;
806
+ keyboardDelegate?: KeyboardDelegate;
807
+ "aria-label"?: MaybeAccessor<string | undefined>;
808
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
809
+ }
810
+
811
+ export interface TableResult {
812
+ gridProps: DOMProps;
813
+ baseId: Accessor<string>;
814
+ }
815
+
816
+ export function table<R, C>(options: TableOptions, state: TableState<R, C>): TableResult {
817
+ const baseId = id();
818
+ const locale = useLocale();
819
+ const search = collator({ usage: "search", sensitivity: "base" });
820
+
821
+ const delegate =
822
+ options.keyboardDelegate ??
823
+ new TableKeyboardDelegate<R, C>({
824
+ collection: state.collection,
825
+ disabledKeys: state.disabledKeys,
826
+ direction: () => locale().direction,
827
+ collator: search,
828
+ ref: options.ref,
829
+ layoutDelegate: options.layoutDelegate,
830
+ });
831
+
832
+ const { collectionProps } = selectableCollection({
833
+ ref: options.ref,
834
+ selectionManager: state.selectionManager,
835
+ keyboardDelegate: delegate,
836
+ disallowEmptySelection: options.disallowEmptySelection,
837
+ disallowTypeAhead: options.disallowTypeAhead,
838
+ // The focused key is a CELL and a selected key is a ROW; selecting what
839
+ // focus lands on would select cells.
840
+ selectOnFocus: false,
841
+ });
842
+
843
+ return {
844
+ baseId,
845
+ gridProps: mergeProps(filterDOMProps(options, { labelable: true }), collectionProps, {
846
+ role: () => (state.collection().isTree ? "treegrid" : "grid"),
847
+ id: baseId,
848
+ "aria-multiselectable": () =>
849
+ state.selectionManager().selectionMode === "multiple" ? true : undefined,
850
+ "aria-rowcount": () =>
851
+ // The header row counts: a screen reader saying "row 1 of 8" for the
852
+ // first body row of seven is off by the header it just read.
853
+ access(options.isVirtualized) === true ? state.collection().size + 1 : undefined,
854
+ "aria-colcount": () =>
855
+ access(options.isVirtualized) === true ? state.collection().columns.length : undefined,
856
+ }),
857
+ };
858
+ }
859
+
860
+ /**
861
+ * Focus for something that is a PLACE, not a value.
862
+ *
863
+ * A cell and a column header both take focus and neither is ever selected, so
864
+ * `selectableItem` is the wrong tool: the only way to tell it something is not
865
+ * selectable is to call it disabled, and a disabled item also refuses the
866
+ * roving focus — so its two effects then fight over who holds it and neither
867
+ * lets go.
868
+ *
869
+ * Under `child` focus a place that holds controls passes focus on to them: a
870
+ * cell holding a button is reached as the button, or the button could never
871
+ * be reached from the keyboard at all. Which end of the cell is entered at
872
+ * follows the direction focus arrived from.
873
+ */
874
+ function focusPlace(
875
+ key: Key,
876
+ ref: ElementRef,
877
+ manager: Accessor<SelectionManager>,
878
+ focusMode: () => "cell" | "child" = () => "cell",
879
+ ): { props: DOMProps; isFocused: Accessor<boolean> } {
880
+ const isFocused = (): boolean => manager().isFocused && manager().focusedKey === key;
881
+
882
+ const enter = (element: HTMLElement): void => {
883
+ // Focus already on something inside is where the user put it.
884
+ const active = activeElement(ownerDocument(element));
885
+ if (active !== element && contains(element, active)) return;
886
+ if (focusMode() === "child") {
887
+ const walker = focusableWalker(element);
888
+ const child = (
889
+ manager().childFocusStrategy === "last" ? walker.last() : walker.nextNode()
890
+ ) as HTMLElement | null;
891
+ if (child !== null) {
892
+ focusSafely(child);
893
+ return;
894
+ }
895
+ }
896
+ if (activeElement(ownerDocument(element)) !== element) focusSafely(element);
897
+ };
898
+
899
+ if (!isServer) {
900
+ createEffect(
901
+ () => {
902
+ if (manager().focusedKey !== key || !manager().isFocused) return null;
903
+ return { element: access(ref) as HTMLElement | null };
904
+ },
905
+ (focused) => {
906
+ if (focused === null) return;
907
+ const { element } = focused;
908
+ if (element !== null) untrack(() => enter(element));
909
+ },
910
+ );
911
+ }
912
+
913
+ return {
914
+ isFocused,
915
+ props: {
916
+ "data-key": String(key),
917
+ // A roving tabindex over the whole grid: exactly one place is in the Tab
918
+ // order, and the grid itself is the stop until something inside is.
919
+ tabIndex: () => (manager().focusedKey === key ? 0 : -1),
920
+ onFocus: (event: FocusEvent) => {
921
+ const element = access(ref) as HTMLElement | null;
922
+ if (element === null || targetElement(event) !== element) return;
923
+ if (manager().focusedKey !== key) {
924
+ manager().setFocusedKey(key);
925
+ return;
926
+ }
927
+ // Already the focused place, so no effect will run: a press on the
928
+ // cell's padding still lands on what the cell holds.
929
+ if (focusMode() === "child") enter(element);
930
+ },
931
+ // A control inside took focus directly, by a press or by Tab: the place
932
+ // holding it is where the roving focus is now, or the grid's own focus
933
+ // handling would pull focus back to wherever it was before.
934
+ onFocusIn: (event: FocusEvent) => {
935
+ const element = access(ref) as HTMLElement | null;
936
+ const target = targetElement(event);
937
+ if (element === null || target === element || !contains(element, target)) return;
938
+ if (manager().focusedKey !== key) manager().setFocusedKey(key);
939
+ },
940
+ },
941
+ };
942
+ }
943
+
944
+ export interface TableColumnHeaderOptions {
945
+ column: Node<unknown>;
946
+ ref: ElementRef;
947
+ baseId: MaybeAccessor<string>;
948
+ }
949
+
950
+ export interface TableColumnHeaderResult {
951
+ columnHeaderProps: DOMProps;
952
+ isFocused: Accessor<boolean>;
953
+ isPressed: Accessor<boolean>;
954
+ allowsSorting: Accessor<boolean>;
955
+ sortDirection: Accessor<"ascending" | "descending" | undefined>;
956
+ }
957
+
958
+ export function tableColumnHeader<R, C>(
959
+ options: TableColumnHeaderOptions,
960
+ state: TableState<R, C>,
961
+ ): TableColumnHeaderResult {
962
+ const allowsSorting = (): boolean => options.column.props?.allowsSorting === true;
963
+
964
+ const sortDirection = (): "ascending" | "descending" | undefined => {
965
+ const descriptor = state.sortDescriptor();
966
+ return descriptor?.column === options.column.key ? descriptor.direction : undefined;
967
+ };
968
+
969
+ const place = focusPlace(options.column.key, options.ref, state.selectionManager);
970
+ const sortByColumn = (): void => {
971
+ state.sort(options.column.key);
972
+ };
973
+ const { pressProps, isPressed } = press({
974
+ ref: options.ref,
975
+ isDisabled: () => !allowsSorting(),
976
+ onPress: sortByColumn,
977
+ });
978
+
979
+ const onKeyDown = (event: KeyboardEvent): void => {
980
+ if (!allowsSorting()) return;
981
+ if (event.key !== "Enter" && event.key !== " ") return;
982
+ event.preventDefault();
983
+ event.stopPropagation();
984
+ state.sort(options.column.key);
985
+ };
986
+
987
+ return {
988
+ allowsSorting,
989
+ sortDirection,
990
+ isFocused: place.isFocused,
991
+ isPressed,
992
+ columnHeaderProps: mergeProps(place.props, pressProps, {
993
+ id: () => columnHeaderIdFor(access(options.baseId), options.column.key),
994
+ role: "columnheader",
995
+ onKeyDown,
996
+ // On the SORTED column only. `aria-sort="none"` on the others says the
997
+ // table is unsorted, which contradicts the one that says it is not.
998
+ "aria-sort": sortDirection,
999
+ "aria-colindex": () => state.collection().columnIndexOf(options.column.key) + 1,
1000
+ }),
1001
+ };
1002
+ }
1003
+
1004
+ export interface TableRowOptions {
1005
+ row: Node<unknown>;
1006
+ ref: ElementRef;
1007
+ baseId: MaybeAccessor<string>;
1008
+ isVirtualized?: MaybeAccessor<boolean | undefined>;
1009
+ onAction?: (key: Key) => void;
1010
+ /** See `selectableItem`. @default `onAction !== undefined` */
1011
+ hasAction?: MaybeAccessor<boolean | undefined>;
1012
+ /** Select on pointer up rather than down, as a draggable row does. */
1013
+ shouldSelectOnPressUp?: MaybeAccessor<boolean | undefined>;
1014
+ }
1015
+
1016
+ export interface TableRowResult {
1017
+ rowProps: DOMProps;
1018
+ /** Options for {@link button}, for the control that expands the row. */
1019
+ expandButtonProps: ButtonOptions & DOMProps;
1020
+ isSelected: Accessor<boolean>;
1021
+ isDisabled: Accessor<boolean>;
1022
+ isPressed: Accessor<boolean>;
1023
+ isExpanded: Accessor<boolean>;
1024
+ hasChildRows: Accessor<boolean>;
1025
+ }
1026
+
1027
+ const strings = new StringDictionary<"expand" | "collapse">({
1028
+ "ar-AE": { expand: "تمديد", collapse: "طي" },
1029
+ "bg-BG": { expand: "Разширяване", collapse: "Свиване" },
1030
+ "cs-CZ": { expand: "Roztáhnout", collapse: "Sbalit" },
1031
+ "da-DK": { expand: "Udvid", collapse: "Skjul" },
1032
+ "de-DE": { expand: "Erweitern", collapse: "Reduzieren" },
1033
+ "el-GR": { expand: "Ανάπτυξη", collapse: "Σύμπτυξη" },
1034
+ "en-US": { expand: "Expand", collapse: "Collapse" },
1035
+ "es-ES": { expand: "Ampliar", collapse: "Contraer" },
1036
+ "et-EE": { expand: "Laienda", collapse: "Ahenda" },
1037
+ "fi-FI": { expand: "Laajenna", collapse: "Pienennä" },
1038
+ "fr-FR": { expand: "Développer", collapse: "Réduire" },
1039
+ "he-IL": { expand: "הרחב", collapse: "כווץ" },
1040
+ "hr-HR": { expand: "Proširi", collapse: "Sažmi" },
1041
+ "hu-HU": { expand: "Kibontás", collapse: "Összecsukás" },
1042
+ "it-IT": { expand: "Espandi", collapse: "Comprimi" },
1043
+ "ja-JP": { expand: "展開", collapse: "折りたたむ" },
1044
+ "ko-KR": { expand: "펼치기", collapse: "접기" },
1045
+ "lt-LT": { expand: "Išskleisti", collapse: "Sutraukti" },
1046
+ "lv-LV": { expand: "Izvērst", collapse: "Sakļaut" },
1047
+ "nb-NO": { expand: "Utvid", collapse: "Skjul" },
1048
+ "nl-NL": { expand: "Uitvouwen", collapse: "Samenvouwen" },
1049
+ "pl-PL": { expand: "Rozwiń", collapse: "Zwiń" },
1050
+ "pt-BR": { expand: "Expandir", collapse: "Recolher" },
1051
+ "pt-PT": { expand: "Expandir", collapse: "Colapsar" },
1052
+ "ro-RO": { expand: "Extindeți", collapse: "Restrângeți" },
1053
+ "ru-RU": { expand: "Развернуть", collapse: "Свернуть" },
1054
+ "sk-SK": { expand: "Rozbaliť", collapse: "Zbaliť" },
1055
+ "sl-SI": { expand: "Razširi", collapse: "Strni" },
1056
+ "sr-SP": { expand: "Proširi", collapse: "Skupi" },
1057
+ "sv-SE": { expand: "Expandera", collapse: "Dölj" },
1058
+ "tr-TR": { expand: "Genişlet", collapse: "Daralt" },
1059
+ "uk-UA": { expand: "Розгорнути", collapse: "Згорнути" },
1060
+ "zh-CN": { expand: "扩展", collapse: "折叠" },
1061
+ "zh-TW": { expand: "展開", collapse: "收合" },
1062
+ });
1063
+
1064
+ export function tableRow<R, C>(options: TableRowOptions, state: TableState<R, C>): TableRowResult {
1065
+ const manager = (): SelectionManager => state.selectionManager();
1066
+ const message = stringFormatter(strings);
1067
+ const key = options.row.key;
1068
+ const position = (): TableRowPosition | null => state.collection().rowPosition(key);
1069
+ const hasChildRows = (): boolean => position()?.hasChildRows === true;
1070
+ const isExpanded = (): boolean => hasChildRows() && state.expandedKeys?.().has(key) === true;
1071
+
1072
+ const item = selectableItem({
1073
+ key,
1074
+ ref: options.ref,
1075
+ selectionManager: state.selectionManager,
1076
+ isDisabled: () => options.row.props?.isDisabled === true,
1077
+ hasAction: () => access(options.hasAction) ?? options.onAction !== undefined,
1078
+ onAction: () => options.onAction?.(key),
1079
+ shouldSelectOnPressUp: options.shouldSelectOnPressUp,
1080
+ });
1081
+
1082
+ const rowHeaderIds = (): string =>
1083
+ state
1084
+ .collection()
1085
+ .rowHeaderColumns.map((column) => cellIdFor(access(options.baseId), key, column.key))
1086
+ .join(" ");
1087
+
1088
+ const expandButtonId = id();
1089
+
1090
+ return {
1091
+ isSelected: item.isSelected,
1092
+ isDisabled: item.isDisabled,
1093
+ isPressed: item.isPressed,
1094
+ isExpanded,
1095
+ hasChildRows,
1096
+ rowProps: mergeProps(item.itemProps, {
1097
+ role: "row",
1098
+ // The row itself is never the Tab stop: focus lives in a cell.
1099
+ tabIndex: () => undefined,
1100
+ "aria-selected": () => (manager().canSelectItem(key) ? item.isSelected() : undefined),
1101
+ "aria-disabled": () => item.isDisabled() || undefined,
1102
+ // A nested row's place is its level and its position among siblings,
1103
+ // which a flat row index would contradict.
1104
+ "aria-rowindex": () =>
1105
+ access(options.isVirtualized) === true && !state.collection().isTree
1106
+ ? state.collection().rowIndexOf(key) + 2
1107
+ : undefined,
1108
+ "aria-expanded": () => (hasChildRows() ? isExpanded() : undefined),
1109
+ "aria-level": () => (position() === null ? undefined : options.row.level + 1),
1110
+ "aria-posinset": () => position()?.posinset,
1111
+ "aria-setsize": () => position()?.setsize,
1112
+ "aria-labelledby": rowHeaderIds,
1113
+ }),
1114
+ expandButtonProps: {
1115
+ id: expandButtonId,
1116
+ isDisabled: item.isDisabled,
1117
+ excludeFromTabOrder: true,
1118
+ // The keyboard expands from the tree column's cell, so the button is a
1119
+ // pointer's alone and must not take focus away from that cell.
1120
+ preventFocusOnPress: true,
1121
+ [PREVENT_FOCUS_ATTRIBUTE]: true,
1122
+ "aria-label": () => message().format(isExpanded() ? "collapse" : "expand"),
1123
+ "aria-labelledby": () => `${expandButtonId()} ${rowHeaderIds()}`,
1124
+ onPress: () => {
1125
+ if (item.isDisabled()) return;
1126
+ state.toggleKey?.(key);
1127
+ const column = state.treeColumn?.() ?? state.collection().columns[0]?.key;
1128
+ if (column === undefined) return;
1129
+ manager().setFocused(true);
1130
+ manager().setFocusedKey(cellKeyFor(key, column));
1131
+ },
1132
+ },
1133
+ };
1134
+ }
1135
+
1136
+ /** The id a cell renders under. */
1137
+ export function cellIdFor(baseId: string, rowKey: Key, columnKey: Key): string {
1138
+ return `${baseId}-cell-${String(rowKey)}-${String(columnKey)}`;
1139
+ }
1140
+
1141
+ /**
1142
+ * The id a column header renders under.
1143
+ *
1144
+ * Derived from the table's own id for the reason `cellIdFor` is: two tables
1145
+ * with a column of the same key would otherwise write the same id twice. A
1146
+ * header needs one at all so that anything naming a column — a resize handle,
1147
+ * a caller's own summary — has something to point at.
1148
+ */
1149
+ export function columnHeaderIdFor(baseId: string, columnKey: Key): string {
1150
+ return `${baseId}-column-${String(columnKey)}`;
1151
+ }
1152
+
1153
+ export interface TableCellOptions {
1154
+ row: Node<unknown>;
1155
+ column: Node<unknown>;
1156
+ ref: ElementRef;
1157
+ baseId: MaybeAccessor<string>;
1158
+ /**
1159
+ * Whether focusing the cell focuses the first control inside it.
1160
+ *
1161
+ * @default "child", or "cell" when the table navigates by Tab
1162
+ */
1163
+ focusMode?: MaybeAccessor<"cell" | "child" | undefined>;
1164
+ }
1165
+
1166
+ export interface TableCellResult {
1167
+ gridCellProps: DOMProps;
1168
+ isFocused: Accessor<boolean>;
1169
+ isPressed: Accessor<boolean>;
1170
+ }
1171
+
1172
+ /** Every focusable element inside `element`, in order. */
1173
+ function focusablesIn(element: HTMLElement): HTMLElement[] {
1174
+ const walker = focusableWalker(element);
1175
+ const found: HTMLElement[] = [];
1176
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
1177
+ found.push(node as HTMLElement);
1178
+ }
1179
+ return found;
1180
+ }
1181
+
1182
+ export function tableCell<R, C>(
1183
+ options: TableCellOptions,
1184
+ state: TableState<R, C>,
1185
+ ): TableCellResult {
1186
+ const key = cellKeyFor(options.row.key, options.column.key);
1187
+ const locale = useLocale();
1188
+ const manager = (): SelectionManager => state.selectionManager();
1189
+ const behavior = (): TableKeyboardNavigationBehavior =>
1190
+ state.keyboardNavigationBehavior?.() ?? "arrow";
1191
+ const focusMode = (): "cell" | "child" =>
1192
+ access(options.focusMode) ?? (behavior() === "tab" ? "cell" : "child");
1193
+
1194
+ const isRowHeader = (): boolean =>
1195
+ state.collection().rowHeaderColumns.some((column) => column.key === options.column.key);
1196
+
1197
+ // Focus only. What a press on a cell MEANS is the row's business, and the
1198
+ // row has its own `selectableItem` for it.
1199
+ const place = focusPlace(key, options.ref, state.selectionManager, focusMode);
1200
+
1201
+ const cellElement = (): HTMLElement | null => (access(options.ref) as HTMLElement | null) ?? null;
1202
+
1203
+ /**
1204
+ * The expand and collapse keys, in the cell of the tree column.
1205
+ *
1206
+ * A tree grid row is opened with the arrow that points into it and closed
1207
+ * with the one pointing back out, and from a closed or childless row that
1208
+ * one goes up to the parent. Only then does the arrow move between cells.
1209
+ */
1210
+ const expansionKey = (event: KeyboardEvent): boolean => {
1211
+ if (state.treeColumn?.() !== options.column.key) return false;
1212
+ const position = state.collection().rowPosition(options.row.key);
1213
+ if (position === null || manager().isDisabled(options.row.key)) return false;
1214
+
1215
+ const rtl = locale().direction === "rtl";
1216
+ const expand = rtl ? "ArrowLeft" : "ArrowRight";
1217
+ const collapse = rtl ? "ArrowRight" : "ArrowLeft";
1218
+ const expanded = state.expandedKeys?.().has(options.row.key) === true;
1219
+
1220
+ if (event.key === expand && position.hasChildRows && !expanded) {
1221
+ state.toggleKey?.(options.row.key);
1222
+ return true;
1223
+ }
1224
+ if (event.key !== collapse) return false;
1225
+ if (position.hasChildRows && expanded) {
1226
+ state.toggleKey?.(options.row.key);
1227
+ return true;
1228
+ }
1229
+ const parent = options.row.parentKey;
1230
+ if (parent === undefined || state.collection().rowIndexOf(parent) < 0) return false;
1231
+ manager().setFocusedKey(cellKeyFor(parent, options.column.key));
1232
+ return true;
1233
+ };
1234
+
1235
+ /**
1236
+ * Left and right walk the controls inside the cell before they leave it.
1237
+ *
1238
+ * Under `child` focus the cell itself is never stood on, so the walk ends
1239
+ * at its first control; under `cell` focus it goes back to the cell. At
1240
+ * either end the key is left to the grid, which moves to the next cell.
1241
+ */
1242
+ const onKeyDownCapture = (event: KeyboardEvent): void => {
1243
+ const element = cellElement();
1244
+ if (element === null || !contains(element, targetElement(event))) return;
1245
+ if (expansionKey(event)) {
1246
+ event.preventDefault();
1247
+ event.stopPropagation();
1248
+ return;
1249
+ }
1250
+ if (behavior() === "tab") return;
1251
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
1252
+
1253
+ const forwards = (event.key === "ArrowRight") === (locale().direction !== "rtl");
1254
+ const controls = focusablesIn(element);
1255
+ const active = activeElement(ownerDocument(element));
1256
+ const at = active === element ? -1 : controls.indexOf(active as HTMLElement);
1257
+
1258
+ let target: HTMLElement | null = null;
1259
+ if (forwards) target = controls[at + 1] ?? null;
1260
+ else if (at > 0) target = controls[at - 1] ?? null;
1261
+ else if (at === 0 && focusMode() === "cell") target = element;
1262
+ if (target === null) return;
1263
+
1264
+ event.preventDefault();
1265
+ event.stopPropagation();
1266
+ focusSafely(target);
1267
+ };
1268
+
1269
+ /**
1270
+ * With Tab navigation the keys typed into a control in the cell are the
1271
+ * control's: a text field's arrows move its caret and its letters are not a
1272
+ * typeahead. Tab itself stays inside the cell while there is somewhere in
1273
+ * it to go, and leaves the grid otherwise.
1274
+ */
1275
+ const onKeyDown = (event: KeyboardEvent): void => {
1276
+ if (behavior() !== "tab") return;
1277
+ const element = cellElement();
1278
+ const target = targetElement(event);
1279
+ if (element === null || !contains(element, target)) return;
1280
+
1281
+ if (event.key !== "Tab") {
1282
+ if (target !== element) event.stopPropagation();
1283
+ return;
1284
+ }
1285
+
1286
+ const active = activeElement(ownerDocument(element));
1287
+ if (event.shiftKey) {
1288
+ // Back to the cell, or to an earlier control in it.
1289
+ if (active !== element) event.stopPropagation();
1290
+ return;
1291
+ }
1292
+ const walker = focusableWalker(element, { tabbable: true });
1293
+ if (active !== null && contains(element, active)) walker.currentNode = active;
1294
+ if (walker.nextNode() !== null) event.stopPropagation();
1295
+ };
1296
+
1297
+ return {
1298
+ isFocused: place.isFocused,
1299
+ isPressed: () => false,
1300
+ gridCellProps: mergeProps(place.props, {
1301
+ id: () => cellIdFor(access(options.baseId), options.row.key, options.column.key),
1302
+ role: () => (isRowHeader() ? "rowheader" : "gridcell"),
1303
+ "aria-colindex": () => state.collection().columnIndexOf(options.column.key) + 1,
1304
+ onKeyDownCapture,
1305
+ onKeyDown,
1306
+ }),
1307
+ };
1308
+ }
1309
+
1310
+ // ---------------------------------------------------------------------------
1311
+ // Components
1312
+ // ---------------------------------------------------------------------------
1313
+
1314
+ interface TableContextValue {
1315
+ state: TableState<unknown, unknown>;
1316
+ baseId: Accessor<string>;
1317
+ onAction: Accessor<((key: Key) => void) | undefined>;
1318
+ /** Set when the table is inside a `<Virtualizer>`. */
1319
+ virtual: VirtualizerValue | null;
1320
+ /** Where a `<TableFooter>` hands over its rows. */
1321
+ setFooterItems?: (items: Accessor<Iterable<unknown> | undefined>) => void;
1322
+ /** The table's drag and drop, when it was given `dragAndDropHooks`. */
1323
+ dragAndDrop?: CollectionDragAndDrop | undefined;
1324
+ /**
1325
+ * Whether the table was given drag hooks, for a caller deciding whether to
1326
+ * render a column for the `<DragButton>`. True while disabled too: the
1327
+ * column stays, and its buttons say they are disabled.
1328
+ */
1329
+ allowsDragging: Accessor<boolean>;
1330
+ }
1331
+
1332
+ const TableContext = createContext<TableContextValue | null>(null);
1333
+ const RowContext = createContext<Node<unknown> | null>(null);
1334
+ const ColumnContext = createContext<Node<unknown> | null>(null);
1335
+ const RowStateContext = createContext<TableRowResult | null>(null);
1336
+
1337
+ export function useTable(): TableContextValue {
1338
+ const value = getContext(TableContext);
1339
+ if (value === null || value === undefined) {
1340
+ throw new Error("This must be rendered inside a Table.");
1341
+ }
1342
+ return value;
1343
+ }
1344
+
1345
+ export function useRow(): Node<unknown> {
1346
+ const node = getContext(RowContext);
1347
+ if (node === null || node === undefined) {
1348
+ throw new Error("A Cell must be rendered inside a Row.");
1349
+ }
1350
+ return node;
1351
+ }
1352
+
1353
+ export function useColumn(): Node<unknown> {
1354
+ const node = getContext(ColumnContext);
1355
+ if (node === null || node === undefined) {
1356
+ throw new Error("This must be rendered inside a column callback.");
1357
+ }
1358
+ return node;
1359
+ }
1360
+
1361
+ function TableProvider(props: { value: TableContextValue; children?: Child }) {
1362
+ return provide(
1363
+ TableContext,
1364
+ () => props.value,
1365
+ () => props.children as unknown,
1366
+ );
1367
+ }
1368
+
1369
+ export interface TableComponentProps<R, C> extends StyleProps {
1370
+ /** The columns, left to right. */
1371
+ columns: Iterable<C>;
1372
+ /** The rows, top to bottom. */
1373
+ items: Iterable<R>;
1374
+ children?: Child;
1375
+ rowAccessors?: ItemAccessors<R>;
1376
+ columnAccessors?: ItemAccessors<C>;
1377
+ /** @default "none" */
1378
+ selectionMode?: SelectionMode;
1379
+ selectedKeys?: "all" | Iterable<Key>;
1380
+ defaultSelectedKeys?: "all" | Iterable<Key>;
1381
+ disabledKeys?: Iterable<Key>;
1382
+ disallowEmptySelection?: boolean;
1383
+ sortDescriptor?: SortDescriptor;
1384
+ /** See {@link TableKeyboardNavigationBehavior}. @default "arrow" */
1385
+ keyboardNavigationBehavior?: TableKeyboardNavigationBehavior;
1386
+ /** The column whose cells expand their row. See {@link TableStateOptions.treeColumn}. */
1387
+ treeColumn?: Key;
1388
+ expandedKeys?: Iterable<Key>;
1389
+ defaultExpandedKeys?: Iterable<Key>;
1390
+ "aria-label"?: string;
1391
+ "aria-labelledby"?: string;
1392
+ ref?: RefTarget<HTMLDivElement>;
1393
+ onSelectionChange?: (keys: "all" | Set<Key>) => void;
1394
+ onSortChange?: (descriptor: SortDescriptor) => void;
1395
+ onAction?: (key: Key) => void;
1396
+ onExpandedChange?: (keys: Set<Key>) => void;
1397
+ /**
1398
+ * Drag and drop, from `dragAndDrop()`. A draggable row needs a cell holding
1399
+ * a `<DragButton>` for keyboard and screen reader users to drag it with.
1400
+ */
1401
+ dragAndDropHooks?: DragAndDropHooks;
1402
+ }
1403
+
1404
+ /**
1405
+ * ```tsx
1406
+ * <Table aria-label="Files" columns={COLUMNS} items={files()}
1407
+ * sortDescriptor={sort()} onSortChange={sort.set}>
1408
+ * <TableHeader>{(column) => <Column>{column.name}</Column>}</TableHeader>
1409
+ * <TableBody>
1410
+ * {(file) => <Row>{(column) => <Cell>{file[column.id]}</Cell>}</Row>}
1411
+ * </TableBody>
1412
+ * </Table>
1413
+ * ```
1414
+ */
1415
+ export function Table<R, C>(props: TableComponentProps<R, C>) {
1416
+ const domRef = makeRef<HTMLDivElement>();
1417
+ const options = fromProps(cells(props) as unknown as Incoming<Record<string, unknown>>);
1418
+
1419
+ // Boxed, because the footer hands over an accessor and a signal holding a
1420
+ // function would call it. `ownedWrite`: the footer writes from its body.
1421
+ const [footer, setFooter] = createSignal<{ read: Accessor<Iterable<unknown> | undefined> }>(
1422
+ { read: () => undefined },
1423
+ { ownedWrite: true },
1424
+ );
1425
+
1426
+ const state = tableState<R, C>({
1427
+ ...(options as unknown as TableStateOptions<R, C>),
1428
+ footerItems: () => footer().read() as Iterable<R> | undefined,
1429
+ onSelectionChange: (keys: SelectionValue) => props.onSelectionChange?.(keys),
1430
+ onSortChange: (descriptor) => props.onSortChange?.(descriptor),
1431
+ onExpandedChange: (keys) => props.onExpandedChange?.(keys),
1432
+ });
1433
+
1434
+ // Inside a `<Virtualizer>` the table renders a WINDOW of its rows, and the
1435
+ // layout — not the DOM — answers what is above, below and a page away. Only
1436
+ // the BODY is windowed: the header is one row and always on screen.
1437
+ const virtual = useVirtualizer();
1438
+ const dropping: { held?: CollectionDragAndDrop } = {};
1439
+ virtual?.attach(
1440
+ () => rowsOnly(state.collection()),
1441
+ domRef,
1442
+ () => state.selectionManager().focusedKey,
1443
+ () => dropping.held?.persistedKeys() ?? [],
1444
+ );
1445
+
1446
+ const { gridProps, baseId } = table(
1447
+ {
1448
+ ...(options as unknown as TableOptions),
1449
+ ref: domRef,
1450
+ isVirtualized: () => virtual !== null,
1451
+ layoutDelegate: virtual?.layout,
1452
+ },
1453
+ state,
1454
+ );
1455
+
1456
+ const dragAndDrop = tableDragAndDrop(props.dragAndDropHooks, state, domRef, virtual);
1457
+ dropping.held = dragAndDrop;
1458
+ const hasDragHooks = (): boolean => dragAndDrop?.dragState !== undefined;
1459
+ const allowsDragging = (): boolean =>
1460
+ hasDragHooks() && dragAndDrop?.dragState?.isDisabled() !== true;
1461
+
1462
+ const value: TableContextValue = {
1463
+ state,
1464
+ baseId,
1465
+ onAction: () => props.onAction,
1466
+ virtual,
1467
+ setFooterItems: (items) => setFooter({ read: items }),
1468
+ dragAndDrop,
1469
+ allowsDragging: hasDragHooks,
1470
+ };
1471
+
1472
+ const { focusProps, isFocused, isFocusVisible } = focusRing();
1473
+
1474
+ const elementProps = mergeProps(
1475
+ gridProps,
1476
+ dragAndDrop?.collectionProps,
1477
+ focusProps,
1478
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1479
+ styleProps(cells(props)),
1480
+ {
1481
+ "data-empty": () => state.collection().size === 0,
1482
+ "data-focused": isFocused,
1483
+ "data-focus-visible": isFocusVisible,
1484
+ "data-virtualized": () => virtual !== null,
1485
+ "data-drop-target": () => dragAndDrop?.isRootDropTarget() === true,
1486
+ "data-allows-dragging": allowsDragging,
1487
+ "data-testid": () => props["data-testid"],
1488
+ style: () => (virtual === null ? props.style : contentStyle(virtual.contentSize())),
1489
+ },
1490
+ );
1491
+
1492
+ return (
1493
+ <TableProvider value={value}>
1494
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref)}>
1495
+ <SharedElementTransition>{props.children}</SharedElementTransition>
1496
+ </div>
1497
+ {dragAndDrop?.preview}
1498
+ </TableProvider>
1499
+ );
1500
+ }
1501
+
1502
+ /**
1503
+ * The body's rows, as the collection drag and drop works over.
1504
+ *
1505
+ * Neither the footer's rows nor the column headers are places to drop, and a
1506
+ * cell answers as itself so that a focused cell can be read as its row.
1507
+ */
1508
+ class TableBodyRows<R, C> implements Collection<R> {
1509
+ #table: TableCollection<R, C>;
1510
+
1511
+ constructor(rows: TableCollection<R, C>) {
1512
+ this.#table = rows;
1513
+ }
1514
+
1515
+ #inBody(key: Key | undefined): boolean {
1516
+ if (key === undefined) return false;
1517
+ const at = this.#table.rowIndexOf(key);
1518
+ return at >= 0 && at < this.#table.footerStart;
1519
+ }
1520
+
1521
+ get size(): number {
1522
+ return this.#table.footerStart;
1523
+ }
1524
+
1525
+ *[Symbol.iterator](): IterableIterator<Node<R>> {
1526
+ yield* this.#table.bodyRows;
1527
+ }
1528
+
1529
+ *getKeys(): IterableIterator<Key> {
1530
+ for (const row of this.#table.bodyRows) yield row.key;
1531
+ }
1532
+
1533
+ getItem(key: Key): Node<R> | null {
1534
+ if (this.#inBody(key)) return this.#table.getItem(key);
1535
+ const cell = this.#table.parseCellKey(key);
1536
+ return cell !== null && this.#inBody(cell.row.key) ? this.#table.getItem(key) : null;
1537
+ }
1538
+
1539
+ getKeyBefore(key: Key): Key | null {
1540
+ return this.#inBody(key) ? this.#table.getKeyBefore(key) : null;
1541
+ }
1542
+
1543
+ getKeyAfter(key: Key): Key | null {
1544
+ if (!this.#inBody(key)) return null;
1545
+ const next = this.#table.getKeyAfter(key);
1546
+ return next !== null && this.#inBody(next) ? next : null;
1547
+ }
1548
+
1549
+ getFirstKey(): Key | null {
1550
+ return this.#table.bodyRows[0]?.key ?? null;
1551
+ }
1552
+
1553
+ getLastKey(): Key | null {
1554
+ return this.#table.bodyRows.at(-1)?.key ?? null;
1555
+ }
1556
+
1557
+ getChildren(key: Key): Iterable<Node<R>> {
1558
+ return this.getItem(key)?.childNodes ?? [];
1559
+ }
1560
+
1561
+ at(index: number): Node<R> | null {
1562
+ return index < this.#table.footerStart ? (this.#table.rows[index] ?? null) : null;
1563
+ }
1564
+ }
1565
+
1566
+ const EXPAND_KEYS = { ltr: "ArrowRight", rtl: "ArrowLeft" } as const;
1567
+ const COLLAPSE_KEYS = { ltr: "ArrowLeft", rtl: "ArrowRight" } as const;
1568
+
1569
+ /**
1570
+ * The table's drag and drop: over the body's rows, with a tree's reading of
1571
+ * the pointer for rows that nest, and focus after a drop given to a cell.
1572
+ */
1573
+ function tableDragAndDrop(
1574
+ hooks: DragAndDropHooks | undefined,
1575
+ state: TableState<unknown, unknown>,
1576
+ domRef: Accessor<HTMLDivElement | null>,
1577
+ virtual: VirtualizerValue | null,
1578
+ ): CollectionDragAndDrop | undefined {
1579
+ if (hooks === undefined) return undefined;
1580
+ const layoutDelegate = virtual?.layout;
1581
+ const locale = useLocale();
1582
+ const direction = (): "ltr" | "rtl" => locale().direction;
1583
+ const body = createMemo(
1584
+ () => new TableBodyRows(state.collection()) as unknown as Collection<unknown>,
1585
+ );
1586
+ const expandedKeys = (): Set<Key> => state.expandedKeys?.() ?? new Set<Key>();
1587
+ const hasChildren = (key: Key): boolean => {
1588
+ const node = body().getItem(key);
1589
+ return node !== null && node.type === "item" && node.hasChildNodes;
1590
+ };
1591
+
1592
+ // Rows do not take focus here, cells do: a row is focused as its cell in
1593
+ // the column focus was last in, or else its first.
1594
+ const focusKeyFor = (rowKey: Key): Key => {
1595
+ const collection = state.collection();
1596
+ const focused = state.selectionManager().focusedKey;
1597
+ const cell = focused === null ? null : collection.parseCellKey(focused);
1598
+ const column = cell?.column.key ?? collection.columns[0]?.key;
1599
+ return column === undefined ? rowKey : cellKeyFor(rowKey, column);
1600
+ };
1601
+
1602
+ const result: CollectionDragAndDrop = collectionDragAndDrop({
1603
+ virtual,
1604
+ hooks,
1605
+ collection: body,
1606
+ selectionManager: state.selectionManager,
1607
+ ref: domRef,
1608
+ // A position next to a disabled row is still a place to drop.
1609
+ keyboardDelegate: new ListKeyboardDelegate({
1610
+ collection: body,
1611
+ ref: domRef,
1612
+ disabledBehavior: () => "selection",
1613
+ direction,
1614
+ layoutDelegate,
1615
+ }),
1616
+ direction,
1617
+ dropTargetDelegate: (base) =>
1618
+ new TreeDropTargetDelegate(base, { collection: body, expandedKeys }, direction),
1619
+ // Held over a collapsed row, the drag opens it; a screen reader user may
1620
+ // close it again the same way.
1621
+ onDropActivate: (event: DroppableCollectionActivateEvent) => {
1622
+ if (event.target.type !== "item" || state.toggleKey === undefined) return;
1623
+ const key = event.target.key;
1624
+ const expanded = expandedKeys().has(key);
1625
+ if (hasChildren(key) && (!expanded || hooks.isVirtualDragging?.() === true)) {
1626
+ state.toggleKey(key);
1627
+ }
1628
+ },
1629
+ onKeyDown: (event: KeyboardEvent) => {
1630
+ const target = result.dropState?.target() ?? null;
1631
+ if (target?.type !== "item" || target.dropPosition !== "on") return;
1632
+ if (!hasChildren(target.key) || state.toggleKey === undefined) return;
1633
+ const expanded = expandedKeys().has(target.key);
1634
+ if (event.key === EXPAND_KEYS[direction()] && !expanded) state.toggleKey(target.key);
1635
+ else if (event.key === COLLAPSE_KEYS[direction()] && expanded) state.toggleKey(target.key);
1636
+ },
1637
+ focusKeyFor,
1638
+ });
1639
+
1640
+ if (result.dropState !== undefined) {
1641
+ provideDropIndicator({ render: (props) => <TableDropIndicator of={props} /> });
1642
+ }
1643
+ return result;
1644
+ }
1645
+
1646
+ /** A drop indicator in a table: a row whose one cell spans every column. */
1647
+ function TableDropIndicator(indicator: { of: Incoming<DropIndicatorProps> }) {
1648
+ const props = indicator.of;
1649
+ const grid = useTable();
1650
+ const { dragAndDropHooks, dropState } = useDragAndDropContext();
1651
+ if (dragAndDropHooks?.dropIndicator === undefined || dropState === undefined) {
1652
+ throw new Error("A DropIndicator must be rendered inside a droppable Table.");
1653
+ }
1654
+
1655
+ const target = props.target();
1656
+ const buttonRef = makeRef<HTMLDivElement>();
1657
+ const virtual = useVirtualizer();
1658
+ const { visuallyHiddenProps } = visuallyHidden();
1659
+ const { dropIndicatorProps, isDropTarget, isHidden } = dragAndDropHooks.dropIndicator(
1660
+ { target },
1661
+ dropState,
1662
+ buttonRef,
1663
+ );
1664
+ const level = (): number =>
1665
+ target.type === "item" ? (dropState.collection().getItem(target.key)?.level ?? 0) + 1 : 1;
1666
+ const isTree = (): boolean => grid.state.collection().isTree;
1667
+
1668
+ return (
1669
+ <Show when={!isHidden()}>
1670
+ <div
1671
+ class={props.class?.() ?? props.className?.()}
1672
+ style={{
1673
+ "--table-row-level": String(level() + 1),
1674
+ ...props.style?.(),
1675
+ ...(target.type === "item" ? dropIndicatorStyle(virtual, target) : undefined),
1676
+ }}
1677
+ role="row"
1678
+ aria-level={isTree() ? level() : undefined}
1679
+ data-slot={props["data-slot"]?.() ?? "drop-indicator"}
1680
+ data-drop-target={isDropTarget()}
1681
+ >
1682
+ <div
1683
+ role="gridcell"
1684
+ aria-colspan={grid.state.collection().columns.length}
1685
+ style={{ "grid-column": "1 / -1", padding: "0" }}
1686
+ >
1687
+ <div {...visuallyHiddenProps} role="button" {...dropIndicatorProps} ref={buttonRef.set} />
1688
+ {props.children?.()}
1689
+ </div>
1690
+ </div>
1691
+ </Show>
1692
+ );
1693
+ }
1694
+
1695
+ /** The target for a drop on the whole table, there for keyboard and screen reader drags. */
1696
+ function TableRootDropIndicator() {
1697
+ const grid = useTable();
1698
+ const { dragAndDropHooks, dropState } = useDragAndDropContext();
1699
+ if (dragAndDropHooks?.dropIndicator === undefined || dropState === undefined) return null;
1700
+
1701
+ const buttonRef = makeRef<HTMLDivElement>();
1702
+ const { visuallyHiddenProps } = visuallyHidden();
1703
+ const { dropIndicatorProps, isDropTarget } = dragAndDropHooks.dropIndicator(
1704
+ { target: { type: "root" } },
1705
+ dropState,
1706
+ buttonRef,
1707
+ );
1708
+ const ariaHidden = dropIndicatorProps["aria-hidden"] as Accessor<string | undefined>;
1709
+
1710
+ return (
1711
+ <Show when={isDropTarget() || ariaHidden() === undefined}>
1712
+ <div
1713
+ role="row"
1714
+ aria-hidden={ariaHidden() === "true" ? true : undefined}
1715
+ style={{ height: "0" }}
1716
+ >
1717
+ <div
1718
+ role="gridcell"
1719
+ aria-colspan={grid.state.collection().columns.length}
1720
+ style={{ "grid-column": "1 / -1", padding: "0" }}
1721
+ >
1722
+ <div {...visuallyHiddenProps} role="button" {...dropIndicatorProps} ref={buttonRef.set} />
1723
+ </div>
1724
+ </div>
1725
+ </Show>
1726
+ );
1727
+ }
1728
+
1729
+ export interface TableHeaderComponentProps<C> extends StyleProps {
1730
+ /** How one column header renders. Return a `<Column>`. */
1731
+ children: (column: C) => Child;
1732
+ }
1733
+
1734
+ /** The header row group, holding one row of column headers. */
1735
+ export function TableHeader<C>(props: TableHeaderComponentProps<C>) {
1736
+ const grid = useTable();
1737
+ const render = props.children;
1738
+
1739
+ const elementProps = mergeProps(
1740
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1741
+ styleProps(cells(props)),
1742
+ {
1743
+ role: "rowgroup",
1744
+ "data-testid": () => props["data-testid"],
1745
+ },
1746
+ );
1747
+
1748
+ return (
1749
+ <div {...elementProps}>
1750
+ <div role="row" aria-rowindex={1}>
1751
+ <For each={() => grid.state.collection().columns}>
1752
+ {(column: Node<unknown>) => {
1753
+ const rowOwner = getOwner();
1754
+ if (rowOwner !== null) install(rowOwner, ColumnContext, () => column);
1755
+ return render(column.value as C);
1756
+ }}
1757
+ </For>
1758
+ </div>
1759
+ </div>
1760
+ );
1761
+ }
1762
+
1763
+ export interface ColumnComponentProps extends StyleProps {
1764
+ children?: Child;
1765
+ ref?: RefTarget<HTMLDivElement>;
1766
+ }
1767
+
1768
+ /** One column header. Sortable when its column says so. */
1769
+ export function Column(props: ColumnComponentProps) {
1770
+ const domRef = makeRef<HTMLDivElement>();
1771
+ const grid = useTable();
1772
+ const column = useColumn();
1773
+
1774
+ const { columnHeaderProps, isFocused, isPressed, allowsSorting, sortDirection } =
1775
+ tableColumnHeader({ column, ref: domRef, baseId: grid.baseId }, grid.state);
1776
+
1777
+ const { hoverProps, isHovered } = hover({});
1778
+ const { focusProps, isFocusVisible } = focusRing();
1779
+
1780
+ const elementProps = mergeProps(
1781
+ columnHeaderProps,
1782
+ hoverProps,
1783
+ focusProps,
1784
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1785
+ styleProps(cells(props)),
1786
+ {
1787
+ "data-sortable": allowsSorting,
1788
+ "data-allows-sorting": allowsSorting,
1789
+ "data-sort-direction": sortDirection,
1790
+ "data-focused": isFocused,
1791
+ "data-focus-visible": isFocusVisible,
1792
+ "data-pressed": isPressed,
1793
+ "data-hovered": isHovered,
1794
+ "data-testid": () => props["data-testid"],
1795
+ },
1796
+ );
1797
+
1798
+ return (
1799
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref)}>
1800
+ {props.children}
1801
+ </div>
1802
+ );
1803
+ }
1804
+
1805
+ export interface TableBodyComponentProps<R> extends StyleProps {
1806
+ /** How one row renders. Return a `<Row>`. */
1807
+ children: (item: R) => Child;
1808
+ /** Shown when there are no rows. */
1809
+ renderEmpty?: Child;
1810
+ }
1811
+
1812
+ /** Rows of one part of the table, or the window of them the virtualiser says is on screen. */
1813
+ function rowsOf(grid: TableContextValue, part: "body" | "footer"): Node<unknown>[] {
1814
+ const collection = grid.state.collection();
1815
+ const inPart = (row: Node<unknown>): boolean =>
1816
+ collection.rowIndexOf(row.key) < collection.footerStart === (part === "body");
1817
+ const virtual = grid.virtual;
1818
+ if (virtual === null) return part === "body" ? collection.bodyRows : collection.footerRows;
1819
+ return virtual
1820
+ .visible()
1821
+ .map((info: LayoutInfo) => collection.getItem(info.key))
1822
+ .filter((row: Node<unknown> | null): row is Node<unknown> => row !== null && inPart(row));
1823
+ }
1824
+
1825
+ function renderRows(rows: () => Node<unknown>[], render: (item: never) => Child) {
1826
+ return (
1827
+ <For each={rows()}>
1828
+ {(row: Node<unknown>) => {
1829
+ const rowOwner = getOwner();
1830
+ if (rowOwner !== null) install(rowOwner, RowContext, () => row);
1831
+ return render(row.value as never);
1832
+ }}
1833
+ </For>
1834
+ );
1835
+ }
1836
+
1837
+ /**
1838
+ * The body row group.
1839
+ *
1840
+ * With no rows, `renderEmpty` is shown in one cell spanning every column,
1841
+ * inside a row: a grid's children are rows and a row's are cells, and a
1842
+ * message set loose in the row group is content a screen reader skips.
1843
+ */
1844
+ export function TableBody<R>(props: TableBodyComponentProps<R>) {
1845
+ const grid = useTable();
1846
+ const render = props.children;
1847
+ const isEmpty = (): boolean => grid.state.collection().bodyRows.length === 0;
1848
+
1849
+ const droppable = grid.dragAndDrop?.dropState !== undefined;
1850
+
1851
+ const elementProps = mergeProps(
1852
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1853
+ styleProps(cells(props)),
1854
+ {
1855
+ role: "rowgroup",
1856
+ "data-empty": isEmpty,
1857
+ "data-drop-target": () => grid.dragAndDrop?.isRootDropTarget() === true,
1858
+ "data-testid": () => props["data-testid"],
1859
+ },
1860
+ );
1861
+
1862
+ return (
1863
+ <div {...elementProps}>
1864
+ {droppable ? <TableRootDropIndicator /> : null}
1865
+ {renderRows(() => rowsOf(grid, "body"), render)}
1866
+ <Show when={isEmpty() && props.renderEmpty !== undefined}>
1867
+ <div role="row" aria-rowindex={grid.virtual === null ? undefined : 2}>
1868
+ <div
1869
+ role="gridcell"
1870
+ aria-colindex={1}
1871
+ aria-colspan={grid.state.collection().columns.length}
1872
+ style={{ "grid-column": "1 / -1" }}
1873
+ >
1874
+ {props.renderEmpty}
1875
+ </div>
1876
+ </div>
1877
+ </Show>
1878
+ </div>
1879
+ );
1880
+ }
1881
+
1882
+ export interface TableFooterComponentProps<R> extends StyleProps {
1883
+ /** The footer's rows: a total, a summary. */
1884
+ items: Iterable<R>;
1885
+ /** How one row renders. Return a `<Row>`. */
1886
+ children: (item: R) => Child;
1887
+ }
1888
+
1889
+ /**
1890
+ * The footer row group, after the body.
1891
+ *
1892
+ * Its rows are rows of the table like any other: the arrows move into them
1893
+ * from the last row of the body, so a total is read with its column header.
1894
+ *
1895
+ * ```tsx
1896
+ * <TableFooter items={[{ id: "total", name: "Total", size: "52 KB" }]}>
1897
+ * {(total) => <Row>{(column) => <Cell>{total[column.id]}</Cell>}</Row>}
1898
+ * </TableFooter>
1899
+ * ```
1900
+ */
1901
+ export function TableFooter<R>(props: TableFooterComponentProps<R>) {
1902
+ const grid = useTable();
1903
+ const render = props.children;
1904
+ grid.setFooterItems?.(() => props.items);
1905
+
1906
+ const elementProps = mergeProps(
1907
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1908
+ styleProps(cells(props)),
1909
+ {
1910
+ role: "rowgroup",
1911
+ "data-testid": () => props["data-testid"],
1912
+ },
1913
+ );
1914
+
1915
+ return <div {...elementProps}>{renderRows(() => rowsOf(grid, "footer"), render)}</div>;
1916
+ }
1917
+
1918
+ export interface RowComponentProps<C> extends StyleProps {
1919
+ /** How one cell of this row renders. Return a `<Cell>`. */
1920
+ children: (column: C) => Child;
1921
+ ref?: RefTarget<HTMLDivElement>;
1922
+ }
1923
+
1924
+ /**
1925
+ * Just the body rows, as a collection a layout can walk.
1926
+ *
1927
+ * A table's collection holds columns and rows together, and only the rows are
1928
+ * windowed: the header is one row and is always on screen.
1929
+ */
1930
+ function rowsOnly(collection: TableCollection<unknown, unknown>): Collection<unknown> {
1931
+ return new ListCollection(collection.rows);
1932
+ }
1933
+
1934
+ /** One row, holding a cell per column. */
1935
+ export function Row<C>(props: RowComponentProps<C>) {
1936
+ const domRef = makeRef<HTMLDivElement>();
1937
+ const grid = useTable();
1938
+ const row = useRow();
1939
+ const dnd = rowDragAndDrop(grid, row.key);
1940
+
1941
+ measureRow(grid.virtual, row.key, domRef);
1942
+
1943
+ const rowState = tableRow(
1944
+ {
1945
+ row,
1946
+ ref: domRef,
1947
+ baseId: grid.baseId,
1948
+ isVirtualized: () => grid.virtual !== null,
1949
+ hasAction: () => grid.onAction() !== undefined,
1950
+ onAction: (key) => grid.onAction()?.(key),
1951
+ // Selecting on release lets a press that becomes a drag leave the
1952
+ // selection alone, unless only the drag button starts a drag.
1953
+ shouldSelectOnPressUp: () =>
1954
+ dnd?.collection.dragState !== undefined &&
1955
+ dnd.collection.hooks?.pointerDragSource !== "handle",
1956
+ },
1957
+ grid.state,
1958
+ );
1959
+ const { rowProps, isSelected, isDisabled, isPressed, isExpanded, hasChildRows } = rowState;
1960
+
1961
+ const { hoverProps, isHovered } = hover({ isDisabled });
1962
+ const { focusProps: withinProps, isFocusVisible: isFocusVisibleWithin } = focusRing({
1963
+ within: true,
1964
+ });
1965
+
1966
+ const elementProps = mergeProps(
1967
+ rowProps,
1968
+ hoverProps,
1969
+ withinProps,
1970
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1971
+ styleProps(cells(props)),
1972
+ {
1973
+ "data-selected": isSelected,
1974
+ "data-pressed": isPressed,
1975
+ "data-hovered": isHovered,
1976
+ "data-disabled": isDisabled,
1977
+ "data-focus-visible-within": isFocusVisibleWithin,
1978
+ "data-selection-mode": () => {
1979
+ const mode = grid.state.selectionManager().selectionMode;
1980
+ return mode === "none" ? undefined : mode;
1981
+ },
1982
+ "data-expanded": isExpanded,
1983
+ "data-has-child-items": hasChildRows,
1984
+ "data-level": () => (grid.state.collection().isTree ? row.level + 1 : undefined),
1985
+ "data-dragging": () => dnd?.collection.dragState?.isDragging(row.key) === true,
1986
+ "data-drop-target": () => dnd?.on?.indicator.isDropTarget() === true,
1987
+ "data-testid": () => props["data-testid"],
1988
+ // Positioned by the LAYOUT: the rows above it are not rendered, so
1989
+ // document flow has nothing to place it against.
1990
+ style: () => {
1991
+ const virtual = grid.virtual;
1992
+ if (virtual === null) return props.style;
1993
+ const info = virtual.layout.getLayoutInfo(row.key);
1994
+ return info === null ? props.style : rowStyle(info);
1995
+ },
1996
+ },
1997
+ );
1998
+
1999
+ const render = props.children;
2000
+
2001
+ const element = (
2002
+ <div {...mergeProps(elementProps, dnd?.itemProps)} ref={mergeRefs(domRef.set, props.ref)}>
2003
+ {provide(
2004
+ RowStateContext,
2005
+ () => rowState,
2006
+ () => (
2007
+ <SelectionIndicatorProvider isSelected={isSelected()}>
2008
+ <For each={() => grid.state.collection().columns}>
2009
+ {(column: Node<unknown>) => {
2010
+ const cellOwner = getOwner();
2011
+ if (cellOwner !== null) install(cellOwner, ColumnContext, () => column);
2012
+ return render(column.value as C);
2013
+ }}
2014
+ </For>
2015
+ </SelectionIndicatorProvider>
2016
+ ),
2017
+ )}
2018
+ </div>
2019
+ );
2020
+ if (dnd === null) return element;
2021
+
2022
+ const { visuallyHiddenProps } = visuallyHidden();
2023
+ const on = dnd.on;
2024
+
2025
+ return (
2026
+ <>
2027
+ <Show when={dnd.collection.shouldRenderIndicator(dnd.before)}>
2028
+ {dnd.collection.renderDropIndicator(dnd.before)}
2029
+ </Show>
2030
+ {on === null ? null : (
2031
+ <Show when={!on.indicator.isHidden()}>
2032
+ <div role="row" style={{ height: "0" }}>
2033
+ <div
2034
+ role="gridcell"
2035
+ aria-colspan={grid.state.collection().columns.length}
2036
+ style={{ "grid-column": "1 / -1", padding: "0" }}
2037
+ >
2038
+ <div
2039
+ role="button"
2040
+ {...visuallyHiddenProps}
2041
+ {...on.indicator.dropIndicatorProps}
2042
+ ref={on.ref.set}
2043
+ />
2044
+ </div>
2045
+ </div>
2046
+ </Show>
2047
+ )}
2048
+ {element}
2049
+ <For each={dnd.after()}>
2050
+ {(target: ItemDropTarget) => (
2051
+ <Show when={dnd.collection.shouldRenderIndicator(target)}>
2052
+ {dnd.collection.renderDropIndicator(target)}
2053
+ </Show>
2054
+ )}
2055
+ </For>
2056
+ </>
2057
+ );
2058
+ }
2059
+
2060
+ interface RowDragAndDrop {
2061
+ collection: CollectionDragAndDrop;
2062
+ itemProps: DOMProps;
2063
+ before: ItemDropTarget;
2064
+ after: Accessor<ItemDropTarget[]>;
2065
+ /** The target for a drop ON the row: rows here take no focus, so it is a row of its own. */
2066
+ on: {
2067
+ indicator: ReturnType<NonNullable<DragAndDropHooks["dropIndicator"]>>;
2068
+ ref: ReturnType<typeof makeRef<HTMLDivElement>>;
2069
+ } | null;
2070
+ }
2071
+
2072
+ /**
2073
+ * A body row's part in its table's drag and drop. Focus is on cells, so a
2074
+ * keyboard drag starts from a `<DragButton>` in one of them; a footer row
2075
+ * takes no part.
2076
+ */
2077
+ function rowDragAndDrop(grid: TableContextValue, key: Key): RowDragAndDrop | null {
2078
+ const collection = grid.dragAndDrop;
2079
+ if (collection === undefined) return null;
2080
+ const everyRow = grid.state.collection();
2081
+ if (everyRow.rowIndexOf(key) >= everyRow.footerStart) return null;
2082
+ const { hooks, dragState, dropState } = collection;
2083
+
2084
+ const draggable =
2085
+ dragState === undefined || hooks?.draggableItem === undefined
2086
+ ? null
2087
+ : hooks.draggableItem({ key, hasDragButton: true }, dragState);
2088
+ const dragButtonRef = makeRef<Element>();
2089
+ const slot = draggableItemSlotProps(draggable, hooks, dragButtonRef, dragButtonRef.set);
2090
+ if (draggable !== null) provideDragButton(slot.dragButton);
2091
+
2092
+ let on: RowDragAndDrop["on"] = null;
2093
+ if (dropState !== undefined && hooks?.dropIndicator !== undefined) {
2094
+ const ref = makeRef<HTMLDivElement>();
2095
+ on = {
2096
+ ref,
2097
+ indicator: hooks.dropIndicator(
2098
+ { target: { type: "item", key, dropPosition: "on" } },
2099
+ dropState,
2100
+ ref,
2101
+ ),
2102
+ };
2103
+ }
2104
+
2105
+ const after = createMemo(() => {
2106
+ const rows = dropState?.collection() ?? dragState?.collection();
2107
+ const node = rows?.getItem(key) ?? null;
2108
+ return rows === undefined || node === null ? [] : afterDropIndicatorTargets(rows, node);
2109
+ });
2110
+
2111
+ return {
2112
+ collection,
2113
+ on,
2114
+ before: { type: "item", key, dropPosition: "before" },
2115
+ after,
2116
+ itemProps: slot.itemProps,
2117
+ };
2118
+ }
2119
+
2120
+ export interface TableExpandButtonProps extends StyleProps {
2121
+ children?: Child;
2122
+ ref?: RefTarget<HTMLButtonElement>;
2123
+ }
2124
+
2125
+ /**
2126
+ * The control that expands and collapses the enclosing row, for the cell of
2127
+ * the tree column. Named "Expand" or "Collapse" in the reader's language,
2128
+ * followed by the row's own name.
2129
+ *
2130
+ * It is for a pointer: from the keyboard the arrows expand and collapse while
2131
+ * the tree column's cell is focused, so the button stays out of the Tab order
2132
+ * and does not take focus when pressed.
2133
+ */
2134
+ export function TableExpandButton(props: TableExpandButtonProps) {
2135
+ const domRef = makeRef<HTMLButtonElement>();
2136
+ const rowState = getContext(RowStateContext);
2137
+ if (rowState === null || rowState === undefined) {
2138
+ throw new Error("A TableExpandButton must be rendered inside a Row.");
2139
+ }
2140
+ const { buttonProps, isPressed } = button(rowState.expandButtonProps, domRef);
2141
+ const { hoverProps, isHovered } = hover({});
2142
+
2143
+ const elementProps = mergeProps(
2144
+ buttonProps,
2145
+ {
2146
+ id: rowState.expandButtonProps.id,
2147
+ [PREVENT_FOCUS_ATTRIBUTE]: true,
2148
+ "aria-labelledby": rowState.expandButtonProps["aria-labelledby"],
2149
+ },
2150
+ hoverProps,
2151
+ filterDOMProps(fromProps(cells(props)), { global: true }),
2152
+ styleProps(cells(props)),
2153
+ {
2154
+ type: "button",
2155
+ "data-expanded": rowState.isExpanded,
2156
+ "data-pressed": isPressed,
2157
+ "data-hovered": isHovered,
2158
+ "data-disabled": rowState.isDisabled,
2159
+ "data-testid": () => props["data-testid"],
2160
+ },
2161
+ );
2162
+
2163
+ return (
2164
+ <button {...elementProps} ref={mergeRefs(domRef.set, props.ref)}>
2165
+ {props.children}
2166
+ </button>
2167
+ );
2168
+ }
2169
+
2170
+ export interface CellComponentProps extends StyleProps {
2171
+ children?: Child;
2172
+ ref?: RefTarget<HTMLDivElement>;
2173
+ }
2174
+
2175
+ /** One cell. `rowheader` when its column is the one that identifies the row. */
2176
+ export function Cell(props: CellComponentProps) {
2177
+ const domRef = makeRef<HTMLDivElement>();
2178
+ const grid = useTable();
2179
+ const row = useRow();
2180
+ const column = useColumn();
2181
+
2182
+ const { gridCellProps, isFocused } = tableCell(
2183
+ { row, column, ref: domRef, baseId: grid.baseId },
2184
+ grid.state,
2185
+ );
2186
+
2187
+ const { focusProps, isFocusVisible } = focusRing();
2188
+ const { hoverProps, isHovered } = hover({});
2189
+ const rowState = getContext(RowStateContext) ?? null;
2190
+ const isTreeColumn = (): boolean => grid.state.treeColumn?.() === column.key;
2191
+
2192
+ const elementProps = mergeProps(
2193
+ gridCellProps,
2194
+ focusProps,
2195
+ hoverProps,
2196
+ filterDOMProps(fromProps(cells(props)), { global: true }),
2197
+ styleProps(cells(props)),
2198
+ {
2199
+ "data-focused": isFocused,
2200
+ "data-focus-visible": isFocusVisible,
2201
+ "data-hovered": isHovered,
2202
+ "data-selected": () => rowState?.isSelected() === true,
2203
+ "data-disabled": () => rowState?.isDisabled() === true,
2204
+ "data-column-index": () => grid.state.collection().columnIndexOf(column.key),
2205
+ "data-tree-column": isTreeColumn,
2206
+ "data-expanded": () => isTreeColumn() && rowState?.isExpanded() === true,
2207
+ "data-has-child-items": () => isTreeColumn() && rowState?.hasChildRows() === true,
2208
+ "data-level": () => (grid.state.collection().isTree ? row.level + 1 : undefined),
2209
+ "data-testid": () => props["data-testid"],
2210
+ },
2211
+ );
2212
+
2213
+ return (
2214
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref)}>
2215
+ {props.children}
2216
+ </div>
2217
+ );
2218
+ }