@gemologic/sheen-table 0.2.1 → 0.3.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 (50) hide show
  1. package/dist/DataTable.d.ts +4 -0
  2. package/dist/DataTable.js +1154 -1628
  3. package/dist/DataTableToolbar.js +1 -2
  4. package/dist/FilterBar.d.ts +3 -0
  5. package/dist/FilterBar.js +127 -108
  6. package/dist/QueryBuilder.js +72 -68
  7. package/dist/cell-edit.js +1 -2
  8. package/dist/client-state.js +20 -21
  9. package/dist/client-view.js +12 -13
  10. package/dist/column-layout.js +1 -2
  11. package/dist/columns.d.ts +5 -1
  12. package/dist/columns.js +7 -5
  13. package/dist/constrained-columns.js +1 -2
  14. package/dist/data-table-features.d.ts +129 -0
  15. package/dist/data-table-features.js +550 -0
  16. package/dist/export.js +1 -2
  17. package/dist/facets.js +5 -7
  18. package/dist/filter-bar-state.js +14 -18
  19. package/dist/filter-client.js +1 -2
  20. package/dist/filter.js +1 -2
  21. package/dist/grouping.js +1 -2
  22. package/dist/index.js +3 -3
  23. package/dist/messages.d.ts +1 -1
  24. package/dist/messages.js +2 -3
  25. package/dist/pagination.js +1 -2
  26. package/dist/query-builder-state.js +1 -2
  27. package/dist/requests.js +1 -2
  28. package/dist/row-hierarchy.js +1 -2
  29. package/dist/row-identity.js +1 -2
  30. package/dist/saved-views.js +1 -2
  31. package/dist/search-controller.js +1 -2
  32. package/dist/search.js +1 -2
  33. package/dist/selection-client.js +1 -2
  34. package/dist/selection.d.ts +3 -0
  35. package/dist/selection.js +9 -2
  36. package/dist/server-export.js +1 -2
  37. package/dist/sorting.js +1 -2
  38. package/dist/table-state-changes.js +1 -2
  39. package/dist/table-state.js +1 -2
  40. package/dist/text-normalization.js +1 -2
  41. package/dist/url-state.js +1 -2
  42. package/package.json +5 -5
  43. package/src/DataTable.tsx +276 -712
  44. package/src/FilterBar.tsx +17 -3
  45. package/src/QueryBuilder.tsx +5 -5
  46. package/src/columns.ts +9 -3
  47. package/src/data-table-features.tsx +579 -0
  48. package/src/messages.ts +1 -1
  49. package/src/selection.ts +8 -0
  50. package/src/styles.css +17 -11
package/src/DataTable.tsx CHANGED
@@ -1,45 +1,41 @@
1
- import { Button, Checkbox, ContextMenu, DropdownMenu, EmptyState, Pagination, SearchInput, Skeleton, Toaster, createToaster, useTheme } from "@gemologic/sheen";
1
+ import { Button, Checkbox, ContextMenu, DropdownMenu, EmptyState, Glyph, Pagination, SearchInput, Skeleton, flashChange, useTheme } from "@gemologic/sheen";
2
2
  import type { 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";
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
7
  import { changeTableState } from "./table-state-changes.ts";
8
8
  import { canMoveColumn, moveColumn, orderColumnStates, placeColumn } from "./column-layout.ts";
9
9
  import { constrainedColumnValues, summarizedColumns } from "./constrained-columns.ts";
10
10
  import type { ColumnDropPlacement, ColumnMoveDirection } from "./column-layout.ts";
11
11
  import { columnStateSchema, readColumnDefinitions } from "./columns.ts";
12
- import type { ColumnEditor, ColumnValue, SheenColumns } from "./columns.ts";
12
+ import type { ColumnValue, SheenColumns } from "./columns.ts";
13
13
  import { createClientView } from "./client-view.ts";
14
14
  import type { ClientView } from "./client-view.ts";
15
15
  import { formatSearchQuery, parseSearchQuery } from "./search.ts";
16
16
  import type { SearchMode } from "./search.ts";
17
17
  import { getPageRange, resolvePagination } from "./pagination.ts";
18
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";
19
+ import type { ServerRowGroup } from "./grouping.ts";
24
20
  import { createTableRequests } from "./requests.ts";
25
- import type { TableRequestOutcome, TableRequestSnapshot } from "./requests.ts";
21
+ import type { TableRequestOutcome } from "./requests.ts";
26
22
  import { createTableSelection } from "./selection.ts";
27
23
  import type { BulkSelection } from "./selection.ts";
28
24
  import { parseTableState, serializeState } from "./table-state.ts";
29
25
  import type { ColumnState, TableState } from "./table-state.ts";
30
- import { FilterBar } from "./FilterBar.tsx";
26
+ import { filterBarFeature } from "./FilterBar.tsx";
31
27
  import { DataTableToolbar } from "./DataTableToolbar.tsx";
32
28
  import type { DataTableToolbarAction } from "./DataTableToolbar.tsx";
33
29
  import { parseFilter, serializeFilter } from "./filter.ts";
34
30
  import type { FilterNode } from "./filter.ts";
35
31
  import type { FilterDateEditor } from "./FilterBar.tsx";
36
- import { createClientExport } from "./export.ts";
37
32
  import { selectClientRows } from "./selection-client.ts";
38
33
  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 type { ServerExportOutcome, TableExportRequest } from "./server-export.ts";
35
+ import type { CellCommitRequest, CellCommitResult } from "./cell-edit.ts";
42
36
  import { resolveTableMessages } from "./messages.ts";
37
+ import { cellEditingFeature, createSnapshotSignal, createStableRows, defaultCell, groupingFeature, hierarchyFeature } from "./data-table-features.tsx";
38
+ import type { DataTableCellAttributes, DataTableCellBinding, DataTableFeature, DataTableFeatureContext, DataTablePresentation, DisplayDataRow, DisplayGroupRow, DisplayRow, StableRow } from "./data-table-features.tsx";
43
39
 
44
40
  export interface DataTableResult<Row extends object> extends PageResult<Row> {
45
41
  readonly facets?: Readonly<Record<string, Readonly<Record<string, number>>>>;
@@ -158,6 +154,7 @@ interface DataTableBaseProps<Row extends object> {
158
154
  readonly initialState?: DataTableInitialState;
159
155
  /** Reactively applies an app-owned accepted filter. Use onAcceptedStateChange to keep table-authored changes synchronized. */
160
156
  readonly filter?: FilterNode;
157
+ /** Row and cell height as a CSS length, such as `"2.75rem"` for two-line cells. Pair with `estimatedRowHeight` in pixels. */
161
158
  readonly rowHeight?: string;
162
159
  readonly variableRowHeight?: boolean;
163
160
  readonly estimatedRowHeight?: number;
@@ -211,52 +208,17 @@ export interface ServerDataTableProps<Row extends object> extends DataTableBaseP
211
208
 
212
209
  export type DataTableProps<Row extends object> = ClientDataTableProps<Row> | ServerDataTableProps<Row>;
213
210
 
214
- interface StableRow<Row extends object> {
215
- readonly id: string;
216
- readonly value: Accessor<Row>;
217
- readonly update: (row: Row) => boolean;
218
- }
219
-
220
211
  interface ScrollAnchor {
221
212
  readonly id: string;
213
+ readonly index: number;
222
214
  readonly offset: number;
223
215
  }
224
216
 
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;
246
- }
247
-
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;
217
+ interface VirtualRow<Row extends object> {
218
+ readonly row: DisplayRow<Row>;
219
+ readonly item: VirtualItem;
256
220
  }
257
221
 
258
- type DisplayRow<Row extends object> = DisplayDataRow<Row> | DisplayGroupRow<Row>;
259
-
260
222
  function displayDataRow<Row extends object>(row: DisplayRow<Row>): DisplayDataRow<Row> | undefined {
261
223
  return row.kind === "data" ? row : undefined;
262
224
  }
@@ -265,113 +227,12 @@ function displayGroupRow<Row extends object>(row: DisplayRow<Row>): DisplayGroup
265
227
  return row.kind === "group" ? row : undefined;
266
228
  }
267
229
 
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
- };
307
- }
308
-
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
- });
230
+ function sameSelection(left: BulkSelection | undefined, right: BulkSelection | undefined): boolean {
231
+ return left === right || JSON.stringify(left) === JSON.stringify(right);
369
232
  }
370
233
 
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);
234
+ function sameKeys(left: readonly string[], right: readonly string[]): boolean {
235
+ return left.length === right.length && left.every((key, index) => key === right[index]);
375
236
  }
376
237
 
377
238
  function errorMessage(value: unknown): string {
@@ -407,14 +268,6 @@ function exportResetKey(options: false | DataTableExportOptions | undefined): st
407
268
  return key;
408
269
  }
409
270
 
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
271
 
419
272
  function filterActive(filter: FilterNode): boolean {
420
273
  if (filter.kind === "and" || filter.kind === "or") return filter.children.some(filterActive);
@@ -533,18 +386,17 @@ function clampColumnWidth(value: number, minimum: number | null, maximum: number
533
386
  }
534
387
 
535
388
  export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.Element {
389
+ return renderDataTable(props, [filterBarFeature, groupingFeature, hierarchyFeature, cellEditingFeature]);
390
+ }
391
+
392
+ /** Internal composition root. Features own their props, state, and rendering hooks; omitted features are not bundled. */
393
+ export function renderDataTable<Row extends object>(props: DataTableProps<Row>, features: readonly DataTableFeature[]): JSX.Element {
536
394
  if (props.mode === "server" && typeof props.onStateChange !== "function") throw new Error("Server mode requires onStateChange");
537
395
  if (props.mode !== "server" && !Array.isArray(props.data)) throw new Error("Client mode requires a complete data array");
538
396
  if (props.mode !== "server" && props.initialResult !== undefined) throw new Error("initialResult is available only in server mode");
539
397
  if (props.selection && (props.selection.mode !== "multiple" || typeof props.selection.onChange !== "function")) throw new Error("DataTable selection requires multiple mode and onChange");
540
398
  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
399
  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
400
  if (typeof props.editResetKey === "number" && !Number.isFinite(props.editResetKey)) throw new Error("DataTable editResetKey must be a finite number or string");
549
401
  const variant = () => {
550
402
  const value: unknown = props.variant;
@@ -572,38 +424,15 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
572
424
  const searchOptions = resolveSearchOptions(props.search, searchableDefinitions.length);
573
425
  const mobileLayout = resolveMobileLayout(props.mobileLayout);
574
426
  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
427
  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`);
585
428
  const selection = props.selection ? createTableSelection(initialState.filter, schema.filterColumns) : undefined;
586
- const [selectionRevision, setSelectionRevision] = createSignal(0);
587
429
  let selectionAnchorId: string | undefined;
588
430
  let selectionSearch = initialState.search;
589
431
  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
432
  const [clientState, setClientState] = createSignal(initialState);
602
433
  const [searchDraft, setSearchDraft] = createSignal(initialState.search);
603
434
  const [searchScheduled, setSearchScheduled] = createSignal(false);
604
435
  const [layoutColumns, setLayoutColumns] = createSignal(initialState.columns);
605
- const [serverRevision, setServerRevision] = createSignal(0);
606
- const [exportRevision, setExportRevision] = createSignal(0);
607
436
  const [clientExportError, setClientExportError] = createSignal<unknown>(null);
608
437
  const [lastDownload, setLastDownload] = createSignal<{ readonly href: string; readonly filename: string }>();
609
438
  const [coldVisible, setColdVisible] = createSignal(false);
@@ -626,10 +455,12 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
626
455
  return artifact;
627
456
  })
628
457
  : undefined;
629
- const serverSnapshot = (): TableRequestSnapshot<TableState, DataTableResult<Row>> | undefined => {
630
- serverRevision();
631
- return requests?.getSnapshot();
632
- };
458
+ // Client export code loads on first use. Reset and disposal advance the generation so a late load cannot publish.
459
+ let clientExportGeneration = 0;
460
+ let clientExportInFlight = false;
461
+ const server = requests ? createSnapshotSignal(requests.getSnapshot) : undefined;
462
+ const serverSnapshot = () => server?.snapshot();
463
+ const exportStore = serverExports ? createSnapshotSignal(serverExports.getSnapshot) : undefined;
633
464
 
634
465
  const getValue = (row: Row, columnId: string): ColumnValue => {
635
466
  const column = definitionById.get(columnId);
@@ -656,17 +487,17 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
656
487
  });
657
488
 
658
489
  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));
490
+ if (!requests || !server || serverSnapshot()?.accepted) return;
491
+ void server.track(requests.request(initialState));
663
492
  });
664
493
  createEffect(() => {
665
494
  const nextResetKey = exportResetKey(props.export);
666
495
  if (Object.is(nextResetKey, configuredExportResetKey)) return;
667
496
  configuredExportResetKey = nextResetKey;
668
497
  serverExports?.clear();
669
- setExportRevision(revision => revision + 1);
498
+ clientExportGeneration++;
499
+ clientExportInFlight = false;
500
+ exportStore?.sync();
670
501
  setClientExportError(null);
671
502
  const download = lastDownload();
672
503
  if (download) URL.revokeObjectURL(download.href);
@@ -675,7 +506,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
675
506
  onCleanup(() => {
676
507
  if (searchTimer !== undefined) window.clearTimeout(searchTimer);
677
508
  requests?.dispose();
678
- hierarchy?.dispose();
509
+ clientExportGeneration++;
679
510
  serverExports?.dispose();
680
511
  const download = lastDownload();
681
512
  if (download) URL.revokeObjectURL(download.href);
@@ -713,15 +544,12 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
713
544
  });
714
545
 
715
546
  async function transition(next: TableState): Promise<TableRequestOutcome | "client"> {
716
- if (!requests) {
547
+ if (!requests || !server) {
717
548
  setClientState(next);
718
549
  props.onAcceptedStateChange?.(Object.freeze({ ...next, columns: layoutColumns() }));
719
550
  return "client";
720
551
  }
721
- const completion = requests.request(next);
722
- setServerRevision(revision => revision + 1);
723
- const outcome = await completion;
724
- setServerRevision(revision => revision + 1);
552
+ const outcome = await server.track(requests.request(next));
725
553
  const accepted = requests.getSnapshot().accepted;
726
554
  if (outcome === "accepted" && accepted) props.onAcceptedStateChange?.(Object.freeze({ ...accepted.state, columns: layoutColumns() }));
727
555
  return outcome;
@@ -868,163 +696,126 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
868
696
  }
869
697
 
870
698
  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);
699
+ if (!requests || !server || busy()) return;
700
+ void server.track(requests.retry()).then(outcome => {
876
701
  const accepted = requests.getSnapshot().accepted;
877
702
  if (outcome === "accepted" && accepted) props.onAcceptedStateChange?.(Object.freeze({ ...accepted.state, columns: layoutColumns() }));
878
703
  });
879
704
  }
880
705
 
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
- }
706
+ const stableRows = createStableRows(props.getRowId, () => props.mode === "server" ? result().rows : props.data ?? []);
707
+ const flatDisplayCache = new WeakMap<StableRow<Row>, DisplayDataRow<Row>>();
896
708
  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;
709
+ const existing = flatDisplayCache.get(row);
710
+ if (existing && existing.position === index + 1 && existing.setSize === setSize) return existing;
899
711
  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);
712
+ flatDisplayCache.set(row, created);
901
713
  return created;
902
714
  }
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([]);
715
+ const featureContext: DataTableFeatureContext<Row> = Object.freeze({
716
+ props,
717
+ definitions,
718
+ filterColumns: schema.filterColumns,
719
+ messages,
720
+ locale,
721
+ pending,
722
+ result,
723
+ accepted: acceptedAvailable,
724
+ acceptedFilter: () => acceptedState().filter,
725
+ requestFilter,
726
+ stableRows,
727
+ createStableRows: (source: () => readonly Row[]) => createStableRows(props.getRowId, source),
728
+ rowAt,
729
+ rowIndex,
730
+ focusRow,
965
731
  });
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([]));
732
+ const extensions = features.flatMap(feature => feature(featureContext) ?? []);
733
+ const presentations = extensions.flatMap(extension => extension.presentation ? [extension.presentation] : []);
734
+ if (presentations.length > 1) throw new Error("DataTable grouping and hierarchy are separate presentation modes");
735
+ const presentation: DataTablePresentation<Row> | undefined = presentations[0];
736
+ const treePresentation = presentation !== undefined;
737
+ const cellExtensions = extensions.flatMap(extension => extension.cell ? [extension.cell] : []);
738
+ const queryExtensions = extensions.flatMap(extension => extension.query ? [extension.query] : []);
739
+ const overlays = extensions.flatMap(extension => extension.overlay ? [extension.overlay] : []);
740
+ const flatResultRows = createMemo<readonly Row[]>(() => presentation ? Object.freeze([]) : result().rows);
741
+ const serverFlatStableRows = createMemo<readonly StableRow<Row>[]>(() => props.mode === "server" && !presentation
742
+ ? Object.freeze(flatResultRows().map((row, index) => stableRows.resolve(row, index)))
743
+ : Object.freeze([]));
968
744
  function flatStableRow(index: number): StableRow<Row> | undefined {
969
745
  const row = flatResultRows()[index];
970
746
  if (!row) return undefined;
971
- const client = clientRowIndex();
972
- if (client) return client.resolve(row, index);
973
- return serverFlatStableRows()[index];
747
+ return props.mode === "server" ? serverFlatStableRows()[index] : stableRows.resolve(row, index);
974
748
  }
975
- const rowCount = (): number => hierarchy || props.grouping ? structuredRows().length : flatResultRows().length;
749
+ const rowCount = (): number => presentation ? presentation.rows().length : flatResultRows().length;
976
750
  function rowAt(index: number): DisplayRow<Row> | undefined {
977
- if (hierarchy || props.grouping) return structuredRows()[index];
751
+ if (presentation) return presentation.rows()[index];
978
752
  const row = flatStableRow(index);
979
753
  return row ? flatDisplayRow(row, index, flatResultRows().length) : undefined;
980
754
  }
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;
755
+ /**
756
+ * Callers pass the index they already know (the realized item, focused row, or scroll anchor), so keyboard
757
+ * handling is O(1). The scan only runs when rows moved under a stale hint, at most once per accepted row change.
758
+ */
759
+ function rowIndex(key: string, hint?: number): number {
760
+ if (hint !== undefined && hint >= 0 && rowAt(hint)?.key === key) return hint;
761
+ if (presentation) return presentation.rows().findIndex(row => row.key === key);
762
+ if (!key.startsWith("row:")) return -1;
763
+ const id = key.slice("row:".length);
764
+ return flatResultRows().findIndex(row => props.getRowId(row) === id);
765
+ }
766
+ const loadedRows = createMemo<readonly StableRow<Row>[]>(() => presentation
767
+ ? presentation.rows().flatMap(row => row.kind === "data" ? [row.row] : [])
768
+ : props.mode === "server" ? serverFlatStableRows()
769
+ : selection || actions().length > 0 ? flatResultRows().map((row, index) => stableRows.resolve(row, index)) : Object.freeze([]));
770
+ const loadedIds = createMemo<ReadonlySet<string>>(() => new Set(loadedRows().map(row => row.id)));
771
+ const [selectionPayload, setSelectionPayload] = createSignal<BulkSelection | undefined>(selection?.getPayload(), { equals: sameSelection });
772
+ // The accepted boundary (reset key, search, filter, and loaded rows) drives selection eligibility before rows render.
773
+ createComputed(() => {
774
+ const ids = loadedIds();
775
+ const resetKey = props.selection?.resetKey;
776
+ const state = acceptedState();
777
+ if (!selection) return;
778
+ untrack(() => {
779
+ if (!Object.is(resetKey, selectionResetKey) || state.search !== selectionSearch) {
780
+ selection.reset();
781
+ selectionAnchorId = undefined;
782
+ }
783
+ selectionResetKey = resetKey;
784
+ selectionSearch = state.search;
785
+ selection.setFilter(state.filter);
786
+ selection.setLoadedIds([...ids]);
787
+ setSelectionPayload(selection.getPayload());
788
+ });
1012
789
  });
790
+ let notifiedSelection = selectionPayload();
791
+ // Boundary-driven clears reach the application here; user changes notify directly in publishSelection.
792
+ createEffect(on(selectionPayload, payload => {
793
+ if (!payload || payload === notifiedSelection) return;
794
+ notifiedSelection = payload;
795
+ props.selection?.onChange(payload);
796
+ }, { defer: true }));
1013
797
  function publishSelection(): void {
1014
798
  if (!selection) return;
1015
799
  const payload = selection.getPayload();
1016
- setSelectionRevision(revision => revision + 1);
800
+ notifiedSelection = payload;
801
+ setSelectionPayload(payload);
1017
802
  props.selection?.onChange(payload);
1018
803
  }
804
+ const selectionMarks = createMemo<ReadonlySet<string>>(() => {
805
+ const payload = selectionPayload();
806
+ return new Set(payload?.kind === "query" ? payload.excluded : payload?.ids ?? []);
807
+ });
1019
808
  function rowSelected(id: string): boolean {
1020
- selectionRevision();
1021
- selectableRows();
1022
- return selection?.isSelected(id) ?? false;
809
+ const payload = selectionPayload();
810
+ if (!payload) return false;
811
+ return payload.kind === "query" ? loadedIds().has(id) && !selectionMarks().has(id) : selectionMarks().has(id);
812
+ }
813
+ function selectionAnchorLoaded(id: string): boolean {
814
+ return loadedIds().has(id);
1023
815
  }
1024
816
  function changeRowSelection(id: string, selected: boolean, range: boolean): void {
1025
817
  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);
818
+ if (range && selectionAnchorId !== undefined && selectionAnchorLoaded(selectionAnchorId)) selection.selectRange(selectionAnchorId, id, selected);
1028
819
  else {
1029
820
  selection.setSelected(id, selected);
1030
821
  selectionAnchorId = id;
@@ -1047,10 +838,13 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1047
838
  selectionAnchorId = undefined;
1048
839
  publishSelection();
1049
840
  }
1050
- const selectedLoadedCount = createMemo(() => selectableRows().rows.filter(row => rowSelected(row.id)).length);
1051
- const selectionPayload = createMemo(() => {
1052
- selectionRevision();
1053
- return selection?.getPayload();
841
+ const selectedLoadedCount = createMemo(() => {
842
+ const payload = selectionPayload();
843
+ if (!payload) return 0;
844
+ const loaded = loadedIds();
845
+ let marked = 0;
846
+ for (const id of selectionMarks()) if (loaded.has(id)) marked++;
847
+ return payload.kind === "query" ? loaded.size - marked : marked;
1054
848
  });
1055
849
  const selectionActive = createMemo(() => {
1056
850
  const payload = selectionPayload();
@@ -1066,10 +860,10 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1066
860
  function actionContext(anchor?: StableRow<Row>): DataTableActionContext<Row> {
1067
861
  const payload = anchor ? rowActionSelection(anchor) : selectionPayload();
1068
862
  if (!payload) throw new Error("DataTable selection actions require an active selection");
1069
- const loadedRows = selectableRows().rows
863
+ const selectedRows = loadedRows()
1070
864
  .filter(row => payload.kind === "query" ? !payload.excluded.includes(row.id) : payload.ids.includes(row.id))
1071
865
  .map(row => row.value());
1072
- return Object.freeze({ selection: payload, loadedRows: Object.freeze(loadedRows), ...(anchor ? { anchor: anchor.value() } : {}) });
866
+ return Object.freeze({ selection: payload, loadedRows: Object.freeze(selectedRows), ...(anchor ? { anchor: anchor.value() } : {}) });
1073
867
  }
1074
868
 
1075
869
  function actionDisabled(action: DataTableAction<Row>, context: DataTableActionContext<Row>): boolean {
@@ -1133,14 +927,15 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1133
927
  if (typeof label !== "string" || !label.trim()) throw new Error(`Selection label for ${row.id} must be nonempty`);
1134
928
  return label;
1135
929
  }
930
+ const acceptedColumns = createMemo(() => acceptedState().columns);
931
+ const acceptedColumnById = createMemo(() => new Map(acceptedColumns().map(column => [column.id, column])));
1136
932
  const columnRecords = definitions.map((definition, index) => {
1137
933
  const initial = initialState.columns.find(column => column.id === definition.id);
1138
934
  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() });
935
+ const state = createMemo(() => acceptedColumnById().get(definition.id) ?? initial);
936
+ return Object.freeze({ definition, state, variable: `--sheen-table-column-${index}`, sortDescriptionId: createUniqueId() });
1141
937
  });
1142
938
  const columnRecordById = new Map(columnRecords.map(column => [column.definition.id, column]));
1143
- const acceptedColumns = createMemo(() => acceptedState().columns);
1144
939
  const orderedColumnStates = createMemo(() => orderColumnStates(acceptedColumns()));
1145
940
  const summaryEligible = createMemo(() => {
1146
941
  const ids = props.summarizeColumns ?? [];
@@ -1179,81 +974,18 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1179
974
  });
1180
975
  };
1181
976
  const visibleDefinitions = createMemo(() => {
1182
- const ordered = orderedColumnStates();
1183
- for (const state of ordered) columnRecordById.get(state.id)?.updateState(state);
1184
- return ordered.flatMap(state => {
977
+ return orderedColumnStates().flatMap(state => {
1185
978
  const record = columnRecordById.get(state.id);
1186
979
  return record && state.visible && !summarizedIds().has(state.id) ? [record] : [];
1187
980
  });
1188
981
  });
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
982
  const availableExportFormats = createMemo<readonly DataTableExportFormat[]>(() => {
1248
983
  const hasVisibleValue = visibleDefinitions().some(column => column.definition.accessor !== null);
1249
984
  if (!hasVisibleValue || configuredExportFormats.length === 0) return Object.freeze([]);
1250
985
  if (props.mode === "server" && !serverExports) return Object.freeze([]);
1251
986
  return configuredExportFormats;
1252
987
  });
1253
- const serverExportSnapshot = (): ServerExportSnapshot<Blob> | undefined => {
1254
- exportRevision();
1255
- return serverExports?.getSnapshot();
1256
- };
988
+ const serverExportSnapshot = () => exportStore?.snapshot();
1257
989
  const exportPending = (): boolean => serverExportSnapshot()?.pending ?? false;
1258
990
  const exportError = (): unknown => serverExportSnapshot()?.error ?? clientExportError();
1259
991
 
@@ -1269,29 +1001,35 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1269
1001
  anchor.click();
1270
1002
  }
1271
1003
 
1272
- function exportClient(format: DataTableExportFormat): void {
1273
- if (props.mode === "server") return;
1004
+ async function exportClient(format: DataTableExportFormat): Promise<void> {
1005
+ if (props.mode === "server" || clientExportInFlight) return;
1274
1006
  setClientExportError(null);
1007
+ // Capture the accepted view, selection, and columns at request time; only the code load is deferred.
1008
+ const generation = clientExportGeneration;
1009
+ clientExportInFlight = true;
1275
1010
  try {
1276
1011
  const view = clientView()?.view ?? [];
1277
1012
  const payload = selectionActive() ? selectionPayload() : undefined;
1278
1013
  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
1014
+ const columns = visibleDefinitions().flatMap(column => column.definition.accessor
1280
1015
  ? [{ id: column.definition.id, header: column.definition.header, value: column.definition.accessor }]
1281
- : []));
1016
+ : []);
1017
+ const { createClientExport } = await import("./export.ts");
1018
+ if (generation !== clientExportGeneration) return;
1019
+ const exported = createClientExport(rows, columns);
1282
1020
  const content = format === "csv" ? exported.toCSV() : exported.toJSON();
1283
1021
  publishDownload(new Blob([content], { type: format === "csv" ? "text/csv;charset=utf-8" : "application/json;charset=utf-8" }), format);
1284
1022
  } catch (value) {
1285
- setClientExportError(value);
1023
+ if (generation === clientExportGeneration) setClientExportError(value);
1024
+ } finally {
1025
+ if (generation === clientExportGeneration) clientExportInFlight = false;
1286
1026
  }
1287
1027
  }
1288
1028
 
1289
1029
  async function finishServerExport(completion: Promise<ServerExportOutcome>): Promise<void> {
1290
- setExportRevision(revision => revision + 1);
1291
- const outcome = await completion;
1292
- setExportRevision(revision => revision + 1);
1030
+ const outcome = await (exportStore ? exportStore.track(completion) : completion);
1293
1031
  if (outcome !== "accepted") return;
1294
- const accepted = serverExports?.getSnapshot().accepted;
1032
+ const accepted = serverExportSnapshot()?.accepted;
1295
1033
  if (accepted) publishDownload(accepted.artifact, accepted.request.format);
1296
1034
  }
1297
1035
 
@@ -1304,7 +1042,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1304
1042
  function requestExport(format: DataTableExportFormat): void {
1305
1043
  if (pending() || exportPending()) return;
1306
1044
  if (props.mode === "server") exportServer(format);
1307
- else exportClient(format);
1045
+ else void exportClient(format);
1308
1046
  }
1309
1047
 
1310
1048
  function retryExport(): void {
@@ -1367,9 +1105,12 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1367
1105
  }
1368
1106
 
1369
1107
  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);
1108
+ const cells = [...tableElement?.querySelectorAll<HTMLElement>("[data-column]") ?? []].filter(element => element.dataset.column === column.definition.id);
1109
+ // 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.
1110
+ const previous = cells.map(cell => cell.style.inlineSize);
1111
+ for (const cell of cells) cell.style.inlineSize = "max-content";
1112
+ const measured = cells.reduce((maximum, cell) => Math.max(maximum, Math.ceil(cell.getBoundingClientRect().width)), 0);
1113
+ cells.forEach((cell, index) => { cell.style.inlineSize = previous[index] ?? ""; });
1373
1114
  setColumnWidth(column, measured > 0 ? measured : currentColumnWidth(column));
1374
1115
  }
1375
1116
 
@@ -1427,7 +1168,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1427
1168
  });
1428
1169
  const toolbarActions = createMemo<readonly DataTableToolbarAction[]>(() => {
1429
1170
  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 });
1171
+ if (selection && (presentation?.allowSelectAll ?? true) && acceptedState().search.length === 0) next.push({ kind: "action", id: "select-all", label: messages().selectAll, disabled: pending(), onSelect: selectAllMatchingRows });
1431
1172
  if (availableExportFormats().length > 0) next.push({ kind: "menu", id: "export", label: messages().export, disabled: pending() || exportPending(), items: exportMenuItems() });
1432
1173
  if (lastDownload()) next.push({ kind: "action", id: "download", label: messages().downloadLastExport, onSelect: downloadLastExport });
1433
1174
  if (props.columnControls !== false) next.push({ kind: "menu", id: "columns", label: messages().columns, items: columnMenuItems() });
@@ -1658,41 +1399,55 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1658
1399
  measuredDensity = currentDensity;
1659
1400
  if (virtualizerMounted && changed) virtualizer.measure();
1660
1401
  });
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>[] = [];
1402
+ const virtualRows = createMemo<ReadonlyMap<string, VirtualRow<Row>>>(() => {
1403
+ const rows = new Map<string, VirtualRow<Row>>();
1665
1404
  for (const item of virtualizer.getVirtualItems()) {
1666
1405
  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);
1406
+ if (row) rows.set(row.key, { row, item });
1681
1407
  }
1682
- for (const id of renderedRowCache.keys()) if (!retained.has(id)) renderedRowCache.delete(id);
1683
1408
  return rows;
1684
1409
  });
1410
+ // Rendered rows are keyed by stable display key, so a row's DOM survives position and data refreshes.
1411
+ const renderedKeys = createMemo<readonly string[]>(() => [...virtualRows().keys()], [], { equals: sameKeys });
1412
+ function virtualRow(key: string): VirtualRow<Row> {
1413
+ const row = virtualRows().get(key);
1414
+ if (!row) throw new Error(`Missing rendered table row: ${key}`);
1415
+ return row;
1416
+ }
1417
+ // Each rendered row reads its own entry signal. Scrolling rebuilds `virtualRows`, but only rows whose item or data changed are notified,
1418
+ // instead of marking every rendered row's reactive subtree stale on every frame.
1419
+ const rowEntries = new Map<string, Signal<VirtualRow<Row>>>();
1420
+ createComputed(() => {
1421
+ const current = virtualRows();
1422
+ for (const [key, entry] of rowEntries) {
1423
+ const next = current.get(key);
1424
+ if (next) entry[1](next);
1425
+ else rowEntries.delete(key);
1426
+ }
1427
+ });
1428
+ function rowEntry(key: string): Accessor<VirtualRow<Row>> {
1429
+ const existing = rowEntries.get(key);
1430
+ if (existing) return existing[0];
1431
+ const entry = createSignal(untrack(() => virtualRow(key)), { equals: (previous, next) => previous.row === next.row && previous.item === next.item });
1432
+ rowEntries.set(key, entry);
1433
+ return entry[0];
1434
+ }
1685
1435
  const [activeRowKey, setActiveRowKey] = createSignal<string | null>(null);
1436
+ let activeRowHint = -1;
1437
+ function activateRow(key: string, index: number): void {
1438
+ activeRowHint = index;
1439
+ setActiveRowKey(key);
1440
+ }
1686
1441
  const focusableRowKey = createMemo<string | null>(() => {
1687
- if (!props.onRowActivate && !selection && !hierarchy && !props.grouping && actions().length === 0) return null;
1442
+ if (!props.onRowActivate && !selection && !treePresentation && actions().length === 0) return null;
1688
1443
  const active = activeRowKey();
1689
- return active && rowIndex(active) >= 0 ? active : rowAt(0)?.key ?? null;
1444
+ return active && rowIndex(active, activeRowHint) >= 0 ? active : rowAt(0)?.key ?? null;
1690
1445
  });
1691
1446
  let focusFrame: number | undefined;
1692
1447
  function focusRow(index: number): void {
1693
1448
  const row = rowAt(index);
1694
1449
  if (!row || !viewport) return;
1695
- setActiveRowKey(row.key);
1450
+ activateRow(row.key, index);
1696
1451
  virtualizer.scrollToIndex(index, { align: "auto" });
1697
1452
  let attempts = 10;
1698
1453
  const realize = (): void => {
@@ -1708,60 +1463,14 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1708
1463
  if (focusFrame !== undefined) cancelAnimationFrame(focusFrame);
1709
1464
  focusFrame = requestAnimationFrame(realize);
1710
1465
  }
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 {
1466
+ function handleRowKeyDown(event: KeyboardEvent, row: DisplayRow<Row>, index: number): void {
1730
1467
  if (event.target !== event.currentTarget || event.altKey) return;
1731
1468
  if (selection && !pending() && row.kind === "data" && (event.ctrlKey || event.metaKey) && !event.shiftKey && event.key.toLowerCase() === "a") {
1732
1469
  event.preventDefault();
1733
1470
  selectLoadedRows(true);
1734
1471
  return;
1735
1472
  }
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
- }
1473
+ if (presentation?.keyDown(event, row, index, "table")) return;
1765
1474
  if (selection && !pending() && row.kind === "data" && !event.ctrlKey && !event.metaKey && event.key === " ") {
1766
1475
  event.preventDefault();
1767
1476
  changeRowSelection(row.row.id, !rowSelected(row.row.id), event.shiftKey);
@@ -1773,7 +1482,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1773
1482
  return;
1774
1483
  }
1775
1484
  if (event.ctrlKey || event.metaKey || (event.shiftKey && !selection)) return;
1776
- const current = rowIndex(row.key);
1485
+ const current = rowIndex(row.key, index);
1777
1486
  if (current < 0) return;
1778
1487
  const page = Math.max(1, Math.floor((viewport?.clientHeight ?? estimatedRowHeight()) / estimatedRowHeight()));
1779
1488
  const last = Math.max(0, rowCount() - 1);
@@ -1788,7 +1497,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1788
1497
  event.preventDefault();
1789
1498
  const nextRow = rowAt(next);
1790
1499
  if (selection && row.kind === "data" && event.shiftKey && nextRow?.kind === "data") {
1791
- if (!selectionAnchorId || !selectableRows().rows.some(candidate => candidate.id === selectionAnchorId)) selectionAnchorId = row.row.id;
1500
+ if (!selectionAnchorId || !selectionAnchorLoaded(selectionAnchorId)) selectionAnchorId = row.row.id;
1792
1501
  selection.selectRange(selectionAnchorId, nextRow.row.id, true);
1793
1502
  publishSelection();
1794
1503
  }
@@ -1818,7 +1527,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1818
1527
  const top = viewport.scrollTop;
1819
1528
  const item = virtualizer.getVirtualItems().find(candidate => candidate.end > top);
1820
1529
  const row = item ? rowAt(item.index) : undefined;
1821
- if (item && row) scrollAnchor = { id: row.key, offset: top - item.start };
1530
+ if (item && row) scrollAnchor = { id: row.key, index: item.index, offset: top - item.start };
1822
1531
  return;
1823
1532
  }
1824
1533
  const bounds = viewport.getBoundingClientRect();
@@ -1828,7 +1537,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1828
1537
  const index = Number(row.dataset.index);
1829
1538
  const item = virtualizer.getVirtualItems().find(candidate => candidate.index === index);
1830
1539
  if (!item) return;
1831
- scrollAnchor = { id: row.dataset.rowKey, offset: viewport.scrollTop - item.start };
1540
+ scrollAnchor = { id: row.dataset.rowKey, index, offset: viewport.scrollTop - item.start };
1832
1541
  }
1833
1542
  function scheduleScrollAnchorCapture(): void {
1834
1543
  if (anchorFrame !== undefined) cancelAnimationFrame(anchorFrame);
@@ -1838,7 +1547,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1838
1547
  });
1839
1548
  }
1840
1549
  onCleanup(() => { if (anchorFrame !== undefined) cancelAnimationFrame(anchorFrame); });
1841
- const currentRowCollection = (): readonly DisplayRow<Row>[] | readonly Row[] => hierarchy || props.grouping ? structuredRows() : flatResultRows();
1550
+ const currentRowCollection = (): readonly DisplayRow<Row>[] | readonly Row[] => presentation ? presentation.rows() : flatResultRows();
1842
1551
  let previousRows = currentRowCollection();
1843
1552
  let previousState = serializeState(acceptedState(), schema);
1844
1553
  createEffect(() => {
@@ -1846,7 +1555,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1846
1555
  const nextState = serializeState(acceptedState(), schema);
1847
1556
  const anchor = scrollAnchor;
1848
1557
  if (viewport && anchor && nextRows !== previousRows && nextState === previousState) {
1849
- const index = rowIndex(anchor.id);
1558
+ const index = rowIndex(anchor.id, anchor.index);
1850
1559
  const offset = index < 0 ? undefined : virtualizer.getOffsetForIndex(index, "start")?.[0];
1851
1560
  if (offset !== undefined) viewport.scrollTop = Math.max(0, offset + anchor.offset);
1852
1561
  }
@@ -1931,16 +1640,8 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1931
1640
  selectMobileRows(true);
1932
1641
  return;
1933
1642
  }
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
- }
1643
+ const current = mobileRows().findIndex(candidate => candidate.key === row.key);
1644
+ if (presentation?.keyDown(event, row, current, "cards")) return;
1944
1645
  if (selection && !pending() && row.kind === "data" && !event.ctrlKey && !event.metaKey && event.key === " ") {
1945
1646
  event.preventDefault();
1946
1647
  changeRowSelection(row.row.id, !rowSelected(row.row.id), event.shiftKey);
@@ -1952,7 +1653,6 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1952
1653
  return;
1953
1654
  }
1954
1655
  if (event.ctrlKey || event.metaKey || event.shiftKey) return;
1955
- const current = mobileRows().findIndex(candidate => candidate.key === row.key);
1956
1656
  const last = Math.max(0, mobileRows().length - 1);
1957
1657
  const next = event.key === "ArrowDown" ? Math.min(last, current + 1)
1958
1658
  : event.key === "ArrowUp" ? Math.max(0, current - 1)
@@ -1971,7 +1671,6 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1971
1671
  onCheckedChange={checked => { changeRowSelection(cellProps.row.id, checked, selectRange); selectRange = false; }} />
1972
1672
  </td>;
1973
1673
  }
1974
- const treePresentation = Boolean(hierarchy || props.grouping);
1975
1674
  function logicalColumnIndex(id: string): number {
1976
1675
  const index = orderedColumnStates().findIndex(column => column.id === id);
1977
1676
  if (index < 0) throw new Error(`Missing accepted state for table column: ${id}`);
@@ -1986,157 +1685,33 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1986
1685
  ? undefined
1987
1686
  : treePresentation ? -1 : result().total + 1 + (hasFooter() ? 1 : 0);
1988
1687
  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
- });
1688
+ function bindCell(row: () => DisplayDataRow<Row> | undefined, column: (typeof columnRecords)[number]): DataTableCellBinding<Row> | undefined {
1689
+ for (const extension of cellExtensions) {
1690
+ const binding = extension(row, column.definition);
1691
+ if (binding) return binding;
2031
1692
  }
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)} />;
2102
- }
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 {
1693
+ return undefined;
1694
+ }
1695
+ 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
1696
  const definition = cellProps.column.definition;
2113
1697
  const input = createMemo(() => {
2114
1698
  const row = cellProps.row.row.value();
2115
1699
  return { row, value: definition.accessor?.(row) ?? null };
2116
1700
  }, undefined, { equals: (previous, next) => Object.is(previous.value, next.value) && (definition.cell === null
2117
1701
  || (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>;
1702
+ if (definition.flash) createEffect(on(() => ({ id: cellProps.row.row.id, value: input().value }), (next, previous) => {
1703
+ const element = cellProps.host();
1704
+ if (!element || !previous || previous.id !== next.id || typeof next.value !== "number" || typeof previous.value !== "number" || next.value === previous.value) return;
1705
+ flashChange(element, next.value > previous.value ? "up" : "down");
1706
+ }, { defer: true }));
1707
+ const content = () => cellProps.cell?.active() ? cellProps.cell.render(() => cellProps.row) : definition.cell?.(input().value, input().row) ?? defaultCell(input().value);
1708
+ const TreeCell = presentation?.TreeCell;
1709
+ if (!TreeCell || !cellProps.first) return <>{content()}</>;
1710
+ return <TreeCell row={cellProps.row}>{content()}</TreeCell>;
2129
1711
  }
2130
1712
  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);
1713
+ const GroupCell = presentation?.GroupCell;
1714
+ return GroupCell ? <GroupCell row={cellProps.row} column={cellProps.column.definition} label={cellProps.labelColumn} /> : null;
2140
1715
  }
2141
1716
  function MobileSelectionControl(controlProps: { readonly row: StableRow<Row> }): JSX.Element {
2142
1717
  let selectRange = false;
@@ -2146,21 +1721,15 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2146
1721
  }
2147
1722
  function MobileCellContent(cellProps: { readonly row: DisplayRow<Row>; readonly column: (typeof columnRecords)[number]; readonly title: boolean }): JSX.Element {
2148
1723
  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
- };
1724
+ const cell = bindCell(data, cellProps.column);
1725
+ const attributes = (): DataTableCellAttributes => cell?.attributes() ?? {};
1726
+ let host: HTMLDivElement | undefined;
2158
1727
  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
1728
  <GroupCellContent row={group()} column={cellProps.column} labelColumn={cellProps.title} />
2160
1729
  </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()} />
1730
+ {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}
1731
+ 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"]}>
1732
+ <DataCellContent row={current()} column={cellProps.column} first={cellProps.title} cell={cell} host={() => host} />
2164
1733
  </div>}
2165
1734
  </Show>;
2166
1735
  }
@@ -2174,7 +1743,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2174
1743
  <div class="sheen-data-table-mobile-title">
2175
1744
  <Show when={title()} fallback={data()?.row.id ?? displayGroupRow(cardProps.row)?.label ?? ""}>{column => <MobileCellContent row={cardProps.row} column={column()} title />}</Show>
2176
1745
  </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>
1746
+ <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
1747
  </div>
2179
1748
  <Show when={details().length > 0}><dl class="sheen-data-table-mobile-fields">
2180
1749
  <For each={details()}>{column => <div class="sheen-data-table-mobile-field">
@@ -2184,18 +1753,17 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2184
1753
  </dl></Show>
2185
1754
  </>;
2186
1755
  }
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` }}>
1756
+ 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
1757
  <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
1758
  <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
1759
  <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 ? <>
1760
+ query={searchOptions || queryExtensions.some(query => query.visible()) || columnSummaries().length > 0 ? <>
2192
1761
  <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
1762
  onValueChange={updateSearchDraft} onCompositionStart={startSearchComposition} onCompositionEnd={event => finishSearchComposition(event.currentTarget.value)} />
2194
1763
  <Show when={searchOptions?.exactMatch}><DropdownMenu class="sheen-data-table-search-mode-menu" trigger={<span>{searchMode() === "exact" ? messages().searchExact : messages().searchRanked}</span>}
2195
1764
  triggerLabel={`${messages().searchMatchMode}: ${searchMode() === "exact" ? messages().searchExact : messages().searchRanked}`} items={searchModeItems()} disabled={pending()} /></Show>
2196
1765
  </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>
1766
+ <For each={queryExtensions}>{query => <Show when={query.visible()}>{query.render()}</Show>}</For>
2199
1767
  <Show when={columnSummaries().length > 0}><div class="sheen-data-table-constraints" role="group" aria-label={messages().constrainedColumns}>
2200
1768
  <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
1769
  </div></Show>
@@ -2210,9 +1778,9 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2210
1778
  <thead><tr aria-rowindex="1" style={{ "grid-template-columns": template() }}>
2211
1779
  <Show when={selection}><th class="sheen-data-table-selection-cell" scope="col" role={treePresentation ? "columnheader" : undefined} aria-colindex="1">
2212
1780
  <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} />
1781
+ checked={loadedRows().length > 0 && selectedLoadedCount() === loadedRows().length}
1782
+ indeterminate={selectedLoadedCount() > 0 && selectedLoadedCount() < loadedRows().length}
1783
+ disabled={pending() || loadedRows().length === 0} onCheckedChange={selectLoadedRows} />
2216
1784
  </th></Show>
2217
1785
  <For each={visibleDefinitions()}>{column => {
2218
1786
  const sorted = () => acceptedState().sorting.find(entry => entry.column === column.definition.id);
@@ -2228,11 +1796,11 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2228
1796
  const reportedWidth = () => column.state().width ?? (typeof column.definition.width === "number" ? column.definition.width : column.definition.minWidth ?? 160);
2229
1797
  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
1798
  aria-sort={sortPosition() === 1 ? sorted()?.direction === "asc" ? "ascending" : sorted()?.direction === "desc" ? "descending" : undefined : undefined}>
2231
- <div class="sheen-data-table-header-content">
1799
+ <div class="sheen-data-table-header-content" title={column.definition.header}>
2232
1800
  <Show when={column.definition.sort} fallback={<span class="sheen-data-table-header-label">{column.definition.header}</span>}>
2233
1801
  <button class="sheen-data-table-sort" type="button" disabled={pending()} aria-describedby={column.sortDescriptionId} onClick={event => requestSort(column.definition.id, event.shiftKey)}>
2234
1802
  <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>
1803
+ <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
1804
  </button>
2237
1805
  <span id={column.sortDescriptionId} class="sheen-data-table-state-label">{sortDescription()}</span>
2238
1806
  </Show>
@@ -2261,15 +1829,17 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2261
1829
  <Show when={bodyState() === "empty"}><EmptyState kind="empty" /></Show>
2262
1830
  </td></tr></tbody>}>
2263
1831
  <tbody style={{ height: `${virtualizer.getTotalSize()}px` }}>
2264
- <For each={renderedRows()}>{current => {
2265
- const row = () => current.row();
1832
+ <For each={renderedKeys()}>{key => {
1833
+ const entry = rowEntry(key);
1834
+ const row = createMemo(() => entry().row);
1835
+ const item = createMemo(() => entry().item);
2266
1836
  const dataRow = treePresentation ? () => displayDataRow(row()) : createMemo(() => displayDataRow(row()), undefined, {
2267
1837
  equals: (previous, next) => previous?.row === next?.row,
2268
1838
  });
2269
1839
  const groupRow = () => displayGroupRow(row());
2270
1840
  const labelColumn = () => {
2271
1841
  const visible = visibleDefinitions();
2272
- return visible.some(column => column.definition.id === props.grouping?.by) ? props.grouping?.by : visible[0]?.definition.id;
1842
+ return visible.some(column => column.definition.id === presentation?.labelColumn) ? presentation?.labelColumn : visible[0]?.definition.id;
2273
1843
  };
2274
1844
  function RowCells(): JSX.Element {
2275
1845
  return <>
@@ -2279,59 +1849,53 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2279
1849
  </Show>
2280
1850
  </Show>
2281
1851
  <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}>
1852
+ const cell = bindCell(dataRow, column);
1853
+ const attributes = (): DataTableCellAttributes => cell?.attributes() ?? {};
1854
+ let host: HTMLTableCellElement | undefined;
1855
+ 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}
1856
+ data-editable={attributes()["data-editable"]} data-invalid={attributes()["data-invalid"]}
1857
+ data-stale={attributes()["data-stale"]} data-pending={attributes()["data-pending"]} data-conflict={attributes()["data-conflict"]}>
2294
1858
  <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()} />}
1859
+ {value => <DataCellContent row={value()} column={column} first={column === visibleDefinitions()[0]} cell={cell} host={() => host} />}
2296
1860
  </Show>
2297
1861
  </td>;
2298
1862
  }}</For>
2299
1863
  </>;
2300
1864
  }
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}
1865
+ if (props.actions === undefined) return <tr data-row-key={key} data-row-id={dataRow()?.row.id} data-group-id={groupRow()?.group.id}
1866
+ data-index={item().index} data-selected={dataRow() && rowSelected(dataRow()?.row.id ?? "") ? "" : undefined}
2303
1867
  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)}
1868
+ tabIndex={focusableRowKey() === key ? 0 : props.onRowActivate || selection || treePresentation ? -1 : undefined}
1869
+ aria-rowindex={logicalRowIndex(item().index)}
2306
1870
  aria-level={treePresentation ? dataRow()?.depth ?? 1 : undefined}
2307
1871
  aria-posinset={treePresentation ? row().position : undefined} aria-setsize={treePresentation ? row().setSize : undefined}
2308
1872
  aria-expanded={groupRow()?.expanded ?? (dataRow()?.canExpand ? dataRow()?.expanded : undefined)}
2309
1873
  aria-selected={selection && dataRow() ? rowSelected(dataRow()?.row.id ?? "") : undefined}
2310
1874
  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 }}>
1875
+ onFocus={() => activateRow(key, item().index)} onKeyDown={event => handleRowKeyDown(event, row(), item().index)} onClick={event => handleRowClick(event, row())}
1876
+ ref={element => bindVirtualRow(element, item().index)}
1877
+ style={{ "grid-template-columns": template(), transform: `translateY(${item().start}px)`, "block-size": props.variableRowHeight ? undefined : rowHeight, "min-block-size": rowHeight }}>
2314
1878
  <RowCells />
2315
1879
  </tr>;
2316
1880
  const contextRow = dataRow();
2317
1881
  return <ContextMenu as="tr" items={contextRow ? rowActionItems(contextRow.row) : []} disabled={!contextRow || actions().length === 0 || pending()}
2318
1882
  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}
1883
+ data-row-key={key} data-row-id={dataRow()?.row.id} data-group-id={groupRow()?.group.id}
1884
+ data-index={item().index} data-selected={dataRow() && rowSelected(dataRow()?.row.id ?? "") ? "" : undefined}
2321
1885
  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)}
1886
+ tabIndex={focusableRowKey() === key ? 0 : props.onRowActivate || selection || treePresentation || actions().length > 0 ? -1 : undefined}
1887
+ aria-rowindex={logicalRowIndex(item().index)}
2324
1888
  aria-level={treePresentation ? dataRow()?.depth ?? 1 : undefined}
2325
1889
  aria-posinset={treePresentation ? row().position : undefined} aria-setsize={treePresentation ? row().setSize : undefined}
2326
1890
  aria-expanded={groupRow()?.expanded ?? (dataRow()?.canExpand ? dataRow()?.expanded : undefined)}
2327
1891
  aria-selected={selection && dataRow() ? rowSelected(dataRow()?.row.id ?? "") : undefined}
2328
1892
  aria-busy={dataRow()?.pending ? true : undefined}
2329
- onFocus={() => setActiveRowKey(current.key)} onKeyDown={event => handleRowKeyDown(event, row())} onClick={event => handleRowClick(event, row())}
1893
+ onFocus={() => activateRow(key, item().index)} onKeyDown={event => handleRowKeyDown(event, row(), item().index)} onClick={event => handleRowClick(event, row())}
2330
1894
  ref={element => {
2331
1895
  if (!(element instanceof HTMLTableRowElement)) throw new Error("DataTable context rows must render as table rows");
2332
- bindVirtualRow(element, current.item().index);
1896
+ bindVirtualRow(element, item().index);
2333
1897
  }}
2334
- style={{ "grid-template-columns": template(), transform: `translateY(${current.item().start}px)`, "block-size": props.variableRowHeight ? undefined : rowHeight, "min-block-size": rowHeight }}>
1898
+ style={{ "grid-template-columns": template(), transform: `translateY(${item().start}px)`, "block-size": props.variableRowHeight ? undefined : rowHeight, "min-block-size": rowHeight }}>
2335
1899
  <RowCells />
2336
1900
  </ContextMenu>;
2337
1901
  }}</For>
@@ -2385,7 +1949,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2385
1949
  </Show>
2386
1950
  </div></Show>
2387
1951
  <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>
1952
+ <strong>{messages().selectedCount.replaceAll("{count}", resultNumber().format(selectionCount()))}</strong>
2389
1953
  <For each={actions()}>{action => {
2390
1954
  const context = () => actionContext();
2391
1955
  return <Button size="sm" tone={action.tone ?? "neutral"} disabled={actionDisabled(action, context())} onClick={() => action.onSelect(actionContext())}>{action.label}</Button>;
@@ -2394,6 +1958,6 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2394
1958
  </div></Show>
2395
1959
  </div>
2396
1960
  <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>
1961
+ <For each={overlays}>{overlay => overlay()}</For>
2398
1962
  </section>;
2399
1963
  }