@gemologic/sheen-table 0.2.1 → 0.4.0

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 (71) hide show
  1. package/dist/DataTable.d.ts +58 -10
  2. package/dist/DataTable.js +1294 -1625
  3. package/dist/DataTableToolbar.js +1 -2
  4. package/dist/FilterBar.d.ts +3 -0
  5. package/dist/FilterBar.js +131 -108
  6. package/dist/QueryBuilder.js +72 -68
  7. package/dist/cell-edit.js +1 -2
  8. package/dist/client-state.d.ts +9 -3
  9. package/dist/client-state.js +36 -31
  10. package/dist/client-view.js +12 -13
  11. package/dist/column-layout.js +1 -2
  12. package/dist/columns.d.ts +5 -1
  13. package/dist/columns.js +7 -5
  14. package/dist/constrained-columns.js +1 -2
  15. package/dist/core.d.ts +5 -5
  16. package/dist/core.js +28 -28
  17. package/dist/data-table-features.d.ts +134 -0
  18. package/dist/data-table-features.js +560 -0
  19. package/dist/export.js +1 -2
  20. package/dist/facets.js +5 -7
  21. package/dist/filter-bar-state.js +14 -18
  22. package/dist/filter-client.js +1 -2
  23. package/dist/filter.js +1 -2
  24. package/dist/grouping.js +1 -2
  25. package/dist/index.d.ts +5 -3
  26. package/dist/index.js +32 -31
  27. package/dist/messages.d.ts +4 -1
  28. package/dist/messages.js +5 -3
  29. package/dist/pagination.d.ts +43 -1
  30. package/dist/pagination.js +110 -56
  31. package/dist/query-builder-state.js +1 -2
  32. package/dist/requests.d.ts +3 -3
  33. package/dist/requests.js +39 -30
  34. package/dist/row-hierarchy.js +1 -2
  35. package/dist/row-identity.js +1 -2
  36. package/dist/saved-views.d.ts +17 -14
  37. package/dist/saved-views.js +72 -70
  38. package/dist/search-controller.js +1 -2
  39. package/dist/search.js +1 -2
  40. package/dist/selection-client.js +1 -2
  41. package/dist/selection.d.ts +3 -0
  42. package/dist/selection.js +9 -2
  43. package/dist/server-export.d.ts +16 -7
  44. package/dist/server-export.js +58 -55
  45. package/dist/sorting.js +1 -2
  46. package/dist/table-state-changes.d.ts +6 -3
  47. package/dist/table-state-changes.js +45 -42
  48. package/dist/table-state.d.ts +20 -4
  49. package/dist/table-state.js +67 -42
  50. package/dist/text-normalization.js +1 -2
  51. package/dist/url-state.d.ts +12 -9
  52. package/dist/url-state.js +34 -32
  53. package/package.json +5 -5
  54. package/src/DataTable.tsx +490 -766
  55. package/src/FilterBar.tsx +19 -3
  56. package/src/QueryBuilder.tsx +5 -5
  57. package/src/client-state.ts +31 -17
  58. package/src/columns.ts +9 -3
  59. package/src/core.ts +5 -5
  60. package/src/data-table-features.tsx +592 -0
  61. package/src/index.ts +5 -3
  62. package/src/messages.ts +2 -2
  63. package/src/pagination.ts +83 -14
  64. package/src/requests.ts +22 -8
  65. package/src/saved-views.ts +33 -11
  66. package/src/selection.ts +8 -0
  67. package/src/server-export.ts +17 -11
  68. package/src/styles.css +17 -11
  69. package/src/table-state-changes.ts +22 -12
  70. package/src/table-state.ts +53 -11
  71. package/src/url-state.ts +27 -10
package/src/DataTable.tsx CHANGED
@@ -1,45 +1,42 @@
1
- import { Button, Checkbox, ContextMenu, DropdownMenu, EmptyState, Pagination, SearchInput, Skeleton, Toaster, createToaster, useTheme } from "@gemologic/sheen";
2
- import type { MenuItem, ShortcutAction } from "@gemologic/sheen";
1
+ import { Button, Checkbox, ContextMenu, DropdownMenu, EmptyState, Glyph, Pagination, SearchInput, Skeleton, flashChange, useTheme } from "@gemologic/sheen";
2
+ import type { GlyphName, MenuItem, ShortcutAction } from "@gemologic/sheen";
3
3
  import { createVirtualizer } from "@tanstack/solid-virtual";
4
4
  import type { VirtualItem } from "@tanstack/solid-virtual";
5
- import { For, Index, Show, createEffect, createMemo, createSignal, createUniqueId, on, onCleanup, onMount } from "solid-js";
6
- import type { Accessor, JSX } from "solid-js";
7
- import { changeTableState } from "./table-state-changes.ts";
5
+ import { For, Index, Show, createComputed, createEffect, createMemo, createSignal, createUniqueId, on, onCleanup, onMount, untrack } from "solid-js";
6
+ import type { Accessor, JSX, Signal } from "solid-js";
7
+ import { changeTableStateWith } from "./table-state-changes.ts";
8
+ import type { TableStateChange } from "./table-state-changes.ts";
8
9
  import { canMoveColumn, moveColumn, orderColumnStates, placeColumn } from "./column-layout.ts";
9
10
  import { constrainedColumnValues, summarizedColumns } from "./constrained-columns.ts";
10
11
  import type { ColumnDropPlacement, ColumnMoveDirection } from "./column-layout.ts";
11
12
  import { columnStateSchema, readColumnDefinitions } from "./columns.ts";
12
- import type { ColumnEditor, ColumnValue, SheenColumns } from "./columns.ts";
13
+ import type { ColumnValue, SheenColumns } from "./columns.ts";
13
14
  import { createClientView } from "./client-view.ts";
14
15
  import type { ClientView } from "./client-view.ts";
15
16
  import { formatSearchQuery, parseSearchQuery } from "./search.ts";
16
17
  import type { SearchMode } from "./search.ts";
17
- import { getPageRange, resolvePagination } from "./pagination.ts";
18
- import type { PageResult, TablePagination } from "./pagination.ts";
19
- import { createRowIdentity } from "./row-identity.ts";
20
- import { groupClientRows, normalizeServerGroups } from "./grouping.ts";
21
- import type { ClientRowGroup, ServerRowGroup } from "./grouping.ts";
22
- import { createRowHierarchy } from "./row-hierarchy.ts";
23
- import type { HierarchyRow } from "./row-hierarchy.ts";
18
+ import { getPageRange, parseServerPagination, resetPagination, resolvePagination } from "./pagination.ts";
19
+ import type { CursorPageResult, CursorPagination, CursorPosition, CursorTotal, PageResult, ServerPagination, TablePagination } from "./pagination.ts";
20
+ import type { ServerRowGroup } from "./grouping.ts";
24
21
  import { createTableRequests } from "./requests.ts";
25
- import type { TableRequestOutcome, TableRequestSnapshot } from "./requests.ts";
22
+ import type { TableRequestOutcome } from "./requests.ts";
26
23
  import { createTableSelection } from "./selection.ts";
27
24
  import type { BulkSelection } from "./selection.ts";
28
- import { parseTableState, serializeState } from "./table-state.ts";
25
+ import { parseTableStateWith } from "./table-state.ts";
29
26
  import type { ColumnState, TableState } from "./table-state.ts";
30
- import { FilterBar } from "./FilterBar.tsx";
27
+ import { filterBarFeature } from "./FilterBar.tsx";
31
28
  import { DataTableToolbar } from "./DataTableToolbar.tsx";
32
29
  import type { DataTableToolbarAction } from "./DataTableToolbar.tsx";
33
30
  import { parseFilter, serializeFilter } from "./filter.ts";
34
31
  import type { FilterNode } from "./filter.ts";
35
32
  import type { FilterDateEditor } from "./FilterBar.tsx";
36
- import { createClientExport } from "./export.ts";
37
33
  import { selectClientRows } from "./selection-client.ts";
38
- import { createServerExport } from "./server-export.ts";
39
- import type { ServerExportOutcome, ServerExportSnapshot, TableExportRequest } from "./server-export.ts";
40
- import { createCellEdit } from "./cell-edit.ts";
41
- import type { CellCommitOutcome, CellCommitRequest, CellCommitResult, CellEditSnapshot } from "./cell-edit.ts";
34
+ import { createServerExportWith } from "./server-export.ts";
35
+ import type { ServerExportOutcome, TableExportRequest } from "./server-export.ts";
36
+ import type { CellCommitRequest, CellCommitResult } from "./cell-edit.ts";
42
37
  import { resolveTableMessages } from "./messages.ts";
38
+ import { cellEditingFeature, createSnapshotSignal, createStableRows, defaultCell, groupingFeature, hierarchyFeature } from "./data-table-features.tsx";
39
+ import type { DataTableCellAttributes, DataTableCellBinding, DataTableFeature, DataTableFeatureContext, DataTableFeatureId, DataTablePresentation, DisplayDataRow, DisplayGroupRow, DisplayRow, StableRow } from "./data-table-features.tsx";
43
40
 
44
41
  export interface DataTableResult<Row extends object> extends PageResult<Row> {
45
42
  readonly facets?: Readonly<Record<string, Readonly<Record<string, number>>>>;
@@ -47,6 +44,15 @@ export interface DataTableResult<Row extends object> extends PageResult<Row> {
47
44
  readonly groups?: readonly ServerRowGroup[];
48
45
  }
49
46
 
47
+ /** One cursor page. Either cursor may be null; total is optional and may be an estimate or lower bound. */
48
+ export interface DataTableCursorResult<Row extends object> extends CursorPageResult<Row> {
49
+ readonly facets?: Readonly<Record<string, Readonly<Record<string, number>>>>;
50
+ }
51
+
52
+ /** The request state for a pagination prop: cursor props produce cursor state, everything else numbered or complete state. */
53
+ type DataTableServerPagination<Pagination extends ServerPagination> = Pagination extends CursorPagination ? CursorPagination : TablePagination;
54
+ type DataTableServerResult<Row extends object, Pagination extends ServerPagination> = Pagination extends CursorPagination ? DataTableCursorResult<Row> : DataTableResult<Row>;
55
+
50
56
  export interface DataTableInitialState {
51
57
  readonly search?: string;
52
58
  readonly filter?: TableState["filter"];
@@ -154,16 +160,15 @@ interface DataTableBaseProps<Row extends object> {
154
160
  readonly variant?: DataTableVariant;
155
161
  /** Optional local density for table chrome and rows. Omission inherits the surrounding application density. */
156
162
  readonly density?: DataTableDensity;
157
- readonly pagination?: TablePagination;
158
163
  readonly initialState?: DataTableInitialState;
159
164
  /** Reactively applies an app-owned accepted filter. Use onAcceptedStateChange to keep table-authored changes synchronized. */
160
165
  readonly filter?: FilterNode;
166
+ /** Row and cell height as a CSS length, such as `"2.75rem"` for two-line cells. Pair with `estimatedRowHeight` in pixels. */
161
167
  readonly rowHeight?: string;
162
168
  readonly variableRowHeight?: boolean;
163
169
  readonly estimatedRowHeight?: number;
164
170
  readonly initialViewportHeight?: number;
165
171
  readonly class?: string;
166
- readonly onAcceptedStateChange?: (state: TableState) => void;
167
172
  readonly onRowActivate?: (row: Row) => void;
168
173
  readonly selection?: DataTableSelectionOptions<Row>;
169
174
  /** One action model rendered in both the selection bar and each row context menu. */
@@ -191,72 +196,60 @@ interface DataTableBaseProps<Row extends object> {
191
196
  export interface ClientDataTableProps<Row extends object> extends DataTableBaseProps<Row> {
192
197
  readonly mode?: "client";
193
198
  readonly data: readonly Row[];
199
+ readonly pagination?: TablePagination;
200
+ readonly onAcceptedStateChange?: (state: TableState) => void;
194
201
  readonly initialResult?: never;
195
202
  readonly onStateChange?: never;
196
203
  readonly onExport?: never;
197
204
  readonly refreshKey?: never;
198
205
  }
199
206
 
200
- export interface ServerDataTableProps<Row extends object> extends DataTableBaseProps<Row> {
207
+ /** Pagination is false, numbered `{ pageIndex, pageSize }`, or `{ kind: "cursor", pageSize, cursor }`; its kind selects the result contract. */
208
+ export interface ServerDataTableProps<Row extends object, Pagination extends ServerPagination = TablePagination> extends DataTableBaseProps<Row> {
201
209
  readonly mode: "server";
202
- readonly pagination: TablePagination;
210
+ readonly pagination: Pagination;
211
+ readonly onAcceptedStateChange?: (state: TableState<DataTableServerPagination<Pagination>>) => void;
203
212
  readonly data?: never;
204
- readonly initialResult?: DataTableResult<Row>;
205
- readonly onStateChange: (state: TableState, signal: AbortSignal) => Promise<DataTableResult<Row>>;
213
+ readonly initialResult?: DataTableServerResult<Row, Pagination>;
214
+ readonly onStateChange: (state: TableState<DataTableServerPagination<Pagination>>, signal: AbortSignal) => Promise<DataTableServerResult<Row, Pagination>>;
206
215
  /** Change to revalidate the latest requested/accepted query without resetting layout or scroll. Initial value does not fetch. */
207
216
  readonly refreshKey?: string | number;
208
217
  /** Creates a complete server-side export for the captured accepted query and selection. Without this adapter, export UI is hidden. */
209
- readonly onExport?: (request: TableExportRequest, signal: AbortSignal) => Promise<Blob>;
218
+ readonly onExport?: (request: TableExportRequest<DataTableServerPagination<Pagination>>, signal: AbortSignal) => Promise<Blob>;
210
219
  }
211
220
 
212
- export type DataTableProps<Row extends object> = ClientDataTableProps<Row> | ServerDataTableProps<Row>;
221
+ export type DataTableProps<Row extends object, Pagination extends ServerPagination = TablePagination> = ClientDataTableProps<Row> | ServerDataTableProps<Row, Pagination>;
213
222
 
214
- interface StableRow<Row extends object> {
215
- readonly id: string;
216
- readonly value: Accessor<Row>;
217
- readonly update: (row: Row) => boolean;
223
+ /**
224
+ * The composition root erases the server pagination kind. Method signatures accept every public pairing;
225
+ * parseServerPagination and per-response assessment enforce that state and results keep the configured kind.
226
+ */
227
+ interface ErasedClientProps<Row extends object> extends Omit<ClientDataTableProps<Row>, "onAcceptedStateChange"> {
228
+ onAcceptedStateChange?(state: TableState<ServerPagination>): void;
218
229
  }
230
+ interface ErasedServerProps<Row extends object> extends DataTableBaseProps<Row> {
231
+ readonly mode: "server";
232
+ readonly pagination: ServerPagination;
233
+ readonly data?: never;
234
+ readonly initialResult?: DataTableResult<Row> | DataTableCursorResult<Row>;
235
+ readonly refreshKey?: string | number;
236
+ onAcceptedStateChange?(state: TableState<ServerPagination>): void;
237
+ onStateChange(state: TableState<ServerPagination>, signal: AbortSignal): Promise<DataTableResult<Row> | DataTableCursorResult<Row>>;
238
+ onExport?(request: TableExportRequest<ServerPagination>, signal: AbortSignal): Promise<Blob>;
239
+ }
240
+ export type DataTableInternalProps<Row extends object> = ErasedClientProps<Row> | ErasedServerProps<Row>;
219
241
 
220
242
  interface ScrollAnchor {
221
243
  readonly id: string;
244
+ readonly index: number;
222
245
  readonly offset: number;
223
246
  }
224
247
 
225
- interface RenderedRow<Row extends object> {
226
- readonly key: string;
227
- readonly row: Accessor<DisplayRow<Row>>;
228
- readonly updateRow: (row: DisplayRow<Row>) => void;
229
- readonly item: Accessor<VirtualItem>;
230
- readonly updateItem: (item: VirtualItem) => void;
231
- }
232
-
233
- interface DisplayDataRow<Row extends object> {
234
- readonly kind: "data";
235
- readonly key: string;
236
- readonly row: StableRow<Row>;
237
- readonly parentId: string | null;
238
- readonly depth: number;
239
- readonly position: number;
240
- readonly setSize: number;
241
- readonly canExpand: boolean;
242
- readonly expanded: boolean;
243
- readonly unloaded: boolean;
244
- readonly pending: boolean;
245
- readonly error: unknown;
248
+ interface VirtualRow<Row extends object> {
249
+ readonly row: DisplayRow<Row>;
250
+ readonly item: VirtualItem;
246
251
  }
247
252
 
248
- interface DisplayGroupRow<Row extends object> {
249
- readonly kind: "group";
250
- readonly key: string;
251
- readonly group: ClientRowGroup<Row>;
252
- readonly label: string;
253
- readonly position: number;
254
- readonly setSize: number;
255
- readonly expanded: boolean;
256
- }
257
-
258
- type DisplayRow<Row extends object> = DisplayDataRow<Row> | DisplayGroupRow<Row>;
259
-
260
253
  function displayDataRow<Row extends object>(row: DisplayRow<Row>): DisplayDataRow<Row> | undefined {
261
254
  return row.kind === "data" ? row : undefined;
262
255
  }
@@ -265,113 +258,12 @@ function displayGroupRow<Row extends object>(row: DisplayRow<Row>): DisplayGroup
265
258
  return row.kind === "group" ? row : undefined;
266
259
  }
267
260
 
268
- function createStableRows<Row extends object>(getRowId: (row: Row) => string): (rows: readonly Row[]) => readonly StableRow<Row>[] {
269
- const identity = createRowIdentity(getRowId);
270
- const cache = new Map<string, StableRow<Row>>();
271
- const [revision, setRevision] = createSignal(0);
272
- return rows => {
273
- const ids = identity.resolveIds(rows);
274
- const retained = new Set<string>();
275
- const resolved: StableRow<Row>[] = [];
276
- let changed = false;
277
- for (let index = 0; index < rows.length; index++) {
278
- const row = rows[index]!;
279
- const id = ids[index]!;
280
- retained.add(id);
281
- const existing = cache.get(id);
282
- if (existing) {
283
- changed = existing.update(row) || changed;
284
- resolved.push(existing);
285
- continue;
286
- }
287
- let current = row;
288
- const record: StableRow<Row> = Object.freeze({
289
- id,
290
- value: (): Row => {
291
- revision();
292
- return current;
293
- },
294
- update: (next: Row): boolean => {
295
- if (Object.is(current, next)) return false;
296
- current = next;
297
- return true;
298
- },
299
- });
300
- cache.set(id, record);
301
- resolved.push(record);
302
- }
303
- for (const id of cache.keys()) if (!retained.has(id)) cache.delete(id);
304
- if (changed) setRevision(value => value + 1);
305
- return Object.freeze(resolved);
306
- };
261
+ function sameSelection(left: BulkSelection | undefined, right: BulkSelection | undefined): boolean {
262
+ return left === right || JSON.stringify(left) === JSON.stringify(right);
307
263
  }
308
264
 
309
- interface ClientStableRows<Row extends object> {
310
- readonly update: (rows: readonly Row[]) => void;
311
- readonly resolve: (row: Row, index: number) => StableRow<Row>;
312
- readonly has: (id: string) => boolean;
313
- }
314
-
315
- function createClientStableRows<Row extends object>(getRowId: (row: Row) => string): ClientStableRows<Row> {
316
- const cache = new Map<string, StableRow<Row>>();
317
- let retained: ReadonlySet<string> = new Set();
318
- const known = new WeakMap<Row, string>();
319
- const [revision, setRevision] = createSignal(0);
320
- function create(id: string, row: Row): StableRow<Row> {
321
- let current = row;
322
- const record: StableRow<Row> = Object.freeze({
323
- id,
324
- value: (): Row => {
325
- revision();
326
- return current;
327
- },
328
- update: (next: Row): boolean => {
329
- if (Object.is(current, next)) return false;
330
- current = next;
331
- return true;
332
- },
333
- });
334
- cache.set(id, record);
335
- known.set(row, id);
336
- return record;
337
- }
338
- return Object.freeze({
339
- update(rows: readonly Row[]): void {
340
- if (!Array.isArray(rows)) throw new Error("Table rows must be an array");
341
- const ids = new Set<string>();
342
- let changed = false;
343
- for (let index = 0; index < rows.length; index++) {
344
- const row = rows[index];
345
- if (typeof row !== "object" || row === null) throw new Error(`rows[${index}] must be an object`);
346
- const id = getRowId(row);
347
- if (typeof id !== "string" || !id || id.trim() !== id) throw new Error(`rows[${index}] has an invalid stable ID`);
348
- if (ids.has(id)) throw new Error(`rows[${index}] duplicates row ID ${id}`);
349
- const prior = known.get(row);
350
- if (prior !== undefined && prior !== id) throw new Error(`rows[${index}] changed stable ID from ${prior} to ${id}`);
351
- ids.add(id);
352
- const existing = cache.get(id);
353
- if (existing) {
354
- known.set(row, id);
355
- changed = existing.update(row) || changed;
356
- }
357
- }
358
- for (const id of cache.keys()) if (!ids.has(id)) cache.delete(id);
359
- retained = ids;
360
- if (changed) setRevision(value => value + 1);
361
- },
362
- resolve(row: Row, index: number): StableRow<Row> {
363
- const id = getRowId(row);
364
- if (!retained.has(id)) throw new Error(`Client result row at index ${index} is not part of the supplied data`);
365
- return cache.get(id) ?? create(id, row);
366
- },
367
- has: (id: string) => retained.has(id),
368
- });
369
- }
370
-
371
- function defaultCell(value: ColumnValue): JSX.Element {
372
- if (value === null) return "";
373
- if (typeof value === "boolean") return value ? "Yes" : "No";
374
- return String(value);
265
+ function sameKeys(left: readonly string[], right: readonly string[]): boolean {
266
+ return left.length === right.length && left.every((key, index) => key === right[index]);
375
267
  }
376
268
 
377
269
  function errorMessage(value: unknown): string {
@@ -407,14 +299,6 @@ function exportResetKey(options: false | DataTableExportOptions | undefined): st
407
299
  return key;
408
300
  }
409
301
 
410
- function editorAccepts<Row extends object>(editor: ColumnEditor<Row>, value: ColumnValue): boolean {
411
- if (value === null) return editor.nullable === true;
412
- if (editor.type === "text") return typeof value === "string";
413
- if (editor.type === "number") return typeof value === "number";
414
- if (editor.type === "boolean") return typeof value === "boolean";
415
- if (editor.type === "select") return typeof value === "string" && editor.options.includes(value);
416
- return false;
417
- }
418
302
 
419
303
  function filterActive(filter: FilterNode): boolean {
420
304
  if (filter.kind === "and" || filter.kind === "or") return filter.children.some(filterActive);
@@ -493,17 +377,32 @@ function clientFacetRecord<Row>(view: ClientView<Row>): Readonly<Record<string,
493
377
  return Object.freeze(result);
494
378
  }
495
379
 
496
- function initialTableState<Row extends object>(props: DataTableProps<Row>): TableState {
380
+ function cursorPagination(value: ServerPagination): value is CursorPagination {
381
+ return value !== false && "kind" in value;
382
+ }
383
+
384
+ function cursorResult<Row extends object>(value: DataTableResult<Row> | DataTableCursorResult<Row>): value is DataTableCursorResult<Row> {
385
+ return "nextCursor" in value;
386
+ }
387
+
388
+ /** Client processing runs only on numbered or complete state. */
389
+ function numberedState(state: TableState<ServerPagination>): TableState {
390
+ const pagination = state.pagination;
391
+ if (cursorPagination(pagination)) throw new Error("Cursor pagination requires server mode");
392
+ return { ...state, pagination };
393
+ }
394
+
395
+ function initialTableState<Row extends object>(props: DataTableInternalProps<Row>): TableState<ServerPagination> {
497
396
  const schema = columnStateSchema(props.columns);
498
397
  const definitions = readColumnDefinitions(props.columns);
499
- const pagination = resolvePagination(props.mode ?? "client", props.pagination);
500
- const state = parseTableState({
398
+ const pagination = props.mode === "server" ? parseServerPagination(props.pagination) : resolvePagination("client", props.pagination);
399
+ const state = parseTableStateWith({
501
400
  search: props.initialState?.search ?? "",
502
401
  filter: props.filter ?? props.initialState?.filter ?? { kind: "and", children: [] },
503
402
  sorting: props.initialState?.sorting ?? [],
504
403
  pagination,
505
404
  columns: props.initialState?.columns ?? definitions.map(column => ({ id: column.id, visible: column.visible, width: typeof column.width === "number" ? column.width : null, pin: column.pin })),
506
- }, schema);
405
+ }, schema, parseServerPagination);
507
406
  for (const columnState of state.columns) {
508
407
  const definition = definitions.find(column => column.id === columnState.id);
509
408
  if (!definition) throw new Error(`Unknown table column: ${columnState.id}`);
@@ -521,6 +420,16 @@ function samePagination(left: TablePagination, right: TablePagination): boolean
521
420
  return left === false ? right === false : right !== false && left.pageIndex === right.pageIndex && left.pageSize === right.pageSize;
522
421
  }
523
422
 
423
+ function cursorKey(cursor: CursorPosition): string {
424
+ return `${cursor.direction}:${cursor.value}`;
425
+ }
426
+
427
+ interface CursorStep {
428
+ readonly label: "firstPage" | "previousPage" | "nextPage";
429
+ readonly glyph: GlyphName;
430
+ readonly target: CursorPosition | null | undefined;
431
+ }
432
+
524
433
  function columnTrack(width: number | "fill" | "content", minimum: number | null, maximum: number | null): string {
525
434
  const min = minimum ?? 80;
526
435
  if (typeof width === "number") return `${width}px`;
@@ -532,19 +441,54 @@ function clampColumnWidth(value: number, minimum: number | null, maximum: number
532
441
  return Math.min(maximum ?? 4096, Math.max(minimum ?? 80, Math.round(value)));
533
442
  }
534
443
 
535
- export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.Element {
444
+ export function DataTable<Row extends object, Pagination extends ServerPagination = TablePagination>(props: DataTableProps<Row, Pagination>): JSX.Element {
445
+ return renderDataTable(props, [filterBarFeature, groupingFeature, hierarchyFeature, cellEditingFeature]);
446
+ }
447
+
448
+ /** Props owned by each opt-in feature. A composition without the feature rejects them at compile time and at render. */
449
+ interface DataTableFeatureProps {
450
+ readonly filterBar: "filterBar";
451
+ readonly grouping: "grouping";
452
+ readonly hierarchy: "hierarchy";
453
+ readonly cellEditing: "onCellCommit" | "editResetKey";
454
+ }
455
+ /** DataTable props for a composition that includes only the features named by `Id`. */
456
+ export type ComposedDataTableProps<Row extends object, Id extends DataTableFeatureId, Pagination extends ServerPagination = TablePagination> =
457
+ DataTableProps<Row, Pagination> & { readonly [Key in DataTableFeatureProps[Exclude<DataTableFeatureId, Id>]]?: never };
458
+ export type ComposedDataTable<Id extends DataTableFeatureId> = <Row extends object, Pagination extends ServerPagination = TablePagination>(props: ComposedDataTableProps<Row, Id, Pagination>) => JSX.Element;
459
+
460
+ /**
461
+ * A DataTable that bundles only the listed features. `createDataTable([])` is the lightest table; `DataTable`
462
+ * is the same composition with every feature.
463
+ */
464
+ export function createDataTable<const Features extends readonly DataTableFeature[]>(features: Features): ComposedDataTable<Features[number]["id"]> {
465
+ const composed: DataTableFeature[] = [];
466
+ for (const feature of features) {
467
+ if (typeof feature !== "object" || feature === null || typeof feature.create !== "function") throw new Error("createDataTable accepts only Sheen DataTable features");
468
+ if (composed.some(existing => existing.id === feature.id)) throw new Error(`DataTable feature ${feature.id} is listed more than once`);
469
+ composed.push(feature);
470
+ }
471
+ return props => renderDataTable(props, composed);
472
+ }
473
+
474
+ function requireFeatures<Row extends object>(props: DataTableInternalProps<Row>, definitions: readonly { readonly editor: unknown }[], features: readonly DataTableFeature[]): void {
475
+ const missing = (id: DataTableFeatureId, used: boolean, prop: string): void => {
476
+ if (used && !features.some(feature => feature.id === id)) throw new Error(`DataTable ${prop} requires the ${id}Feature; add it to createDataTable or use DataTable`);
477
+ };
478
+ missing("filterBar", props.filterBar !== undefined && props.filterBar !== false, "filterBar");
479
+ missing("grouping", props.grouping !== undefined, "grouping");
480
+ missing("hierarchy", props.hierarchy !== undefined, "hierarchy");
481
+ missing("cellEditing", props.onCellCommit !== undefined || props.editResetKey !== undefined || definitions.some(column => column.editor !== null), "cell editing");
482
+ }
483
+
484
+ /** Internal composition root behind DataTable and createDataTable. Features own their props, state, and rendering hooks; omitted features are not bundled. */
485
+ export function renderDataTable<Row extends object>(props: DataTableInternalProps<Row>, features: readonly DataTableFeature[]): JSX.Element {
536
486
  if (props.mode === "server" && typeof props.onStateChange !== "function") throw new Error("Server mode requires onStateChange");
537
487
  if (props.mode !== "server" && !Array.isArray(props.data)) throw new Error("Client mode requires a complete data array");
538
488
  if (props.mode !== "server" && props.initialResult !== undefined) throw new Error("initialResult is available only in server mode");
539
489
  if (props.selection && (props.selection.mode !== "multiple" || typeof props.selection.onChange !== "function")) throw new Error("DataTable selection requires multiple mode and onChange");
540
490
  if (typeof props.selection?.resetKey === "number" && !Number.isFinite(props.selection.resetKey)) throw new Error("DataTable selection resetKey must be a finite number or string");
541
491
  if (props.grouping && props.hierarchy) throw new Error("DataTable grouping and hierarchy are separate presentation modes");
542
- if (props.grouping && props.mode !== "server" && props.pagination !== false) throw new Error("Client grouping requires complete continuous data with pagination=false");
543
- if (props.grouping && (typeof props.grouping.by !== "string" || !props.grouping.by.trim())) throw new Error("DataTable grouping requires a column ID");
544
- if (props.grouping?.getLabel !== undefined && typeof props.grouping.getLabel !== "function") throw new Error("DataTable grouping getLabel must be a function");
545
- if (props.hierarchy && !props.hierarchy.getChildren && !props.hierarchy.onLoadChildren) throw new Error("DataTable hierarchy requires getChildren or onLoadChildren");
546
- if (props.hierarchy?.onLoadChildren && !props.hierarchy.hasChildren) throw new Error("Async DataTable hierarchy requires hasChildren");
547
- if (typeof props.hierarchy?.resetKey === "number" && !Number.isFinite(props.hierarchy.resetKey)) throw new Error("DataTable hierarchy resetKey must be a finite number or string");
548
492
  if (typeof props.editResetKey === "number" && !Number.isFinite(props.editResetKey)) throw new Error("DataTable editResetKey must be a finite number or string");
549
493
  const variant = () => {
550
494
  const value: unknown = props.variant;
@@ -566,44 +510,27 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
566
510
  const locale = createMemo(() => theme.state().locale);
567
511
  const messages = createMemo(() => resolveTableMessages(theme.messages()));
568
512
  const definitions = readColumnDefinitions(props.columns);
513
+ requireFeatures(props, definitions, features);
569
514
  const definitionById = new Map(definitions.map(column => [column.id, column]));
570
515
  const searchableDefinitions = definitions.filter(column => column.search !== null);
571
516
  const searchableDefinitionById = new Map(searchableDefinitions.map(column => [column.id, column]));
572
517
  const searchOptions = resolveSearchOptions(props.search, searchableDefinitions.length);
573
518
  const mobileLayout = resolveMobileLayout(props.mobileLayout);
574
519
  if (mobileLayout?.titleColumn && !definitions.some(column => column.id === mobileLayout.titleColumn)) throw new Error(`Unknown mobileLayout title column: ${mobileLayout.titleColumn}`);
575
- const editableDefinitions = definitions.filter(column => column.editor !== null);
576
- if (editableDefinitions.length > 0 && !props.onCellCommit) throw new Error("DataTable editable columns require onCellCommit");
577
- if (editableDefinitions.length === 0 && props.onCellCommit) throw new Error("DataTable onCellCommit requires at least one editable column");
578
- for (const column of editableDefinitions) {
579
- if (!column.accessor || !column.editor) throw new Error(`Editable column ${column.id} requires an accessor and editor`);
580
- }
581
- const editToaster = props.onCellCommit ? createToaster() : undefined;
582
520
  const initialState = initialTableState(props);
583
- const groupingColumn = props.grouping ? definitions.find(column => column.id === props.grouping?.by) : undefined;
584
- if (props.grouping && !groupingColumn?.accessor) throw new Error(`Grouping column ${props.grouping.by} must be an accessor column`);
521
+ const cursorMode = cursorPagination(initialState.pagination);
522
+ if (cursorMode && props.grouping) throw new Error("DataTable grouping requires numbered or complete pagination; cursor pages carry no full-query group metadata");
523
+ if (cursorMode && props.summarizeColumns?.length) throw new Error("DataTable summarizeColumns requires numbered or complete pagination with full-query counts");
524
+ const parseState = (value: unknown): TableState<ServerPagination> => parseTableStateWith(value, schema, parseServerPagination);
525
+ const changeState = (value: TableState<ServerPagination>, change: TableStateChange<ServerPagination>): TableState<ServerPagination> => changeTableStateWith(value, change, schema, parseServerPagination);
585
526
  const selection = props.selection ? createTableSelection(initialState.filter, schema.filterColumns) : undefined;
586
- const [selectionRevision, setSelectionRevision] = createSignal(0);
587
527
  let selectionAnchorId: string | undefined;
588
528
  let selectionSearch = initialState.search;
589
529
  let selectionResetKey = props.selection?.resetKey;
590
- const hierarchy = props.hierarchy ? createRowHierarchy<Row>({
591
- getRowId: props.getRowId,
592
- ...(props.hierarchy.getChildren ? { getChildren: props.hierarchy.getChildren } : {}),
593
- ...(props.hierarchy.hasChildren ? { canLoadChildren: props.hierarchy.hasChildren } : {}),
594
- ...(props.hierarchy.onLoadChildren ? { loadChildren: props.hierarchy.onLoadChildren } : {}),
595
- ...(props.hierarchy.defaultExpanded !== undefined ? { defaultExpanded: props.hierarchy.defaultExpanded } : {}),
596
- }) : undefined;
597
- const [hierarchyRevision, setHierarchyRevision] = createSignal(0);
598
- let hierarchyResetKey = props.hierarchy?.resetKey;
599
- const groupExpansion = new Map<string, boolean>();
600
- const [groupRevision, setGroupRevision] = createSignal(0);
601
530
  const [clientState, setClientState] = createSignal(initialState);
602
531
  const [searchDraft, setSearchDraft] = createSignal(initialState.search);
603
532
  const [searchScheduled, setSearchScheduled] = createSignal(false);
604
533
  const [layoutColumns, setLayoutColumns] = createSignal(initialState.columns);
605
- const [serverRevision, setServerRevision] = createSignal(0);
606
- const [exportRevision, setExportRevision] = createSignal(0);
607
534
  const [clientExportError, setClientExportError] = createSignal<unknown>(null);
608
535
  const [lastDownload, setLastDownload] = createSignal<{ readonly href: string; readonly filename: string }>();
609
536
  const [coldVisible, setColdVisible] = createSignal(false);
@@ -616,20 +543,22 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
616
543
  let searchTimer: number | undefined;
617
544
  let searchComposing = false;
618
545
 
619
- const requests = props.mode === "server" && props.onStateChange
620
- ? createTableRequests<TableState, DataTableResult<Row>>(props.onStateChange, props.initialResult ? { state: initialState, result: props.initialResult } : undefined)
546
+ const requests = props.mode === "server"
547
+ ? createTableRequests<TableState<ServerPagination>, DataTableResult<Row> | DataTableCursorResult<Row>>((state, signal) => props.onStateChange(state, signal), props.initialResult ? { state: initialState, result: props.initialResult } : undefined)
621
548
  : undefined;
622
549
  const serverExports = props.mode === "server" && props.onExport
623
- ? createServerExport<Blob>(schema, async (request, signal) => {
550
+ ? createServerExportWith<Blob, ServerPagination>(schema, parseServerPagination, async (request, signal) => {
624
551
  const artifact = await props.onExport?.(request, signal);
625
552
  if (!(artifact instanceof Blob)) throw new Error("DataTable onExport must resolve to a Blob");
626
553
  return artifact;
627
554
  })
628
555
  : undefined;
629
- const serverSnapshot = (): TableRequestSnapshot<TableState, DataTableResult<Row>> | undefined => {
630
- serverRevision();
631
- return requests?.getSnapshot();
632
- };
556
+ // Client export code loads on first use. Reset and disposal advance the generation so a late load cannot publish.
557
+ let clientExportGeneration = 0;
558
+ let clientExportInFlight = false;
559
+ const server = requests ? createSnapshotSignal(requests.getSnapshot) : undefined;
560
+ const serverSnapshot = () => server?.snapshot();
561
+ const exportStore = serverExports ? createSnapshotSignal(serverExports.getSnapshot) : undefined;
633
562
 
634
563
  const getValue = (row: Row, columnId: string): ColumnValue => {
635
564
  const column = definitionById.get(columnId);
@@ -639,7 +568,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
639
568
  const column = searchableDefinitionById.get(columnId);
640
569
  return column?.search?.(row) ?? null;
641
570
  };
642
- const clientView = createMemo<ClientView<Row> | undefined>(() => props.mode === "server" ? undefined : createClientView(props.data ?? [], clientState(), {
571
+ const clientView = createMemo<ClientView<Row> | undefined>(() => props.mode === "server" ? undefined : createClientView(props.data ?? [], numberedState(clientState()), {
643
572
  locale: locale(),
644
573
  searchColumns: searchableDefinitions.map(column => column.id),
645
574
  exactMatch: searchOptions?.exactMatch ?? false,
@@ -651,22 +580,22 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
651
580
 
652
581
  createEffect(() => {
653
582
  const view = clientView();
654
- if (!view || samePagination(clientState().pagination, view.pagination)) return;
655
- setClientState(state => parseTableState({ ...state, pagination: view.pagination }, schema));
583
+ if (!view || samePagination(numberedState(clientState()).pagination, view.pagination)) return;
584
+ setClientState(state => parseState({ ...state, pagination: view.pagination }));
656
585
  });
657
586
 
658
587
  onMount(() => {
659
- if (!requests || serverSnapshot()?.accepted) return;
660
- const completion = requests.request(initialState);
661
- setServerRevision(revision => revision + 1);
662
- void completion.finally(() => setServerRevision(revision => revision + 1));
588
+ if (!requests || !server || serverSnapshot()?.accepted) return;
589
+ void server.track(requests.request(initialState));
663
590
  });
664
591
  createEffect(() => {
665
592
  const nextResetKey = exportResetKey(props.export);
666
593
  if (Object.is(nextResetKey, configuredExportResetKey)) return;
667
594
  configuredExportResetKey = nextResetKey;
668
595
  serverExports?.clear();
669
- setExportRevision(revision => revision + 1);
596
+ clientExportGeneration++;
597
+ clientExportInFlight = false;
598
+ exportStore?.sync();
670
599
  setClientExportError(null);
671
600
  const download = lastDownload();
672
601
  if (download) URL.revokeObjectURL(download.href);
@@ -675,22 +604,32 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
675
604
  onCleanup(() => {
676
605
  if (searchTimer !== undefined) window.clearTimeout(searchTimer);
677
606
  requests?.dispose();
678
- hierarchy?.dispose();
607
+ clientExportGeneration++;
679
608
  serverExports?.dispose();
680
609
  const download = lastDownload();
681
610
  if (download) URL.revokeObjectURL(download.href);
682
611
  });
683
612
 
684
- const acceptedState = createMemo<TableState>(() => {
613
+ const acceptedState = createMemo<TableState<ServerPagination>>(() => {
685
614
  const state = serverSnapshot()?.accepted?.state ?? clientState();
686
615
  return Object.freeze({ ...state, columns: layoutColumns() });
687
616
  });
688
- const result = (): DataTableResult<Row> => {
617
+ const result = (): DataTableResult<Row> | DataTableCursorResult<Row> => {
689
618
  const accepted = serverSnapshot()?.accepted?.result;
690
619
  if (accepted) return accepted;
691
620
  const view = clientView();
692
621
  return view ? { rows: view.rows, total: view.total, facets: clientFacetRecord(view) } : { rows: [], total: 0 };
693
622
  };
623
+ const acceptedCursorPage = (): DataTableCursorResult<Row> | undefined => {
624
+ const current = result();
625
+ return cursorResult(current) ? current : undefined;
626
+ };
627
+ /** Full-query count when known exactly. Cursor pages may omit, cap, or estimate it. */
628
+ const exactTotal = (): number | undefined => {
629
+ const current = result();
630
+ if (!cursorResult(current)) return current.total;
631
+ return current.total?.kind === "exact" ? current.total.value : undefined;
632
+ };
694
633
  const acceptedAvailable = (): boolean => props.mode !== "server" || serverSnapshot()?.accepted !== null;
695
634
  const busy = (): boolean => searchScheduled() || (serverSnapshot()?.pending ?? false);
696
635
  const pending = (): boolean => busy() || searchDraft() !== acceptedState().search || Boolean(acceptedAvailable() && serverSnapshot()?.requested);
@@ -712,16 +651,13 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
712
651
  });
713
652
  });
714
653
 
715
- async function transition(next: TableState): Promise<TableRequestOutcome | "client"> {
716
- if (!requests) {
654
+ async function transition(next: TableState<ServerPagination>): Promise<TableRequestOutcome | "client"> {
655
+ if (!requests || !server) {
717
656
  setClientState(next);
718
657
  props.onAcceptedStateChange?.(Object.freeze({ ...next, columns: layoutColumns() }));
719
658
  return "client";
720
659
  }
721
- const completion = requests.request(next);
722
- setServerRevision(revision => revision + 1);
723
- const outcome = await completion;
724
- setServerRevision(revision => revision + 1);
660
+ const outcome = await server.track(requests.request(next));
725
661
  const accepted = requests.getSnapshot().accepted;
726
662
  if (outcome === "accepted" && accepted) props.onAcceptedStateChange?.(Object.freeze({ ...accepted.state, columns: layoutColumns() }));
727
663
  return outcome;
@@ -732,8 +668,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
732
668
  const parsed = parseFilter(filter, schema.filterColumns);
733
669
  const current = serverSnapshot()?.requested ?? acceptedState();
734
670
  if (serializeFilter(parsed, schema.filterColumns) === serializeFilter(current.filter, schema.filterColumns)) return;
735
- const pagination = current.pagination === false ? false : { ...current.pagination, pageIndex: 0 };
736
- const next = parseTableState({ ...current, filter: parsed, pagination }, schema);
671
+ const next = parseState({ ...current, filter: parsed, pagination: resetPagination(current.pagination) });
737
672
  setMobilePageIndex(0);
738
673
  void transition(next).then(outcome => {
739
674
  if (outcome === "accepted" || outcome === "client") viewport?.scrollTo({ top: 0 });
@@ -794,7 +729,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
794
729
  setSearchScheduled(false);
795
730
  const requested = serverSnapshot()?.requested;
796
731
  const basis = requested ? Object.freeze({ ...requested, columns: layoutColumns() }) : acceptedState();
797
- const next = changeTableState(basis, { kind: "query", change: { kind: "search", value: query } }, schema);
732
+ const next = changeState(basis, { kind: "query", change: { kind: "search", value: query } });
798
733
  setMobilePageIndex(0);
799
734
  void transition(next).then(outcome => {
800
735
  if (outcome === "accepted" || outcome === "client") viewport?.scrollTo({ top: 0 });
@@ -824,10 +759,9 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
824
759
  scheduleSearch(query);
825
760
  }
826
761
 
827
- function requestPage(pageIndex: number): void {
828
- const current = acceptedState();
829
- if (current.pagination === false || pending()) return;
830
- const next = changeTableState(current, { kind: "query", change: { kind: "pagination", value: { ...current.pagination, pageIndex } } }, schema);
762
+ function requestPagination(pagination: ServerPagination): void {
763
+ if (pending()) return;
764
+ const next = changeState(acceptedState(), { kind: "query", change: { kind: "pagination", value: pagination } });
831
765
  void transition(next).then(outcome => {
832
766
  if (outcome !== "accepted" && outcome !== "client") return;
833
767
  viewport?.scrollTo({ top: 0 });
@@ -835,17 +769,27 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
835
769
  });
836
770
  }
837
771
 
772
+ function requestPage(pageIndex: number): void {
773
+ const current = acceptedState().pagination;
774
+ if (current !== false && !cursorPagination(current)) requestPagination({ ...current, pageIndex });
775
+ }
776
+
777
+ function requestCursor(cursor: CursorPosition | null): void {
778
+ const current = acceptedState().pagination;
779
+ if (cursorPagination(current)) requestPagination({ ...current, cursor });
780
+ }
781
+
838
782
  function requestSort(column: string, multiple: boolean): void {
839
783
  const requested = serverSnapshot()?.requested;
840
784
  const basis = requested ? Object.freeze({ ...requested, columns: layoutColumns() }) : acceptedState();
841
- const next = changeTableState(basis, { kind: "sortCycle", column, multiple }, schema);
785
+ const next = changeState(basis, { kind: "sortCycle", column, multiple });
842
786
  setMobilePageIndex(0);
843
787
  void transition(next);
844
788
  }
845
789
 
846
790
  function requestFilter(filter: FilterNode): void {
847
791
  if (pending()) return;
848
- const next = changeTableState(acceptedState(), { kind: "query", change: { kind: "filter", value: filter } }, schema);
792
+ const next = changeState(acceptedState(), { kind: "query", change: { kind: "filter", value: filter } });
849
793
  setMobilePageIndex(0);
850
794
  void transition(next).then(outcome => { if (outcome === "accepted" || outcome === "client") viewport?.scrollTo({ top: 0 }); });
851
795
  }
@@ -856,8 +800,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
856
800
  setSearchScheduled(false);
857
801
  setSearchDraft("");
858
802
  const current = acceptedState();
859
- const pagination = current.pagination === false ? false : { ...current.pagination, pageIndex: 0 };
860
- const next = parseTableState({ ...current, search: "", filter: { kind: "and", children: [] }, pagination }, schema);
803
+ const next = parseState({ ...current, search: "", filter: { kind: "and", children: [] }, pagination: resetPagination(current.pagination) });
861
804
  setMobilePageIndex(0);
862
805
  void transition(next).then(outcome => {
863
806
  if (outcome === "accepted" || outcome === "client") queueMicrotask(() => {
@@ -868,163 +811,126 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
868
811
  }
869
812
 
870
813
  function retry(): void {
871
- if (!requests || busy()) return;
872
- const completion = requests.retry();
873
- setServerRevision(revision => revision + 1);
874
- void completion.then(outcome => {
875
- setServerRevision(revision => revision + 1);
814
+ if (!requests || !server || busy()) return;
815
+ void server.track(requests.retry()).then(outcome => {
876
816
  const accepted = requests.getSnapshot().accepted;
877
817
  if (outcome === "accepted" && accepted) props.onAcceptedStateChange?.(Object.freeze({ ...accepted.state, columns: layoutColumns() }));
878
818
  });
879
819
  }
880
820
 
881
- const reconcileRows = createStableRows(props.getRowId);
882
- const clientStableRows = createClientStableRows(props.getRowId);
883
- const flatDisplayCache = new Map<string, DisplayDataRow<Row>>();
884
- const clientRowIndex = createMemo(() => {
885
- if (props.mode === "server") return undefined;
886
- const source = props.data ?? [];
887
- clientStableRows.update(source);
888
- for (const id of flatDisplayCache.keys()) if (!clientStableRows.has(id)) flatDisplayCache.delete(id);
889
- return clientStableRows;
890
- });
891
- function stableResultRows(rows: readonly Row[]): readonly StableRow<Row>[] {
892
- const client = clientRowIndex();
893
- if (!client) return reconcileRows(rows);
894
- return rows.map((row, index) => client.resolve(row, index));
895
- }
821
+ const stableRows = createStableRows(props.getRowId, () => props.mode === "server" ? result().rows : props.data ?? []);
822
+ const flatDisplayCache = new WeakMap<StableRow<Row>, DisplayDataRow<Row>>();
896
823
  function flatDisplayRow(row: StableRow<Row>, index: number, setSize: number): DisplayDataRow<Row> {
897
- const existing = flatDisplayCache.get(row.id);
898
- if (existing && existing.row === row && existing.position === index + 1 && existing.setSize === setSize) return existing;
824
+ const existing = flatDisplayCache.get(row);
825
+ if (existing && existing.position === index + 1 && existing.setSize === setSize) return existing;
899
826
  const created: DisplayDataRow<Row> = Object.freeze({ kind: "data", key: `row:${row.id}`, row, parentId: null, depth: 1, position: index + 1, setSize, canExpand: false, expanded: false, unloaded: false, pending: false, error: null });
900
- flatDisplayCache.set(row.id, created);
827
+ flatDisplayCache.set(row, created);
901
828
  return created;
902
829
  }
903
- const groupNumberFormatter = createMemo(() => new Intl.NumberFormat(locale()));
904
- function groupLabel(group: ClientRowGroup<Row>): string {
905
- const supplied = props.grouping?.getLabel?.(group.value);
906
- const label = supplied ?? (group.value === null ? messages().groupMissing : typeof group.value === "number" ? groupNumberFormatter().format(group.value) : String(group.value));
907
- if (typeof label !== "string" || !label.trim()) throw new Error(`Group ${group.id} requires a nonempty label`);
908
- return label;
909
- }
910
- function groupExpanded(id: string): boolean {
911
- groupRevision();
912
- const existing = groupExpansion.get(id);
913
- if (existing !== undefined) return existing;
914
- const initial = props.grouping?.collapsible === false || props.grouping?.defaultExpanded !== false;
915
- groupExpansion.set(id, initial);
916
- return initial;
917
- }
918
- function setGroupExpanded(id: string, expanded: boolean): void {
919
- if (pending() || props.grouping?.collapsible === false || groupExpanded(id) === expanded) return;
920
- groupExpansion.set(id, expanded);
921
- setGroupRevision(revision => revision + 1);
922
- }
923
- const structuredRows = createMemo<readonly DisplayRow<Row>[]>(() => {
924
- if (hierarchy) {
925
- hierarchyRevision();
926
- const nextResetKey = props.hierarchy?.resetKey;
927
- if (!Object.is(nextResetKey, hierarchyResetKey)) hierarchy.reset();
928
- hierarchyResetKey = nextResetKey;
929
- hierarchy.updateRoots(result().rows);
930
- const snapshot = hierarchy.getSnapshot();
931
- const stable = reconcileRows(snapshot.map(item => item.row));
932
- const stableById = new Map(stable.map(row => [row.id, row]));
933
- return Object.freeze(snapshot.map((item: HierarchyRow<Row>): DisplayDataRow<Row> => {
934
- const row = stableById.get(item.id);
935
- if (!row) throw new Error(`Missing stable hierarchy row: ${item.id}`);
936
- return Object.freeze({ kind: "data", key: `row:${item.id}`, row, parentId: item.parentId, depth: item.depth, position: item.position, setSize: item.setSize, canExpand: item.canExpand, expanded: item.expanded, unloaded: item.unloaded, pending: item.pending, error: item.error });
937
- }));
938
- }
939
- if (props.grouping && groupingColumn?.accessor) {
940
- groupRevision();
941
- if (props.mode === "server" && serverSnapshot()?.accepted === null) return Object.freeze([]);
942
- const current = result();
943
- const aggregateColumns = definitions.flatMap(column => column.aggregate && column.accessor ? [{ id: column.id, aggregate: column.aggregate, getValue: column.accessor }] : []);
944
- const groups = props.mode === "server"
945
- ? normalizeServerGroups(current.rows, current.groups, { column: groupingColumn.id, aggregateColumns: aggregateColumns.map(column => column.id), getRowId: props.getRowId })
946
- : groupClientRows(current.rows, { column: groupingColumn.id, getValue: groupingColumn.accessor, aggregates: aggregateColumns });
947
- const stable = props.mode === "server" ? reconcileRows(current.rows) : stableResultRows(current.rows);
948
- const stableById = new Map(stable.map(row => [row.id, row]));
949
- const rows: DisplayRow<Row>[] = [];
950
- for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
951
- const group = groups[groupIndex]!;
952
- const expanded = groupExpanded(group.id);
953
- rows.push(Object.freeze({ kind: "group", key: group.id, group, label: groupLabel(group), position: groupIndex + 1, setSize: groups.length, expanded }));
954
- if (!expanded) continue;
955
- for (let rowIndex = 0; rowIndex < group.rows.length; rowIndex++) {
956
- const id = props.getRowId(group.rows[rowIndex]!);
957
- const row = stableById.get(id);
958
- if (!row) throw new Error(`Missing stable grouped row: ${id}`);
959
- rows.push(Object.freeze({ kind: "data", key: `row:${id}`, row, parentId: group.id, depth: 2, position: rowIndex + 1, setSize: group.rows.length, canExpand: false, expanded: false, unloaded: false, pending: false, error: null }));
960
- }
961
- }
962
- return Object.freeze(rows);
963
- }
964
- return Object.freeze([]);
830
+ const featureContext: DataTableFeatureContext<Row> = Object.freeze({
831
+ props,
832
+ definitions,
833
+ filterColumns: schema.filterColumns,
834
+ messages,
835
+ locale,
836
+ pending,
837
+ result,
838
+ accepted: acceptedAvailable,
839
+ acceptedFilter: () => acceptedState().filter,
840
+ requestFilter,
841
+ stableRows,
842
+ createStableRows: (source: () => readonly Row[]) => createStableRows(props.getRowId, source),
843
+ rowAt,
844
+ rowIndex,
845
+ focusRow,
965
846
  });
966
- const flatResultRows = createMemo<readonly Row[]>(() => hierarchy || props.grouping ? Object.freeze([]) : result().rows);
967
- const serverFlatStableRows = createMemo<readonly StableRow<Row>[]>(() => props.mode === "server" && !hierarchy && !props.grouping ? Object.freeze(stableResultRows(flatResultRows())) : Object.freeze([]));
847
+ const extensions = features.flatMap(feature => feature.create(featureContext) ?? []);
848
+ const presentations = extensions.flatMap(extension => extension.presentation ? [extension.presentation] : []);
849
+ if (presentations.length > 1) throw new Error("DataTable grouping and hierarchy are separate presentation modes");
850
+ const presentation: DataTablePresentation<Row> | undefined = presentations[0];
851
+ const treePresentation = presentation !== undefined;
852
+ const cellExtensions = extensions.flatMap(extension => extension.cell ? [extension.cell] : []);
853
+ const queryExtensions = extensions.flatMap(extension => extension.query ? [extension.query] : []);
854
+ const overlays = extensions.flatMap(extension => extension.overlay ? [extension.overlay] : []);
855
+ const flatResultRows = createMemo<readonly Row[]>(() => presentation ? Object.freeze([]) : result().rows);
856
+ const serverFlatStableRows = createMemo<readonly StableRow<Row>[]>(() => props.mode === "server" && !presentation
857
+ ? Object.freeze(flatResultRows().map((row, index) => stableRows.resolve(row, index)))
858
+ : Object.freeze([]));
968
859
  function flatStableRow(index: number): StableRow<Row> | undefined {
969
860
  const row = flatResultRows()[index];
970
861
  if (!row) return undefined;
971
- const client = clientRowIndex();
972
- if (client) return client.resolve(row, index);
973
- return serverFlatStableRows()[index];
862
+ return props.mode === "server" ? serverFlatStableRows()[index] : stableRows.resolve(row, index);
974
863
  }
975
- const rowCount = (): number => hierarchy || props.grouping ? structuredRows().length : flatResultRows().length;
864
+ const rowCount = (): number => presentation ? presentation.rows().length : flatResultRows().length;
976
865
  function rowAt(index: number): DisplayRow<Row> | undefined {
977
- if (hierarchy || props.grouping) return structuredRows()[index];
866
+ if (presentation) return presentation.rows()[index];
978
867
  const row = flatStableRow(index);
979
868
  return row ? flatDisplayRow(row, index, flatResultRows().length) : undefined;
980
869
  }
981
- function rowIndex(key: string): number {
982
- if (hierarchy || props.grouping) return structuredRows().findIndex(row => row.key === key);
983
- for (let index = 0; index < flatResultRows().length; index++) if (`row:${flatStableRow(index)?.id ?? ""}` === key) return index;
984
- return -1;
985
- }
986
- let selectionInitialized = false;
987
- const selectableRows = createMemo(() => {
988
- const rows = hierarchy || props.grouping
989
- ? structuredRows().flatMap(row => row.kind === "data" ? [row.row] : [])
990
- : props.mode === "server" ? serverFlatStableRows()
991
- : selection || actions().length > 0 ? stableResultRows(flatResultRows()) : Object.freeze([]);
992
- if (!selection) return { rows, before: "", payload: undefined };
993
- const before = JSON.stringify(selection.getPayload());
994
- const nextResetKey = props.selection?.resetKey;
995
- const nextSearch = acceptedState().search;
996
- if (!Object.is(nextResetKey, selectionResetKey) || nextSearch !== selectionSearch) {
997
- selection.reset();
998
- selectionAnchorId = undefined;
999
- }
1000
- selectionResetKey = nextResetKey;
1001
- selectionSearch = nextSearch;
1002
- selection.setFilter(acceptedState().filter);
1003
- selection.setLoadedIds(rows.map(row => row.id));
1004
- return { rows, before, payload: selection.getPayload() };
1005
- });
1006
- createEffect(() => {
1007
- const synchronized = selectableRows();
1008
- if (!selection || !synchronized.payload) return;
1009
- setSelectionRevision(revision => revision + 1);
1010
- if (selectionInitialized && JSON.stringify(synchronized.payload) !== synchronized.before) props.selection?.onChange(synchronized.payload);
1011
- selectionInitialized = true;
870
+ /**
871
+ * Callers pass the index they already know (the realized item, focused row, or scroll anchor), so keyboard
872
+ * handling is O(1). The scan only runs when rows moved under a stale hint, at most once per accepted row change.
873
+ */
874
+ function rowIndex(key: string, hint?: number): number {
875
+ if (hint !== undefined && hint >= 0 && rowAt(hint)?.key === key) return hint;
876
+ if (presentation) return presentation.rows().findIndex(row => row.key === key);
877
+ if (!key.startsWith("row:")) return -1;
878
+ const id = key.slice("row:".length);
879
+ return flatResultRows().findIndex(row => props.getRowId(row) === id);
880
+ }
881
+ const loadedRows = createMemo<readonly StableRow<Row>[]>(() => presentation
882
+ ? presentation.rows().flatMap(row => row.kind === "data" ? [row.row] : [])
883
+ : props.mode === "server" ? serverFlatStableRows()
884
+ : selection || actions().length > 0 ? flatResultRows().map((row, index) => stableRows.resolve(row, index)) : Object.freeze([]));
885
+ const loadedIds = createMemo<ReadonlySet<string>>(() => new Set(loadedRows().map(row => row.id)));
886
+ const [selectionPayload, setSelectionPayload] = createSignal<BulkSelection | undefined>(selection?.getPayload(), { equals: sameSelection });
887
+ // The accepted boundary (reset key, search, filter, and loaded rows) drives selection eligibility before rows render.
888
+ createComputed(() => {
889
+ const ids = loadedIds();
890
+ const resetKey = props.selection?.resetKey;
891
+ const state = acceptedState();
892
+ if (!selection) return;
893
+ untrack(() => {
894
+ if (!Object.is(resetKey, selectionResetKey) || state.search !== selectionSearch) {
895
+ selection.reset();
896
+ selectionAnchorId = undefined;
897
+ }
898
+ selectionResetKey = resetKey;
899
+ selectionSearch = state.search;
900
+ selection.setFilter(state.filter);
901
+ selection.setLoadedIds([...ids]);
902
+ setSelectionPayload(selection.getPayload());
903
+ });
1012
904
  });
905
+ let notifiedSelection = selectionPayload();
906
+ // Boundary-driven clears reach the application here; user changes notify directly in publishSelection.
907
+ createEffect(on(selectionPayload, payload => {
908
+ if (!payload || payload === notifiedSelection) return;
909
+ notifiedSelection = payload;
910
+ props.selection?.onChange(payload);
911
+ }, { defer: true }));
1013
912
  function publishSelection(): void {
1014
913
  if (!selection) return;
1015
914
  const payload = selection.getPayload();
1016
- setSelectionRevision(revision => revision + 1);
915
+ notifiedSelection = payload;
916
+ setSelectionPayload(payload);
1017
917
  props.selection?.onChange(payload);
1018
918
  }
919
+ const selectionMarks = createMemo<ReadonlySet<string>>(() => {
920
+ const payload = selectionPayload();
921
+ return new Set(payload?.kind === "query" ? payload.excluded : payload?.ids ?? []);
922
+ });
1019
923
  function rowSelected(id: string): boolean {
1020
- selectionRevision();
1021
- selectableRows();
1022
- return selection?.isSelected(id) ?? false;
924
+ const payload = selectionPayload();
925
+ if (!payload) return false;
926
+ return payload.kind === "query" ? loadedIds().has(id) && !selectionMarks().has(id) : selectionMarks().has(id);
927
+ }
928
+ function selectionAnchorLoaded(id: string): boolean {
929
+ return loadedIds().has(id);
1023
930
  }
1024
931
  function changeRowSelection(id: string, selected: boolean, range: boolean): void {
1025
932
  if (!selection || pending()) return;
1026
- const anchorLoaded = selectionAnchorId !== undefined && selectableRows().rows.some(row => row.id === selectionAnchorId);
1027
- if (range && anchorLoaded && selectionAnchorId) selection.selectRange(selectionAnchorId, id, selected);
933
+ if (range && selectionAnchorId !== undefined && selectionAnchorLoaded(selectionAnchorId)) selection.selectRange(selectionAnchorId, id, selected);
1028
934
  else {
1029
935
  selection.setSelected(id, selected);
1030
936
  selectionAnchorId = id;
@@ -1047,10 +953,13 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1047
953
  selectionAnchorId = undefined;
1048
954
  publishSelection();
1049
955
  }
1050
- const selectedLoadedCount = createMemo(() => selectableRows().rows.filter(row => rowSelected(row.id)).length);
1051
- const selectionPayload = createMemo(() => {
1052
- selectionRevision();
1053
- return selection?.getPayload();
956
+ const selectedLoadedCount = createMemo(() => {
957
+ const payload = selectionPayload();
958
+ if (!payload) return 0;
959
+ const loaded = loadedIds();
960
+ let marked = 0;
961
+ for (const id of selectionMarks()) if (loaded.has(id)) marked++;
962
+ return payload.kind === "query" ? loaded.size - marked : marked;
1054
963
  });
1055
964
  const selectionActive = createMemo(() => {
1056
965
  const payload = selectionPayload();
@@ -1066,10 +975,10 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1066
975
  function actionContext(anchor?: StableRow<Row>): DataTableActionContext<Row> {
1067
976
  const payload = anchor ? rowActionSelection(anchor) : selectionPayload();
1068
977
  if (!payload) throw new Error("DataTable selection actions require an active selection");
1069
- const loadedRows = selectableRows().rows
978
+ const selectedRows = loadedRows()
1070
979
  .filter(row => payload.kind === "query" ? !payload.excluded.includes(row.id) : payload.ids.includes(row.id))
1071
980
  .map(row => row.value());
1072
- return Object.freeze({ selection: payload, loadedRows: Object.freeze(loadedRows), ...(anchor ? { anchor: anchor.value() } : {}) });
981
+ return Object.freeze({ selection: payload, loadedRows: Object.freeze(selectedRows), ...(anchor ? { anchor: anchor.value() } : {}) });
1073
982
  }
1074
983
 
1075
984
  function actionDisabled(action: DataTableAction<Row>, context: DataTableActionContext<Row>): boolean {
@@ -1099,7 +1008,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1099
1008
  const selectionCount = createMemo(() => {
1100
1009
  const payload = selectionPayload();
1101
1010
  if (!payload) return 0;
1102
- return payload.kind === "query" ? Math.max(0, result().total - payload.excluded.length) : payload.ids.length;
1011
+ return payload.kind === "query" ? Math.max(0, (exactTotal() ?? 0) - payload.excluded.length) : payload.ids.length;
1103
1012
  });
1104
1013
  const [selectionBarPresent, setSelectionBarPresent] = createSignal(false);
1105
1014
  const [selectionBarOpen, setSelectionBarOpen] = createSignal(false);
@@ -1133,14 +1042,15 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1133
1042
  if (typeof label !== "string" || !label.trim()) throw new Error(`Selection label for ${row.id} must be nonempty`);
1134
1043
  return label;
1135
1044
  }
1045
+ const acceptedColumns = createMemo(() => acceptedState().columns);
1046
+ const acceptedColumnById = createMemo(() => new Map(acceptedColumns().map(column => [column.id, column])));
1136
1047
  const columnRecords = definitions.map((definition, index) => {
1137
1048
  const initial = initialState.columns.find(column => column.id === definition.id);
1138
1049
  if (!initial) throw new Error(`Missing initial state for table column: ${definition.id}`);
1139
- const [state, updateState] = createSignal(initial);
1140
- return Object.freeze({ definition, state, updateState, variable: `--sheen-table-column-${index}`, sortDescriptionId: createUniqueId() });
1050
+ const state = createMemo(() => acceptedColumnById().get(definition.id) ?? initial);
1051
+ return Object.freeze({ definition, state, variable: `--sheen-table-column-${index}`, sortDescriptionId: createUniqueId() });
1141
1052
  });
1142
1053
  const columnRecordById = new Map(columnRecords.map(column => [column.definition.id, column]));
1143
- const acceptedColumns = createMemo(() => acceptedState().columns);
1144
1054
  const orderedColumnStates = createMemo(() => orderColumnStates(acceptedColumns()));
1145
1055
  const summaryEligible = createMemo(() => {
1146
1056
  const ids = props.summarizeColumns ?? [];
@@ -1165,7 +1075,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1165
1075
  const value = typeof summary.value === "number"
1166
1076
  ? summary.kind === "date" ? new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeZone: "UTC" }).format(summary.value) : new Intl.NumberFormat(locale).format(summary.value)
1167
1077
  : summary.value;
1168
- return messages().constrainedColumn.replace(/\{(column|value|count)\}/gu, (_match: string, key: string) => key === "column" ? definition.header : key === "value" ? value : new Intl.NumberFormat(locale).format(result().total));
1078
+ return messages().constrainedColumn.replace(/\{(column|value|count)\}/gu, (_match: string, key: string) => key === "column" ? definition.header : key === "value" ? value : new Intl.NumberFormat(locale).format(exactTotal() ?? 0));
1169
1079
  };
1170
1080
  const restoreSummary = (id: string): void => {
1171
1081
  setRestoredSummaries(previous => new Set([...previous, id]));
@@ -1179,81 +1089,18 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1179
1089
  });
1180
1090
  };
1181
1091
  const visibleDefinitions = createMemo(() => {
1182
- const ordered = orderedColumnStates();
1183
- for (const state of ordered) columnRecordById.get(state.id)?.updateState(state);
1184
- return ordered.flatMap(state => {
1092
+ return orderedColumnStates().flatMap(state => {
1185
1093
  const record = columnRecordById.get(state.id);
1186
1094
  return record && state.visible && !summarizedIds().has(state.id) ? [record] : [];
1187
1095
  });
1188
1096
  });
1189
- type CellEditController = ReturnType<typeof createCellEdit<ColumnValue, string>>;
1190
- interface CellEditRecord {
1191
- readonly controller: CellEditController;
1192
- readonly revision: Accessor<number>;
1193
- readonly publish: () => void;
1194
- }
1195
- const cellEditRecords = new Map<string, Map<string, CellEditRecord>>();
1196
- const [editGeneration, setEditGeneration] = createSignal(0);
1197
- let currentEditResetKey = props.editResetKey;
1198
-
1199
- function cellEditRecord(row: StableRow<Row>, column: (typeof columnRecords)[number]): CellEditRecord | undefined {
1200
- editGeneration();
1201
- const editor = column.definition.editor;
1202
- const accessor = column.definition.accessor;
1203
- const commit = props.onCellCommit;
1204
- if (!editor || !accessor || !commit) return undefined;
1205
- const existing = cellEditRecords.get(row.id)?.get(column.definition.id);
1206
- if (existing) return existing;
1207
- const initial = accessor(row.value());
1208
- if (!editorAccepts(editor, initial)) throw new Error(`Initial value for editable cell ${row.id}/${column.definition.id} does not match its editor`);
1209
- const [revision, setRevision] = createSignal(0);
1210
- const publish = () => setRevision(value => value + 1);
1211
- const controller = createCellEdit<ColumnValue, string>(initial, async (request, signal) => {
1212
- const applicationRequest: DataTableCellCommitRequest<Row> = Object.freeze({ ...request, rowId: row.id, row: row.value(), column: column.definition.id });
1213
- const result = await commit(applicationRequest, signal);
1214
- const value = result.kind === "accepted" ? result.value : result.current;
1215
- if (!editorAccepts(editor, value)) throw new Error(`Committed value for ${row.id}/${column.definition.id} does not match its editor`);
1216
- return result;
1217
- }, { validate: value => {
1218
- if (!editorAccepts(editor, value)) return value === null ? messages().cellValueRequired : messages().cellValueInvalid;
1219
- return editor.validate?.(value, row.value()) ?? null;
1220
- } });
1221
- const record = Object.freeze({ controller, revision, publish });
1222
- const rowRecords = cellEditRecords.get(row.id) ?? new Map<string, CellEditRecord>();
1223
- rowRecords.set(column.definition.id, record);
1224
- cellEditRecords.set(row.id, rowRecords);
1225
- return record;
1226
- }
1227
-
1228
- function editSnapshot(record: CellEditRecord | undefined): CellEditSnapshot<ColumnValue, string> | undefined {
1229
- record?.revision();
1230
- return record?.controller.getSnapshot();
1231
- }
1232
-
1233
- createEffect(() => {
1234
- const nextResetKey = props.editResetKey;
1235
- if (typeof nextResetKey === "number" && !Number.isFinite(nextResetKey)) throw new Error("DataTable editResetKey must be a finite number or string");
1236
- if (Object.is(nextResetKey, currentEditResetKey)) return;
1237
- currentEditResetKey = nextResetKey;
1238
- for (const columns of cellEditRecords.values()) for (const record of columns.values()) record.controller.dispose();
1239
- cellEditRecords.clear();
1240
- editToaster?.clear();
1241
- setEditGeneration(generation => generation + 1);
1242
- });
1243
- onCleanup(() => {
1244
- for (const columns of cellEditRecords.values()) for (const record of columns.values()) record.controller.dispose();
1245
- cellEditRecords.clear();
1246
- });
1247
1097
  const availableExportFormats = createMemo<readonly DataTableExportFormat[]>(() => {
1248
1098
  const hasVisibleValue = visibleDefinitions().some(column => column.definition.accessor !== null);
1249
1099
  if (!hasVisibleValue || configuredExportFormats.length === 0) return Object.freeze([]);
1250
1100
  if (props.mode === "server" && !serverExports) return Object.freeze([]);
1251
1101
  return configuredExportFormats;
1252
1102
  });
1253
- const serverExportSnapshot = (): ServerExportSnapshot<Blob> | undefined => {
1254
- exportRevision();
1255
- return serverExports?.getSnapshot();
1256
- };
1103
+ const serverExportSnapshot = () => exportStore?.snapshot();
1257
1104
  const exportPending = (): boolean => serverExportSnapshot()?.pending ?? false;
1258
1105
  const exportError = (): unknown => serverExportSnapshot()?.error ?? clientExportError();
1259
1106
 
@@ -1269,29 +1116,35 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1269
1116
  anchor.click();
1270
1117
  }
1271
1118
 
1272
- function exportClient(format: DataTableExportFormat): void {
1273
- if (props.mode === "server") return;
1119
+ async function exportClient(format: DataTableExportFormat): Promise<void> {
1120
+ if (props.mode === "server" || clientExportInFlight) return;
1274
1121
  setClientExportError(null);
1122
+ // Capture the accepted view, selection, and columns at request time; only the code load is deferred.
1123
+ const generation = clientExportGeneration;
1124
+ clientExportInFlight = true;
1275
1125
  try {
1276
1126
  const view = clientView()?.view ?? [];
1277
1127
  const payload = selectionActive() ? selectionPayload() : undefined;
1278
1128
  const rows = payload ? selectClientRows(view, payload, { locale: locale(), filterColumns: schema.filterColumns, getRowId: props.getRowId, getValue }) : view;
1279
- const exported = createClientExport(rows, visibleDefinitions().flatMap(column => column.definition.accessor
1129
+ const columns = visibleDefinitions().flatMap(column => column.definition.accessor
1280
1130
  ? [{ id: column.definition.id, header: column.definition.header, value: column.definition.accessor }]
1281
- : []));
1131
+ : []);
1132
+ const { createClientExport } = await import("./export.ts");
1133
+ if (generation !== clientExportGeneration) return;
1134
+ const exported = createClientExport(rows, columns);
1282
1135
  const content = format === "csv" ? exported.toCSV() : exported.toJSON();
1283
1136
  publishDownload(new Blob([content], { type: format === "csv" ? "text/csv;charset=utf-8" : "application/json;charset=utf-8" }), format);
1284
1137
  } catch (value) {
1285
- setClientExportError(value);
1138
+ if (generation === clientExportGeneration) setClientExportError(value);
1139
+ } finally {
1140
+ if (generation === clientExportGeneration) clientExportInFlight = false;
1286
1141
  }
1287
1142
  }
1288
1143
 
1289
1144
  async function finishServerExport(completion: Promise<ServerExportOutcome>): Promise<void> {
1290
- setExportRevision(revision => revision + 1);
1291
- const outcome = await completion;
1292
- setExportRevision(revision => revision + 1);
1145
+ const outcome = await (exportStore ? exportStore.track(completion) : completion);
1293
1146
  if (outcome !== "accepted") return;
1294
- const accepted = serverExports?.getSnapshot().accepted;
1147
+ const accepted = serverExportSnapshot()?.accepted;
1295
1148
  if (accepted) publishDownload(accepted.artifact, accepted.request.format);
1296
1149
  }
1297
1150
 
@@ -1304,7 +1157,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1304
1157
  function requestExport(format: DataTableExportFormat): void {
1305
1158
  if (pending() || exportPending()) return;
1306
1159
  if (props.mode === "server") exportServer(format);
1307
- else exportClient(format);
1160
+ else void exportClient(format);
1308
1161
  }
1309
1162
 
1310
1163
  function retryExport(): void {
@@ -1322,9 +1175,13 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1322
1175
  const resultNumber = createMemo(() => new Intl.NumberFormat(locale()));
1323
1176
  const resultCount = () => {
1324
1177
  if (!acceptedAvailable()) return undefined;
1325
- const total = result().total;
1326
- const template = total === 1 ? messages().resultCountOne : messages().resultCount;
1327
- return template.replace("{count}", resultNumber().format(total));
1178
+ const current = result();
1179
+ const total: CursorTotal | undefined = cursorResult(current) ? current.total : { kind: "exact", value: current.total };
1180
+ if (!total) return undefined;
1181
+ const template = total.kind === "estimate" ? messages().resultCountEstimate
1182
+ : total.kind === "atLeast" ? messages().resultCountAtLeast
1183
+ : total.value === 1 ? messages().resultCountOne : messages().resultCount;
1184
+ return template.replace("{count}", resultNumber().format(total.value));
1328
1185
  };
1329
1186
  function downloadLastExport(): void {
1330
1187
  const download = lastDownload();
@@ -1338,14 +1195,14 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1338
1195
  const selectionTrack = "var(--sheen-table-selection-column, 2.75rem)";
1339
1196
  const template = createMemo(() => [...(selection ? [selectionTrack] : []), ...visibleDefinitions().map(track)].join(" "));
1340
1197
 
1341
- function commitLayout(next: TableState): void {
1198
+ function commitLayout(next: TableState<ServerPagination>): void {
1342
1199
  setLayoutColumns(next.columns);
1343
1200
  const base = serverSnapshot()?.accepted?.state ?? clientState();
1344
1201
  props.onAcceptedStateChange?.(Object.freeze({ ...base, columns: next.columns }));
1345
1202
  }
1346
1203
 
1347
- function changeLayout(change: Parameters<typeof changeTableState>[1]): void {
1348
- commitLayout(changeTableState(acceptedState(), change, schema));
1204
+ function changeLayout(change: TableStateChange<ServerPagination>): void {
1205
+ commitLayout(changeState(acceptedState(), change));
1349
1206
  }
1350
1207
 
1351
1208
  function currentColumnWidth(column: (typeof columnRecords)[number]): number {
@@ -1367,18 +1224,21 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1367
1224
  }
1368
1225
 
1369
1226
  function autoFitColumn(column: (typeof columnRecords)[number]): void {
1370
- const measured = [...tableElement?.querySelectorAll<HTMLElement>("[data-column]") ?? []]
1371
- .filter(element => element.dataset.column === column.definition.id)
1372
- .reduce((maximum, element) => Math.max(maximum, element.scrollWidth + 1), 0);
1227
+ const cells = [...tableElement?.querySelectorAll<HTMLElement>("[data-column]") ?? []].filter(element => element.dataset.column === column.definition.id);
1228
+ // Grid tracks size every cell to the current column width, so measure each cell at its content width to fit both wider and narrower content.
1229
+ const previous = cells.map(cell => cell.style.inlineSize);
1230
+ for (const cell of cells) cell.style.inlineSize = "max-content";
1231
+ const measured = cells.reduce((maximum, cell) => Math.max(maximum, Math.ceil(cell.getBoundingClientRect().width)), 0);
1232
+ cells.forEach((cell, index) => { cell.style.inlineSize = previous[index] ?? ""; });
1373
1233
  setColumnWidth(column, measured > 0 ? measured : currentColumnWidth(column));
1374
1234
  }
1375
1235
 
1376
1236
  function setColumnPin(column: (typeof columnRecords)[number], pin: ColumnState["pin"]): void {
1377
1237
  let next = acceptedState();
1378
1238
  if (pin !== false && column.state().width === null && typeof column.definition.width !== "number") {
1379
- next = changeTableState(next, { kind: "columnWidth", column: column.definition.id, width: currentColumnWidth(column) }, schema);
1239
+ next = changeState(next, { kind: "columnWidth", column: column.definition.id, width: currentColumnWidth(column) });
1380
1240
  }
1381
- next = changeTableState(next, { kind: "columnPin", column: column.definition.id, pin }, schema);
1241
+ next = changeState(next, { kind: "columnPin", column: column.definition.id, pin });
1382
1242
  commitLayout(next);
1383
1243
  }
1384
1244
 
@@ -1427,7 +1287,8 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1427
1287
  });
1428
1288
  const toolbarActions = createMemo<readonly DataTableToolbarAction[]>(() => {
1429
1289
  const next: DataTableToolbarAction[] = [];
1430
- if (selection && !hierarchy && acceptedState().search.length === 0) next.push({ kind: "action", id: "select-all", label: messages().selectAll, disabled: pending(), onSelect: selectAllMatchingRows });
1290
+ // An all-matching payload is displayed with a full-query count, so cursor pages without an exact total cannot offer it.
1291
+ if (selection && (presentation?.allowSelectAll ?? true) && acceptedState().search.length === 0 && exactTotal() !== undefined) next.push({ kind: "action", id: "select-all", label: messages().selectAll, disabled: pending(), onSelect: selectAllMatchingRows });
1431
1292
  if (availableExportFormats().length > 0) next.push({ kind: "menu", id: "export", label: messages().export, disabled: pending() || exportPending(), items: exportMenuItems() });
1432
1293
  if (lastDownload()) next.push({ kind: "action", id: "download", label: messages().downloadLastExport, onSelect: downloadLastExport });
1433
1294
  if (props.columnControls !== false) next.push({ kind: "menu", id: "columns", label: messages().columns, items: columnMenuItems() });
@@ -1658,41 +1519,55 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1658
1519
  measuredDensity = currentDensity;
1659
1520
  if (virtualizerMounted && changed) virtualizer.measure();
1660
1521
  });
1661
- const renderedRowCache = new Map<string, RenderedRow<Row>>();
1662
- const renderedRows = createMemo<readonly RenderedRow<Row>[]>(() => {
1663
- const retained = new Set<string>();
1664
- const rows: RenderedRow<Row>[] = [];
1522
+ const virtualRows = createMemo<ReadonlyMap<string, VirtualRow<Row>>>(() => {
1523
+ const rows = new Map<string, VirtualRow<Row>>();
1665
1524
  for (const item of virtualizer.getVirtualItems()) {
1666
1525
  const row = rowAt(item.index);
1667
- if (!row) continue;
1668
- retained.add(row.key);
1669
- const existing = renderedRowCache.get(row.key);
1670
- if (existing) {
1671
- existing.updateRow(row);
1672
- existing.updateItem(item);
1673
- rows.push(existing);
1674
- continue;
1675
- }
1676
- const [currentRow, setCurrentRow] = createSignal(row);
1677
- const [currentItem, setCurrentItem] = createSignal(item);
1678
- const rendered = Object.freeze({ key: row.key, row: currentRow, updateRow: (next: DisplayRow<Row>): void => { setCurrentRow(next); }, item: currentItem, updateItem: (next: VirtualItem): void => { setCurrentItem(next); } });
1679
- renderedRowCache.set(row.key, rendered);
1680
- rows.push(rendered);
1526
+ if (row) rows.set(row.key, { row, item });
1681
1527
  }
1682
- for (const id of renderedRowCache.keys()) if (!retained.has(id)) renderedRowCache.delete(id);
1683
1528
  return rows;
1684
1529
  });
1530
+ // Rendered rows are keyed by stable display key, so a row's DOM survives position and data refreshes.
1531
+ const renderedKeys = createMemo<readonly string[]>(() => [...virtualRows().keys()], [], { equals: sameKeys });
1532
+ function virtualRow(key: string): VirtualRow<Row> {
1533
+ const row = virtualRows().get(key);
1534
+ if (!row) throw new Error(`Missing rendered table row: ${key}`);
1535
+ return row;
1536
+ }
1537
+ // Each rendered row reads its own entry signal. Scrolling rebuilds `virtualRows`, but only rows whose item or data changed are notified,
1538
+ // instead of marking every rendered row's reactive subtree stale on every frame.
1539
+ const rowEntries = new Map<string, Signal<VirtualRow<Row>>>();
1540
+ createComputed(() => {
1541
+ const current = virtualRows();
1542
+ for (const [key, entry] of rowEntries) {
1543
+ const next = current.get(key);
1544
+ if (next) entry[1](next);
1545
+ else rowEntries.delete(key);
1546
+ }
1547
+ });
1548
+ function rowEntry(key: string): Accessor<VirtualRow<Row>> {
1549
+ const existing = rowEntries.get(key);
1550
+ if (existing) return existing[0];
1551
+ const entry = createSignal(untrack(() => virtualRow(key)), { equals: (previous, next) => previous.row === next.row && previous.item === next.item });
1552
+ rowEntries.set(key, entry);
1553
+ return entry[0];
1554
+ }
1685
1555
  const [activeRowKey, setActiveRowKey] = createSignal<string | null>(null);
1556
+ let activeRowHint = -1;
1557
+ function activateRow(key: string, index: number): void {
1558
+ activeRowHint = index;
1559
+ setActiveRowKey(key);
1560
+ }
1686
1561
  const focusableRowKey = createMemo<string | null>(() => {
1687
- if (!props.onRowActivate && !selection && !hierarchy && !props.grouping && actions().length === 0) return null;
1562
+ if (!props.onRowActivate && !selection && !treePresentation && actions().length === 0) return null;
1688
1563
  const active = activeRowKey();
1689
- return active && rowIndex(active) >= 0 ? active : rowAt(0)?.key ?? null;
1564
+ return active && rowIndex(active, activeRowHint) >= 0 ? active : rowAt(0)?.key ?? null;
1690
1565
  });
1691
1566
  let focusFrame: number | undefined;
1692
1567
  function focusRow(index: number): void {
1693
1568
  const row = rowAt(index);
1694
1569
  if (!row || !viewport) return;
1695
- setActiveRowKey(row.key);
1570
+ activateRow(row.key, index);
1696
1571
  virtualizer.scrollToIndex(index, { align: "auto" });
1697
1572
  let attempts = 10;
1698
1573
  const realize = (): void => {
@@ -1708,60 +1583,14 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1708
1583
  if (focusFrame !== undefined) cancelAnimationFrame(focusFrame);
1709
1584
  focusFrame = requestAnimationFrame(realize);
1710
1585
  }
1711
- function changeHierarchyExpansion(row: DisplayDataRow<Row>, expanded: boolean): void {
1712
- if (!hierarchy || pending()) return;
1713
- const completion = hierarchy.setExpanded(row.row.id, expanded);
1714
- setHierarchyRevision(revision => revision + 1);
1715
- void completion.finally(() => setHierarchyRevision(revision => revision + 1));
1716
- }
1717
- function retryHierarchy(row: DisplayDataRow<Row>): void {
1718
- if (!hierarchy || pending()) return;
1719
- const completion = hierarchy.retry(row.row.id);
1720
- setHierarchyRevision(revision => revision + 1);
1721
- void completion.finally(() => setHierarchyRevision(revision => revision + 1));
1722
- }
1723
- const [hierarchyMounted, setHierarchyMounted] = createSignal(false);
1724
- onMount(() => { setHierarchyMounted(true); });
1725
- createEffect(() => {
1726
- if (!hierarchy || !hierarchyMounted()) return;
1727
- for (const row of structuredRows()) if (row.kind === "data" && row.expanded && row.unloaded && !row.pending && row.error === null) changeHierarchyExpansion(row, true);
1728
- });
1729
- function handleRowKeyDown(event: KeyboardEvent, row: DisplayRow<Row>): void {
1586
+ function handleRowKeyDown(event: KeyboardEvent, row: DisplayRow<Row>, index: number): void {
1730
1587
  if (event.target !== event.currentTarget || event.altKey) return;
1731
1588
  if (selection && !pending() && row.kind === "data" && (event.ctrlKey || event.metaKey) && !event.shiftKey && event.key.toLowerCase() === "a") {
1732
1589
  event.preventDefault();
1733
1590
  selectLoadedRows(true);
1734
1591
  return;
1735
1592
  }
1736
- if (row.kind === "group" && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === " " || event.key === "Enter")) {
1737
- event.preventDefault();
1738
- setGroupExpanded(row.group.id, !row.expanded);
1739
- return;
1740
- }
1741
- if (row.kind === "group" && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
1742
- event.preventDefault();
1743
- setGroupExpanded(row.group.id, event.key === "ArrowRight");
1744
- return;
1745
- }
1746
- if (hierarchy && row.kind === "data" && row.canExpand && !event.ctrlKey && !event.metaKey && !event.shiftKey && event.key === "ArrowRight") {
1747
- event.preventDefault();
1748
- if (!row.expanded) changeHierarchyExpansion(row, true);
1749
- else {
1750
- const current = rowIndex(row.key);
1751
- const child = rowAt(current + 1);
1752
- if (child?.kind === "data" && child.parentId === row.row.id) focusRow(current + 1);
1753
- }
1754
- return;
1755
- }
1756
- if (hierarchy && row.kind === "data" && !event.ctrlKey && !event.metaKey && !event.shiftKey && event.key === "ArrowLeft") {
1757
- event.preventDefault();
1758
- if (row.expanded) changeHierarchyExpansion(row, false);
1759
- else if (row.parentId) {
1760
- const parent = structuredRows().findIndex(candidate => candidate.kind === "data" && candidate.row.id === row.parentId);
1761
- if (parent >= 0) focusRow(parent);
1762
- }
1763
- return;
1764
- }
1593
+ if (presentation?.keyDown(event, row, index, "table")) return;
1765
1594
  if (selection && !pending() && row.kind === "data" && !event.ctrlKey && !event.metaKey && event.key === " ") {
1766
1595
  event.preventDefault();
1767
1596
  changeRowSelection(row.row.id, !rowSelected(row.row.id), event.shiftKey);
@@ -1773,7 +1602,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1773
1602
  return;
1774
1603
  }
1775
1604
  if (event.ctrlKey || event.metaKey || (event.shiftKey && !selection)) return;
1776
- const current = rowIndex(row.key);
1605
+ const current = rowIndex(row.key, index);
1777
1606
  if (current < 0) return;
1778
1607
  const page = Math.max(1, Math.floor((viewport?.clientHeight ?? estimatedRowHeight()) / estimatedRowHeight()));
1779
1608
  const last = Math.max(0, rowCount() - 1);
@@ -1788,7 +1617,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1788
1617
  event.preventDefault();
1789
1618
  const nextRow = rowAt(next);
1790
1619
  if (selection && row.kind === "data" && event.shiftKey && nextRow?.kind === "data") {
1791
- if (!selectionAnchorId || !selectableRows().rows.some(candidate => candidate.id === selectionAnchorId)) selectionAnchorId = row.row.id;
1620
+ if (!selectionAnchorId || !selectionAnchorLoaded(selectionAnchorId)) selectionAnchorId = row.row.id;
1792
1621
  selection.selectRange(selectionAnchorId, nextRow.row.id, true);
1793
1622
  publishSelection();
1794
1623
  }
@@ -1818,7 +1647,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1818
1647
  const top = viewport.scrollTop;
1819
1648
  const item = virtualizer.getVirtualItems().find(candidate => candidate.end > top);
1820
1649
  const row = item ? rowAt(item.index) : undefined;
1821
- if (item && row) scrollAnchor = { id: row.key, offset: top - item.start };
1650
+ if (item && row) scrollAnchor = { id: row.key, index: item.index, offset: top - item.start };
1822
1651
  return;
1823
1652
  }
1824
1653
  const bounds = viewport.getBoundingClientRect();
@@ -1828,7 +1657,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1828
1657
  const index = Number(row.dataset.index);
1829
1658
  const item = virtualizer.getVirtualItems().find(candidate => candidate.index === index);
1830
1659
  if (!item) return;
1831
- scrollAnchor = { id: row.dataset.rowKey, offset: viewport.scrollTop - item.start };
1660
+ scrollAnchor = { id: row.dataset.rowKey, index, offset: viewport.scrollTop - item.start };
1832
1661
  }
1833
1662
  function scheduleScrollAnchorCapture(): void {
1834
1663
  if (anchorFrame !== undefined) cancelAnimationFrame(anchorFrame);
@@ -1838,15 +1667,15 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1838
1667
  });
1839
1668
  }
1840
1669
  onCleanup(() => { if (anchorFrame !== undefined) cancelAnimationFrame(anchorFrame); });
1841
- const currentRowCollection = (): readonly DisplayRow<Row>[] | readonly Row[] => hierarchy || props.grouping ? structuredRows() : flatResultRows();
1670
+ const currentRowCollection = (): readonly DisplayRow<Row>[] | readonly Row[] => presentation ? presentation.rows() : flatResultRows();
1842
1671
  let previousRows = currentRowCollection();
1843
- let previousState = serializeState(acceptedState(), schema);
1672
+ let previousState = JSON.stringify(acceptedState());
1844
1673
  createEffect(() => {
1845
1674
  const nextRows = currentRowCollection();
1846
- const nextState = serializeState(acceptedState(), schema);
1675
+ const nextState = JSON.stringify(acceptedState());
1847
1676
  const anchor = scrollAnchor;
1848
1677
  if (viewport && anchor && nextRows !== previousRows && nextState === previousState) {
1849
- const index = rowIndex(anchor.id);
1678
+ const index = rowIndex(anchor.id, anchor.index);
1850
1679
  const offset = index < 0 ? undefined : virtualizer.getOffsetForIndex(index, "start")?.[0];
1851
1680
  if (offset !== undefined) viewport.scrollTop = Math.max(0, offset + anchor.offset);
1852
1681
  }
@@ -1856,8 +1685,38 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1856
1685
 
1857
1686
  const range = createMemo(() => {
1858
1687
  const pagination = acceptedState().pagination;
1859
- return pagination === false ? undefined : getPageRange(pagination, result().total);
1688
+ return pagination === false || cursorPagination(pagination) ? undefined : getPageRange(pagination, exactTotal() ?? 0);
1860
1689
  });
1690
+ /** Each step's target is undefined when the accepted page has nothing in that direction. */
1691
+ const cursorSteps = createMemo<readonly CursorStep[] | undefined>(() => {
1692
+ const pagination = acceptedState().pagination;
1693
+ if (!cursorPagination(pagination)) return undefined;
1694
+ const previous = acceptedCursorPage()?.previousCursor ?? null;
1695
+ const next = acceptedCursorPage()?.nextCursor ?? null;
1696
+ return [
1697
+ { label: "firstPage", glyph: "chevrons-left", target: pagination.cursor === null || previous === null ? undefined : null },
1698
+ { label: "previousPage", glyph: "chevron-left", target: previous === null ? undefined : { direction: "before", value: previous } },
1699
+ { label: "nextPage", glyph: "chevron-right", target: next === null ? undefined : { direction: "after", value: next } },
1700
+ ];
1701
+ });
1702
+ /** Cursor APIs expose no page index, so the ordinal is derived from accepted navigation and resets to 1 at the first page. */
1703
+ const cursorPageNumber = createMemo<{ readonly key: string | null; readonly page: number | undefined }>(previous => {
1704
+ const pagination = acceptedState().pagination;
1705
+ const page = acceptedCursorPage();
1706
+ if (!cursorPagination(pagination) || !page) return { key: null, page: undefined };
1707
+ if (pagination.cursor === null || page.previousCursor === null) return { key: null, page: 1 };
1708
+ const key = cursorKey(pagination.cursor);
1709
+ if (key === previous.key) return previous;
1710
+ const prior = previous.page;
1711
+ return { key, page: prior === undefined ? undefined : pagination.cursor.direction === "after" ? prior + 1 : Math.max(2, prior - 1) };
1712
+ }, { key: null, page: undefined });
1713
+ const cursorStatus = (): string => {
1714
+ if (!acceptedCursorPage()) return "";
1715
+ const page = cursorPageNumber().page;
1716
+ return page === undefined
1717
+ ? messages().cursorPageRows.replaceAll("{count}", resultNumber().format(result().rows.length))
1718
+ : theme.messages().pageLabel.replaceAll("{page}", resultNumber().format(page));
1719
+ };
1861
1720
  const mobileRange = createMemo(() => {
1862
1721
  if (!mobileLayout || acceptedState().pagination !== false) return undefined;
1863
1722
  return getPageRange({ pageIndex: mobilePageIndex(), pageSize: mobileLayout.pageSize }, rowCount());
@@ -1931,16 +1790,8 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1931
1790
  selectMobileRows(true);
1932
1791
  return;
1933
1792
  }
1934
- if (row.kind === "group" && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === " " || event.key === "Enter" || event.key === "ArrowRight" || event.key === "ArrowLeft")) {
1935
- event.preventDefault();
1936
- setGroupExpanded(row.group.id, event.key === "ArrowRight" ? true : event.key === "ArrowLeft" ? false : !row.expanded);
1937
- return;
1938
- }
1939
- if (hierarchy && row.kind === "data" && row.canExpand && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
1940
- event.preventDefault();
1941
- changeHierarchyExpansion(row, event.key === "ArrowRight");
1942
- return;
1943
- }
1793
+ const current = mobileRows().findIndex(candidate => candidate.key === row.key);
1794
+ if (presentation?.keyDown(event, row, current, "cards")) return;
1944
1795
  if (selection && !pending() && row.kind === "data" && !event.ctrlKey && !event.metaKey && event.key === " ") {
1945
1796
  event.preventDefault();
1946
1797
  changeRowSelection(row.row.id, !rowSelected(row.row.id), event.shiftKey);
@@ -1952,7 +1803,6 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1952
1803
  return;
1953
1804
  }
1954
1805
  if (event.ctrlKey || event.metaKey || event.shiftKey) return;
1955
- const current = mobileRows().findIndex(candidate => candidate.key === row.key);
1956
1806
  const last = Math.max(0, mobileRows().length - 1);
1957
1807
  const next = event.key === "ArrowDown" ? Math.min(last, current + 1)
1958
1808
  : event.key === "ArrowUp" ? Math.max(0, current - 1)
@@ -1971,7 +1821,6 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1971
1821
  onCheckedChange={checked => { changeRowSelection(cellProps.row.id, checked, selectRange); selectRange = false; }} />
1972
1822
  </td>;
1973
1823
  }
1974
- const treePresentation = Boolean(hierarchy || props.grouping);
1975
1824
  function logicalColumnIndex(id: string): number {
1976
1825
  const index = orderedColumnStates().findIndex(column => column.id === id);
1977
1826
  if (index < 0) throw new Error(`Missing accepted state for table column: ${id}`);
@@ -1979,164 +1828,41 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1979
1828
  }
1980
1829
  function logicalRowIndex(index: number): number {
1981
1830
  const pagination = acceptedState().pagination;
1982
- if (treePresentation || pagination === false) return index + 2;
1983
- return getPageRange(pagination, result().total).start + index + 2;
1831
+ if (treePresentation || pagination === false || cursorPagination(pagination)) return index + 2;
1832
+ return getPageRange(pagination, exactTotal() ?? 0).start + index + 2;
1984
1833
  }
1834
+ // Cursor pages have no known absolute offset, so they report an unknown row count like tree presentations.
1985
1835
  const logicalRowCount = (): number | undefined => rowCount() === 0
1986
1836
  ? undefined
1987
- : treePresentation ? -1 : result().total + 1 + (hasFooter() ? 1 : 0);
1988
- const footerRowIndex = (): number => treePresentation ? rowCount() + 2 : result().total + 2;
1989
- function expansionLabel(row: DisplayDataRow<Row>): string {
1990
- return `${row.expanded ? messages().collapse : messages().expand} ${row.row.id}`;
1991
- }
1992
- function EditableCellValue(cellProps: { readonly row: DisplayDataRow<Row>; readonly column: (typeof columnRecords)[number]; readonly record: CellEditRecord }): JSX.Element {
1993
- const editor = cellProps.column.definition.editor;
1994
- const accessor = cellProps.column.definition.accessor;
1995
- if (!editor || !accessor) throw new Error(`Editable cell ${cellProps.row.row.id}/${cellProps.column.definition.id} is missing its editor`);
1996
- const activeEditor = editor;
1997
- const id = createUniqueId();
1998
- let editorElement: HTMLInputElement | HTMLSelectElement | undefined;
1999
- let restingElement: HTMLSpanElement | undefined;
2000
- let restoringRestingFocus = false;
2001
- let incoming = accessor(cellProps.row.row.value());
2002
- const snapshot = (): CellEditSnapshot<ColumnValue, string> => {
2003
- cellProps.record.revision();
2004
- return cellProps.record.controller.getSnapshot();
2005
- };
2006
- const draft = (): ColumnValue => snapshot().draft?.value ?? snapshot().committed;
2007
- const label = () => messages().editCell.replaceAll("{column}", cellProps.column.definition.header).replaceAll("{id}", cellProps.row.row.id);
2008
- const message = () => {
2009
- const current = snapshot();
2010
- if (current.invalid) return current.invalid;
2011
- if (current.conflict) return messages().cellConflict.replaceAll("{value}", current.conflict.current === null ? messages().noValue : String(current.conflict.current));
2012
- return current.error ? messages().cellUpdateFailedDescription : null;
2013
- };
2014
- const content = () => cellProps.column.definition.cell?.(snapshot().committed, cellProps.row.row.value()) ?? defaultCell(snapshot().committed);
2015
-
2016
- createEffect(() => {
2017
- const next = accessor(cellProps.row.row.value());
2018
- if (Object.is(next, incoming)) return;
2019
- incoming = next;
2020
- cellProps.record.controller.acceptRefetch(next);
2021
- cellProps.record.publish();
2022
- });
2023
-
2024
- function focusEditor(): void { queueMicrotask(() => editorElement?.focus({ preventScroll: true })); }
2025
- function focusResting(): void {
2026
- queueMicrotask(() => {
2027
- restoringRestingFocus = true;
2028
- try { restingElement?.focus({ preventScroll: true }); }
2029
- finally { restoringRestingFocus = false; }
2030
- });
2031
- }
2032
- function begin(): void {
2033
- if (restoringRestingFocus || pending()) return;
2034
- if (cellProps.record.controller.begin()) {
2035
- cellProps.record.publish();
2036
- focusEditor();
2037
- }
2038
- }
2039
- function update(value: ColumnValue): void {
2040
- cellProps.record.controller.setDraft(value);
2041
- cellProps.record.publish();
2042
- }
2043
- async function finish(completion: Promise<CellCommitOutcome>, restore: boolean, notify = true): Promise<CellCommitOutcome> {
2044
- cellProps.record.publish();
2045
- const outcome = await completion;
2046
- cellProps.record.publish();
2047
- const current = snapshot();
2048
- if (outcome === "accepted" && !current.editing && restore) focusResting();
2049
- if ((outcome === "invalid" || outcome === "conflict") && restore) focusEditor();
2050
- if (outcome === "failed" && notify && editToaster) editToaster.show({
2051
- title: messages().cellUpdateFailed,
2052
- description: messages().cellUpdateFailedDescription,
2053
- tone: "danger",
2054
- priority: "assertive",
2055
- duration: null,
2056
- action: {
2057
- label: messages().retry,
2058
- retryLabel: messages().retry,
2059
- errorMessage: messages().retryFailed,
2060
- run: async () => {
2061
- const retried = await finish(cellProps.record.controller.retry(), false, false);
2062
- if (retried !== "accepted") throw new Error(`Cell retry was not accepted: ${retried}`);
2063
- focusResting();
2064
- },
2065
- },
2066
- });
2067
- return outcome;
2068
- }
2069
- function commit(restore: boolean): void { void finish(cellProps.record.controller.commit(), restore); }
2070
- function blur(): void {
2071
- const current = snapshot();
2072
- const unchangedFailure = (current.error !== null || current.conflict !== null) && current.attempt !== null && current.draft !== null && Object.is(current.attempt.value, current.draft.value);
2073
- if (!unchangedFailure) commit(false);
2074
- }
2075
- function keyDown(event: KeyboardEvent): void {
2076
- if (event.key === "Enter") {
2077
- event.preventDefault();
2078
- commit(true);
2079
- } else if (event.key === "Escape") {
2080
- event.preventDefault();
2081
- cellProps.record.controller.discard();
2082
- cellProps.record.publish();
2083
- focusResting();
2084
- }
2085
- }
2086
- function EditorControl(): JSX.Element {
2087
- const invalid = () => snapshot().invalid !== null || snapshot().error !== null || undefined;
2088
- const describedBy = () => message() ? `${id}-message` : undefined;
2089
- if (activeEditor.type === "boolean") return <input ref={element => { editorElement = element; element.checked = draft() === true; }} class="sheen-data-table-editor sheen-data-table-editor-boolean" type="checkbox"
2090
- aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown} onChange={event => update(event.currentTarget.checked)} />;
2091
- if (activeEditor.type === "select") return <select ref={element => { editorElement = element; element.value = draft() === null ? "" : String(draft()); }} class="sheen-data-table-editor"
2092
- aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown} onChange={event => update(event.currentTarget.value === "" && activeEditor.nullable ? null : event.currentTarget.value)}>
2093
- <Show when={activeEditor.nullable}><option value="">{messages().noValue}</option></Show>
2094
- <For each={activeEditor.options}>{option => <option value={option}>{option}</option>}</For>
2095
- </select>;
2096
- if (activeEditor.type === "number") return <input ref={element => { editorElement = element; element.value = draft() === null ? "" : String(draft()); }} class="sheen-data-table-editor" type="number" inputMode="decimal"
2097
- aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown}
2098
- onInput={event => update(event.currentTarget.value === "" ? null : event.currentTarget.valueAsNumber)} />;
2099
- return <input ref={element => { editorElement = element; element.value = draft() === null ? "" : String(draft()); }} class="sheen-data-table-editor" type="text"
2100
- aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown}
2101
- onInput={event => update(event.currentTarget.value === "" && activeEditor.nullable ? null : event.currentTarget.value)} />;
1837
+ : treePresentation || cursorMode ? -1 : (exactTotal() ?? 0) + 1 + (hasFooter() ? 1 : 0);
1838
+ const footerRowIndex = (): number => treePresentation || cursorMode ? rowCount() + 2 : (exactTotal() ?? 0) + 2;
1839
+ function bindCell(row: () => DisplayDataRow<Row> | undefined, column: (typeof columnRecords)[number]): DataTableCellBinding<Row> | undefined {
1840
+ for (const extension of cellExtensions) {
1841
+ const binding = extension(row, column.definition);
1842
+ if (binding) return binding;
2102
1843
  }
2103
- return <span class="sheen-data-table-edit-value">
2104
- <Show when={snapshot().editing} fallback={<span ref={element => { restingElement = element; element.addEventListener("focus", begin); if (element.ownerDocument.activeElement === element) queueMicrotask(begin); }} class="sheen-data-table-edit-rest" tabindex="0" aria-keyshortcuts="Enter" onClick={begin}
2105
- onKeyDown={event => { if (event.key === "Enter") { event.preventDefault(); begin(); } }}>{content()}</span>}>
2106
- <EditorControl />
2107
- </Show>
2108
- <Show when={message()}>{value => <span id={`${id}-message`} class="sheen-data-table-edit-message" role={snapshot().invalid !== null || snapshot().conflict !== null ? "alert" : undefined}>{value()}</span>}</Show>
2109
- </span>;
2110
- }
2111
- function DataCellContent(cellProps: { readonly row: DisplayDataRow<Row>; readonly column: (typeof columnRecords)[number]; readonly first: boolean; readonly edit: CellEditRecord | undefined }): JSX.Element {
1844
+ return undefined;
1845
+ }
1846
+ function DataCellContent(cellProps: { readonly row: DisplayDataRow<Row>; readonly column: (typeof columnRecords)[number]; readonly first: boolean; readonly cell: DataTableCellBinding<Row> | undefined; readonly host: () => HTMLElement | undefined }): JSX.Element {
2112
1847
  const definition = cellProps.column.definition;
2113
1848
  const input = createMemo(() => {
2114
1849
  const row = cellProps.row.row.value();
2115
1850
  return { row, value: definition.accessor?.(row) ?? null };
2116
1851
  }, undefined, { equals: (previous, next) => Object.is(previous.value, next.value) && (definition.cell === null
2117
1852
  || (definition.cellDependencies === null ? previous.row === next.row : definition.cellDependencies.every(key => Object.is(previous.row[key], next.row[key])))) });
2118
- const content = () => cellProps.edit ? <EditableCellValue row={cellProps.row} column={cellProps.column} record={cellProps.edit} /> : definition.cell?.(input().value, input().row) ?? defaultCell(input().value);
2119
- if (!treePresentation || !cellProps.first) return <>{content()}</>;
2120
- return <div class="sheen-data-table-tree-cell" style={{ "--sheen-table-depth": Math.max(0, cellProps.row.depth - 1) }}>
2121
- <Show when={cellProps.row.canExpand} fallback={<span class="sheen-data-table-expander-space" aria-hidden="true" />}>
2122
- <button type="button" class="sheen-data-table-expander" aria-label={expansionLabel(cellProps.row)} aria-expanded={cellProps.row.expanded} disabled={pending()}
2123
- onClick={() => changeHierarchyExpansion(cellProps.row, !cellProps.row.expanded)}>{cellProps.row.expanded ? "▾" : "▸"}</button>
2124
- </Show>
2125
- <span class="sheen-data-table-tree-value">{content()}</span>
2126
- <Show when={cellProps.row.pending}><span class="sheen-data-table-row-status" role="status">{messages().loadingChildren}</span></Show>
2127
- <Show when={cellProps.row.error !== null}><span class="sheen-data-table-row-status" role="alert">{messages().serverError} <button type="button" onClick={() => retryHierarchy(cellProps.row)}>{messages().retry}</button></span></Show>
2128
- </div>;
1853
+ if (definition.flash) createEffect(on(() => ({ id: cellProps.row.row.id, value: input().value }), (next, previous) => {
1854
+ const element = cellProps.host();
1855
+ if (!element || !previous || previous.id !== next.id || typeof next.value !== "number" || typeof previous.value !== "number" || next.value === previous.value) return;
1856
+ flashChange(element, next.value > previous.value ? "up" : "down");
1857
+ }, { defer: true }));
1858
+ const content = () => cellProps.cell?.active() ? cellProps.cell.render(() => cellProps.row) : definition.cell?.(input().value, input().row) ?? defaultCell(input().value);
1859
+ const TreeCell = presentation?.TreeCell;
1860
+ if (!TreeCell || !cellProps.first) return <>{content()}</>;
1861
+ return <TreeCell row={cellProps.row}>{content()}</TreeCell>;
2129
1862
  }
2130
1863
  function GroupCellContent(cellProps: { readonly row: DisplayGroupRow<Row>; readonly column: (typeof columnRecords)[number]; readonly labelColumn: boolean }): JSX.Element {
2131
- if (cellProps.labelColumn) return <div class="sheen-data-table-tree-cell" style={{ "--sheen-table-depth": 0 }}>
2132
- <Show when={props.grouping?.collapsible !== false} fallback={<span class="sheen-data-table-expander-space" aria-hidden="true" />}>
2133
- <button type="button" class="sheen-data-table-expander" disabled={pending()} aria-label={`${cellProps.row.expanded ? messages().collapse : messages().expand} ${cellProps.row.label}`}
2134
- aria-expanded={cellProps.row.expanded} onClick={() => setGroupExpanded(cellProps.row.group.id, !cellProps.row.expanded)}>{cellProps.row.expanded ? "▾" : "▸"}</button>
2135
- </Show>
2136
- <span class="sheen-data-table-group-label">{cellProps.row.label} <span class="sheen-data-table-group-count">({groupNumberFormatter().format(cellProps.row.group.count)})</span></span>
2137
- </div>;
2138
- const aggregate = cellProps.row.group.aggregates.find(value => value.column === cellProps.column.definition.id)?.value ?? null;
2139
- return defaultCell(aggregate);
1864
+ const GroupCell = presentation?.GroupCell;
1865
+ return GroupCell ? <GroupCell row={cellProps.row} column={cellProps.column.definition} label={cellProps.labelColumn} /> : null;
2140
1866
  }
2141
1867
  function MobileSelectionControl(controlProps: { readonly row: StableRow<Row> }): JSX.Element {
2142
1868
  let selectRange = false;
@@ -2146,21 +1872,15 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2146
1872
  }
2147
1873
  function MobileCellContent(cellProps: { readonly row: DisplayRow<Row>; readonly column: (typeof columnRecords)[number]; readonly title: boolean }): JSX.Element {
2148
1874
  const data = () => displayDataRow(cellProps.row);
2149
- const edit = createMemo(() => {
2150
- const current = data();
2151
- return current ? cellEditRecord(current.row, cellProps.column) : undefined;
2152
- });
2153
- const state = () => editSnapshot(edit());
2154
- const invalid = () => {
2155
- const current = state();
2156
- return Boolean(current && (current.invalid !== null || current.error !== null));
2157
- };
1875
+ const cell = bindCell(data, cellProps.column);
1876
+ const attributes = (): DataTableCellAttributes => cell?.attributes() ?? {};
1877
+ let host: HTMLDivElement | undefined;
2158
1878
  return <Show when={data()} fallback={<Show when={displayGroupRow(cellProps.row)}>{group => <div class="sheen-data-table-mobile-value" data-column={cellProps.column.definition.id} data-align={cellProps.column.definition.align} data-numeric={cellProps.column.definition.numeric || undefined}>
2159
1879
  <GroupCellContent row={group()} column={cellProps.column} labelColumn={cellProps.title} />
2160
1880
  </div>}</Show>}>
2161
- {current => <div class="sheen-data-table-mobile-value" data-column={cellProps.column.definition.id} data-align={cellProps.column.definition.align} data-numeric={cellProps.column.definition.numeric || undefined}
2162
- data-editable={edit() ? "" : undefined} data-invalid={invalid() ? "" : undefined} data-stale={state()?.stale ? "" : undefined} data-pending={state()?.pending ? "" : undefined} data-conflict={state()?.conflict ? "" : undefined}>
2163
- <DataCellContent row={current()} column={cellProps.column} first={cellProps.title} edit={edit()} />
1881
+ {current => <div ref={host} class="sheen-data-table-mobile-value" data-column={cellProps.column.definition.id} data-align={cellProps.column.definition.align} data-numeric={cellProps.column.definition.numeric || undefined}
1882
+ data-editable={attributes()["data-editable"]} data-invalid={attributes()["data-invalid"]} data-stale={attributes()["data-stale"]} data-pending={attributes()["data-pending"]} data-conflict={attributes()["data-conflict"]}>
1883
+ <DataCellContent row={current()} column={cellProps.column} first={cellProps.title} cell={cell} host={() => host} />
2164
1884
  </div>}
2165
1885
  </Show>;
2166
1886
  }
@@ -2174,7 +1894,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2174
1894
  <div class="sheen-data-table-mobile-title">
2175
1895
  <Show when={title()} fallback={data()?.row.id ?? displayGroupRow(cardProps.row)?.label ?? ""}>{column => <MobileCellContent row={cardProps.row} column={column()} title />}</Show>
2176
1896
  </div>
2177
- <Show when={data()}>{value => <Show when={actions().length > 0}><DropdownMenu trigger={messages().rowActions.replaceAll("{id}", value().row.id)} items={rowActionItems(value().row)} disabled={pending()} /></Show>}</Show>
1897
+ <Show when={data()}>{value => <Show when={actions().length > 0}><DropdownMenu trigger={<Glyph name="more" />} triggerLabel={messages().rowActions.replaceAll("{id}", value().row.id)} items={rowActionItems(value().row)} disabled={pending()} /></Show>}</Show>
2178
1898
  </div>
2179
1899
  <Show when={details().length > 0}><dl class="sheen-data-table-mobile-fields">
2180
1900
  <For each={details()}>{column => <div class="sheen-data-table-mobile-field">
@@ -2184,18 +1904,17 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2184
1904
  </dl></Show>
2185
1905
  </>;
2186
1906
  }
2187
- return <section ref={root} class={className()} data-variant={variant()} data-sheen-density={density()} data-mobile-layout={mobileLayout ? "" : undefined} data-variable-height={props.variableRowHeight ? "" : undefined} data-selection={selection ? "multiple" : undefined} data-pending={busy() ? "" : undefined} data-previous-results={previous() ? "" : undefined} aria-busy={busy() || undefined} style={{ "--sheen-data-table-initial-viewport-height": `${initialViewportHeight}px` }}>
1907
+ return <section ref={root} class={className()} data-variant={variant()} data-sheen-density={density()} data-mobile-layout={mobileLayout ? "" : undefined} data-variable-height={props.variableRowHeight ? "" : undefined} data-selection={selection ? "multiple" : undefined} data-pending={busy() ? "" : undefined} data-previous-results={previous() ? "" : undefined} aria-busy={busy() || undefined} style={{ "--sheen-data-table-initial-viewport-height": `${initialViewportHeight}px`, ...(props.rowHeight === undefined ? {} : { "--sheen-table-row-h": props.rowHeight }) }}>
2188
1908
  <Show when={acceptedAvailable() ? error() : null}>{value => <div class="sheen-data-table-error" role="alert"><span>{errorMessage(value())}</span><Button onClick={retry}>{messages().retry}</Button></div>}</Show>
2189
1909
  <Show when={exportError()}><div class="sheen-data-table-error" role="alert"><span>{messages().exportFailed}</span><Show when={serverExports}><Button onClick={retryExport}>{messages().retryExport}</Button></Show></div></Show>
2190
1910
  <DataTableToolbar label={messages().tableControls.replace("{caption}", props.caption)} result={resultCount()} resultPrevious={previous() ? messages().previousResults : undefined} actions={toolbarActions()}
2191
- query={searchOptions || (props.filterBar !== false && schema.filterColumns.length > 0) || columnSummaries().length > 0 ? <>
1911
+ query={searchOptions || queryExtensions.some(query => query.visible()) || columnSummaries().length > 0 ? <>
2192
1912
  <Show when={searchOptions}><div class="sheen-data-table-search-field" data-search-mode={searchMode()}><SearchInput class="sheen-data-table-search" label={searchLabel()} placeholder={searchPlaceholder()} value={searchDraft()} shortcut={searchShortcut()} aria-busy={busy() || undefined}
2193
1913
  onValueChange={updateSearchDraft} onCompositionStart={startSearchComposition} onCompositionEnd={event => finishSearchComposition(event.currentTarget.value)} />
2194
1914
  <Show when={searchOptions?.exactMatch}><DropdownMenu class="sheen-data-table-search-mode-menu" trigger={<span>{searchMode() === "exact" ? messages().searchExact : messages().searchRanked}</span>}
2195
1915
  triggerLabel={`${messages().searchMatchMode}: ${searchMode() === "exact" ? messages().searchExact : messages().searchRanked}`} items={searchModeItems()} disabled={pending()} /></Show>
2196
1916
  </div></Show>
2197
- <Show when={props.filterBar !== false && schema.filterColumns.length > 0}><FilterBar columns={props.columns} value={acceptedState().filter} facets={result().facets} disabled={pending()} onChange={requestFilter}
2198
- {...(typeof props.filterBar === "object" && props.filterBar.dateEditor ? { dateEditor: props.filterBar.dateEditor } : {})} /></Show>
1917
+ <For each={queryExtensions}>{query => <Show when={query.visible()}>{query.render()}</Show>}</For>
2199
1918
  <Show when={columnSummaries().length > 0}><div class="sheen-data-table-constraints" role="group" aria-label={messages().constrainedColumns}>
2200
1919
  <For each={columnSummaries().map(item => item.column)}>{id => <span class="sheen-data-table-constraint"><span>{summaryLabel(id)}</span><Button size="sm" variant="ghost" aria-label={messages().restoreColumn.replaceAll("{column}", columnRecordById.get(id)?.definition.header ?? id)} onClick={() => restoreSummary(id)}>{messages().showColumn}</Button></span>}</For>
2201
1920
  </div></Show>
@@ -2210,9 +1929,9 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2210
1929
  <thead><tr aria-rowindex="1" style={{ "grid-template-columns": template() }}>
2211
1930
  <Show when={selection}><th class="sheen-data-table-selection-cell" scope="col" role={treePresentation ? "columnheader" : undefined} aria-colindex="1">
2212
1931
  <Checkbox data-sheen-selection-control="" class="sheen-data-table-selection-control" label={messages().selectPage}
2213
- checked={selectableRows().rows.length > 0 && selectedLoadedCount() === selectableRows().rows.length}
2214
- indeterminate={selectedLoadedCount() > 0 && selectedLoadedCount() < selectableRows().rows.length}
2215
- disabled={pending() || selectableRows().rows.length === 0} onCheckedChange={selectLoadedRows} />
1932
+ checked={loadedRows().length > 0 && selectedLoadedCount() === loadedRows().length}
1933
+ indeterminate={selectedLoadedCount() > 0 && selectedLoadedCount() < loadedRows().length}
1934
+ disabled={pending() || loadedRows().length === 0} onCheckedChange={selectLoadedRows} />
2216
1935
  </th></Show>
2217
1936
  <For each={visibleDefinitions()}>{column => {
2218
1937
  const sorted = () => acceptedState().sorting.find(entry => entry.column === column.definition.id);
@@ -2228,11 +1947,11 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2228
1947
  const reportedWidth = () => column.state().width ?? (typeof column.definition.width === "number" ? column.definition.width : column.definition.minWidth ?? 160);
2229
1948
  return <th scope="col" role={treePresentation ? "columnheader" : undefined} aria-colindex={logicalColumnIndex(column.definition.id)} data-column={column.definition.id} data-pin={column.state().pin || undefined} data-pin-edge={pinEdge(column)} data-sort-direction={sorted()?.direction} data-sort-priority={sorted() ? sortPosition() : undefined} style={pinStyle(column)}
2230
1949
  aria-sort={sortPosition() === 1 ? sorted()?.direction === "asc" ? "ascending" : sorted()?.direction === "desc" ? "descending" : undefined : undefined}>
2231
- <div class="sheen-data-table-header-content">
1950
+ <div class="sheen-data-table-header-content" title={column.definition.header}>
2232
1951
  <Show when={column.definition.sort} fallback={<span class="sheen-data-table-header-label">{column.definition.header}</span>}>
2233
1952
  <button class="sheen-data-table-sort" type="button" disabled={pending()} aria-describedby={column.sortDescriptionId} onClick={event => requestSort(column.definition.id, event.shiftKey)}>
2234
1953
  <span class="sheen-data-table-sort-label">{column.definition.header}</span>
2235
- <Show when={sorted()}>{value => <span class="sheen-data-table-sort-indicator" aria-hidden="true"><span class="sheen-data-table-sort-direction">{value().direction === "asc" ? "↑" : "↓"}</span><Show when={acceptedState().sorting.length > 1}><span class="sheen-data-table-sort-priority">{sortPosition()}</span></Show></span>}</Show>
1954
+ <Show when={sorted()}>{value => <span class="sheen-data-table-sort-indicator" aria-hidden="true"><span class="sheen-data-table-sort-direction"><Glyph name={value().direction === "asc" ? "chevron-up" : "chevron-down"} /></span><Show when={acceptedState().sorting.length > 1}><span class="sheen-data-table-sort-priority">{sortPosition()}</span></Show></span>}</Show>
2236
1955
  </button>
2237
1956
  <span id={column.sortDescriptionId} class="sheen-data-table-state-label">{sortDescription()}</span>
2238
1957
  </Show>
@@ -2261,15 +1980,17 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2261
1980
  <Show when={bodyState() === "empty"}><EmptyState kind="empty" /></Show>
2262
1981
  </td></tr></tbody>}>
2263
1982
  <tbody style={{ height: `${virtualizer.getTotalSize()}px` }}>
2264
- <For each={renderedRows()}>{current => {
2265
- const row = () => current.row();
1983
+ <For each={renderedKeys()}>{key => {
1984
+ const entry = rowEntry(key);
1985
+ const row = createMemo(() => entry().row);
1986
+ const item = createMemo(() => entry().item);
2266
1987
  const dataRow = treePresentation ? () => displayDataRow(row()) : createMemo(() => displayDataRow(row()), undefined, {
2267
1988
  equals: (previous, next) => previous?.row === next?.row,
2268
1989
  });
2269
1990
  const groupRow = () => displayGroupRow(row());
2270
1991
  const labelColumn = () => {
2271
1992
  const visible = visibleDefinitions();
2272
- return visible.some(column => column.definition.id === props.grouping?.by) ? props.grouping?.by : visible[0]?.definition.id;
1993
+ return visible.some(column => column.definition.id === presentation?.labelColumn) ? presentation?.labelColumn : visible[0]?.definition.id;
2273
1994
  };
2274
1995
  function RowCells(): JSX.Element {
2275
1996
  return <>
@@ -2279,59 +2000,53 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2279
2000
  </Show>
2280
2001
  </Show>
2281
2002
  <For each={visibleDefinitions()}>{column => {
2282
- const edit = column.definition.editor ? createMemo(() => {
2283
- const value = dataRow();
2284
- return value ? cellEditRecord(value.row, column) : undefined;
2285
- }) : () => undefined;
2286
- const state = () => editSnapshot(edit());
2287
- const invalid = () => {
2288
- const currentState = state();
2289
- return Boolean(currentState && (currentState.invalid !== null || currentState.error !== null));
2290
- };
2291
- return <td role={treePresentation ? "gridcell" : undefined} aria-colindex={logicalColumnIndex(column.definition.id)} data-column={column.definition.id} data-pin={column.state().pin || undefined} data-pin-edge={pinEdge(column)} style={pinStyle(column)} data-align={column.definition.align} data-numeric={column.definition.numeric || undefined}
2292
- data-editable={edit() ? "" : undefined} data-invalid={invalid() ? "" : undefined}
2293
- data-stale={state()?.stale ? "" : undefined} data-pending={state()?.pending ? "" : undefined} data-conflict={state()?.conflict ? "" : undefined}>
2003
+ const cell = bindCell(dataRow, column);
2004
+ const attributes = (): DataTableCellAttributes => cell?.attributes() ?? {};
2005
+ let host: HTMLTableCellElement | undefined;
2006
+ return <td ref={host} role={treePresentation ? "gridcell" : undefined} aria-colindex={logicalColumnIndex(column.definition.id)} data-column={column.definition.id} data-pin={column.state().pin || undefined} data-pin-edge={pinEdge(column)} style={pinStyle(column)} data-align={column.definition.align} data-numeric={column.definition.numeric || undefined}
2007
+ data-editable={attributes()["data-editable"]} data-invalid={attributes()["data-invalid"]}
2008
+ data-stale={attributes()["data-stale"]} data-pending={attributes()["data-pending"]} data-conflict={attributes()["data-conflict"]}>
2294
2009
  <Show when={dataRow()} fallback={<Show when={groupRow()}>{value => <GroupCellContent row={value()} column={column} labelColumn={column.definition.id === labelColumn()} />}</Show>}>
2295
- {value => <DataCellContent row={value()} column={column} first={column === visibleDefinitions()[0]} edit={edit()} />}
2010
+ {value => <DataCellContent row={value()} column={column} first={column === visibleDefinitions()[0]} cell={cell} host={() => host} />}
2296
2011
  </Show>
2297
2012
  </td>;
2298
2013
  }}</For>
2299
2014
  </>;
2300
2015
  }
2301
- if (props.actions === undefined) return <tr data-row-key={current.key} data-row-id={dataRow()?.row.id} data-group-id={groupRow()?.group.id}
2302
- data-index={current.item().index} data-selected={dataRow() && rowSelected(dataRow()?.row.id ?? "") ? "" : undefined}
2016
+ if (props.actions === undefined) return <tr data-row-key={key} data-row-id={dataRow()?.row.id} data-group-id={groupRow()?.group.id}
2017
+ data-index={item().index} data-selected={dataRow() && rowSelected(dataRow()?.row.id ?? "") ? "" : undefined}
2303
2018
  data-loading={dataRow()?.pending ? "" : undefined} data-load-error={dataRow() && dataRow()?.error !== null ? "" : undefined}
2304
- tabIndex={focusableRowKey() === current.key ? 0 : props.onRowActivate || selection || treePresentation ? -1 : undefined}
2305
- aria-rowindex={logicalRowIndex(current.item().index)}
2019
+ tabIndex={focusableRowKey() === key ? 0 : props.onRowActivate || selection || treePresentation ? -1 : undefined}
2020
+ aria-rowindex={logicalRowIndex(item().index)}
2306
2021
  aria-level={treePresentation ? dataRow()?.depth ?? 1 : undefined}
2307
2022
  aria-posinset={treePresentation ? row().position : undefined} aria-setsize={treePresentation ? row().setSize : undefined}
2308
2023
  aria-expanded={groupRow()?.expanded ?? (dataRow()?.canExpand ? dataRow()?.expanded : undefined)}
2309
2024
  aria-selected={selection && dataRow() ? rowSelected(dataRow()?.row.id ?? "") : undefined}
2310
2025
  aria-busy={dataRow()?.pending ? true : undefined}
2311
- onFocus={() => setActiveRowKey(current.key)} onKeyDown={event => handleRowKeyDown(event, row())} onClick={event => handleRowClick(event, row())}
2312
- ref={element => bindVirtualRow(element, current.item().index)}
2313
- style={{ "grid-template-columns": template(), transform: `translateY(${current.item().start}px)`, "block-size": props.variableRowHeight ? undefined : rowHeight, "min-block-size": rowHeight }}>
2026
+ onFocus={() => activateRow(key, item().index)} onKeyDown={event => handleRowKeyDown(event, row(), item().index)} onClick={event => handleRowClick(event, row())}
2027
+ ref={element => bindVirtualRow(element, item().index)}
2028
+ style={{ "grid-template-columns": template(), transform: `translateY(${item().start}px)`, "block-size": props.variableRowHeight ? undefined : rowHeight, "min-block-size": rowHeight }}>
2314
2029
  <RowCells />
2315
2030
  </tr>;
2316
2031
  const contextRow = dataRow();
2317
2032
  return <ContextMenu as="tr" items={contextRow ? rowActionItems(contextRow.row) : []} disabled={!contextRow || actions().length === 0 || pending()}
2318
2033
  onContextMenu={() => { const value = dataRow(); if (value) prepareContextSelection(value.row); }}
2319
- data-row-key={current.key} data-row-id={dataRow()?.row.id} data-group-id={groupRow()?.group.id}
2320
- data-index={current.item().index} data-selected={dataRow() && rowSelected(dataRow()?.row.id ?? "") ? "" : undefined}
2034
+ data-row-key={key} data-row-id={dataRow()?.row.id} data-group-id={groupRow()?.group.id}
2035
+ data-index={item().index} data-selected={dataRow() && rowSelected(dataRow()?.row.id ?? "") ? "" : undefined}
2321
2036
  data-loading={dataRow()?.pending ? "" : undefined} data-load-error={dataRow() && dataRow()?.error !== null ? "" : undefined}
2322
- tabIndex={focusableRowKey() === current.key ? 0 : props.onRowActivate || selection || treePresentation || actions().length > 0 ? -1 : undefined}
2323
- aria-rowindex={logicalRowIndex(current.item().index)}
2037
+ tabIndex={focusableRowKey() === key ? 0 : props.onRowActivate || selection || treePresentation || actions().length > 0 ? -1 : undefined}
2038
+ aria-rowindex={logicalRowIndex(item().index)}
2324
2039
  aria-level={treePresentation ? dataRow()?.depth ?? 1 : undefined}
2325
2040
  aria-posinset={treePresentation ? row().position : undefined} aria-setsize={treePresentation ? row().setSize : undefined}
2326
2041
  aria-expanded={groupRow()?.expanded ?? (dataRow()?.canExpand ? dataRow()?.expanded : undefined)}
2327
2042
  aria-selected={selection && dataRow() ? rowSelected(dataRow()?.row.id ?? "") : undefined}
2328
2043
  aria-busy={dataRow()?.pending ? true : undefined}
2329
- onFocus={() => setActiveRowKey(current.key)} onKeyDown={event => handleRowKeyDown(event, row())} onClick={event => handleRowClick(event, row())}
2044
+ onFocus={() => activateRow(key, item().index)} onKeyDown={event => handleRowKeyDown(event, row(), item().index)} onClick={event => handleRowClick(event, row())}
2330
2045
  ref={element => {
2331
2046
  if (!(element instanceof HTMLTableRowElement)) throw new Error("DataTable context rows must render as table rows");
2332
- bindVirtualRow(element, current.item().index);
2047
+ bindVirtualRow(element, item().index);
2333
2048
  }}
2334
- style={{ "grid-template-columns": template(), transform: `translateY(${current.item().start}px)`, "block-size": props.variableRowHeight ? undefined : rowHeight, "min-block-size": rowHeight }}>
2049
+ style={{ "grid-template-columns": template(), transform: `translateY(${item().start}px)`, "block-size": props.variableRowHeight ? undefined : rowHeight, "min-block-size": rowHeight }}>
2335
2050
  <RowCells />
2336
2051
  </ContextMenu>;
2337
2052
  }}</For>
@@ -2385,7 +2100,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2385
2100
  </Show>
2386
2101
  </div></Show>
2387
2102
  <Show when={selectionBarPresent()}><div class="sheen-data-table-selection-actions" data-open={String(selectionBarOpen())} role="toolbar" aria-label={messages().selectionActions} aria-hidden={!selectionBarOpen() || undefined} inert={!selectionBarOpen()} onAnimationEnd={finishSelectionBarExit}>
2388
- <strong>{messages().selectedCount.replaceAll("{count}", groupNumberFormatter().format(selectionCount()))}</strong>
2103
+ <strong>{messages().selectedCount.replaceAll("{count}", resultNumber().format(selectionCount()))}</strong>
2389
2104
  <For each={actions()}>{action => {
2390
2105
  const context = () => actionContext();
2391
2106
  return <Button size="sm" tone={action.tone ?? "neutral"} disabled={actionDisabled(action, context())} onClick={() => action.onSelect(actionContext())}>{action.label}</Button>;
@@ -2394,6 +2109,15 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2394
2109
  </div></Show>
2395
2110
  </div>
2396
2111
  <Show when={range()}>{page => <Pagination class="sheen-data-table-pagination" pageIndex={page().pageIndex} pageCount={page().pageCount} pending={busy()} disabled={previous()} onPageChange={requestPage} />}</Show>
2397
- <Show when={editToaster}>{controller => <Toaster controller={controller()} />}</Show>
2112
+ <Show when={cursorSteps()}>{steps => <nav class="sheen-pagination sheen-data-table-pagination" aria-label={theme.messages().pagination} aria-busy={busy() || undefined} aria-disabled={previous() || undefined} data-pending={busy() ? "" : undefined}>
2113
+ <Index each={steps()}>{step => {
2114
+ // Index keeps each button node, so focus survives the accepted page change. aria-disabled keeps it in Tab order.
2115
+ const unavailable = () => step().target === undefined || busy() || previous() || undefined;
2116
+ return <Button variant="ghost" class="sheen-pagination-step" aria-label={theme.messages()[step().label]} aria-disabled={unavailable()}
2117
+ onClick={() => { const target = step().target; if (target !== undefined && !unavailable()) requestCursor(target); }}><Glyph name={step().glyph} /></Button>;
2118
+ }}</Index>
2119
+ <output aria-live="polite" aria-atomic="true">{cursorStatus()}</output>
2120
+ </nav>}</Show>
2121
+ <For each={overlays}>{overlay => overlay()}</For>
2398
2122
  </section>;
2399
2123
  }