@gemologic/sheen-table 0.2.0 → 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 +7 -0
  2. package/dist/DataTable.js +1154 -1624
  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 +285 -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;
@@ -194,6 +191,7 @@ export interface ClientDataTableProps<Row extends object> extends DataTableBaseP
194
191
  readonly initialResult?: never;
195
192
  readonly onStateChange?: never;
196
193
  readonly onExport?: never;
194
+ readonly refreshKey?: never;
197
195
  }
198
196
 
199
197
  export interface ServerDataTableProps<Row extends object> extends DataTableBaseProps<Row> {
@@ -202,58 +200,25 @@ export interface ServerDataTableProps<Row extends object> extends DataTableBaseP
202
200
  readonly data?: never;
203
201
  readonly initialResult?: DataTableResult<Row>;
204
202
  readonly onStateChange: (state: TableState, signal: AbortSignal) => Promise<DataTableResult<Row>>;
203
+ /** Change to revalidate the latest requested/accepted query without resetting layout or scroll. Initial value does not fetch. */
204
+ readonly refreshKey?: string | number;
205
205
  /** Creates a complete server-side export for the captured accepted query and selection. Without this adapter, export UI is hidden. */
206
206
  readonly onExport?: (request: TableExportRequest, signal: AbortSignal) => Promise<Blob>;
207
207
  }
208
208
 
209
209
  export type DataTableProps<Row extends object> = ClientDataTableProps<Row> | ServerDataTableProps<Row>;
210
210
 
211
- interface StableRow<Row extends object> {
212
- readonly id: string;
213
- readonly value: Accessor<Row>;
214
- readonly update: (row: Row) => boolean;
215
- }
216
-
217
211
  interface ScrollAnchor {
218
212
  readonly id: string;
213
+ readonly index: number;
219
214
  readonly offset: number;
220
215
  }
221
216
 
222
- interface RenderedRow<Row extends object> {
223
- readonly key: string;
224
- readonly row: Accessor<DisplayRow<Row>>;
225
- readonly updateRow: (row: DisplayRow<Row>) => void;
226
- readonly item: Accessor<VirtualItem>;
227
- readonly updateItem: (item: VirtualItem) => void;
228
- }
229
-
230
- interface DisplayDataRow<Row extends object> {
231
- readonly kind: "data";
232
- readonly key: string;
233
- readonly row: StableRow<Row>;
234
- readonly parentId: string | null;
235
- readonly depth: number;
236
- readonly position: number;
237
- readonly setSize: number;
238
- readonly canExpand: boolean;
239
- readonly expanded: boolean;
240
- readonly unloaded: boolean;
241
- readonly pending: boolean;
242
- readonly error: unknown;
243
- }
244
-
245
- interface DisplayGroupRow<Row extends object> {
246
- readonly kind: "group";
247
- readonly key: string;
248
- readonly group: ClientRowGroup<Row>;
249
- readonly label: string;
250
- readonly position: number;
251
- readonly setSize: number;
252
- readonly expanded: boolean;
217
+ interface VirtualRow<Row extends object> {
218
+ readonly row: DisplayRow<Row>;
219
+ readonly item: VirtualItem;
253
220
  }
254
221
 
255
- type DisplayRow<Row extends object> = DisplayDataRow<Row> | DisplayGroupRow<Row>;
256
-
257
222
  function displayDataRow<Row extends object>(row: DisplayRow<Row>): DisplayDataRow<Row> | undefined {
258
223
  return row.kind === "data" ? row : undefined;
259
224
  }
@@ -262,113 +227,12 @@ function displayGroupRow<Row extends object>(row: DisplayRow<Row>): DisplayGroup
262
227
  return row.kind === "group" ? row : undefined;
263
228
  }
264
229
 
265
- function createStableRows<Row extends object>(getRowId: (row: Row) => string): (rows: readonly Row[]) => readonly StableRow<Row>[] {
266
- const identity = createRowIdentity(getRowId);
267
- const cache = new Map<string, StableRow<Row>>();
268
- const [revision, setRevision] = createSignal(0);
269
- return rows => {
270
- const ids = identity.resolveIds(rows);
271
- const retained = new Set<string>();
272
- const resolved: StableRow<Row>[] = [];
273
- let changed = false;
274
- for (let index = 0; index < rows.length; index++) {
275
- const row = rows[index]!;
276
- const id = ids[index]!;
277
- retained.add(id);
278
- const existing = cache.get(id);
279
- if (existing) {
280
- changed = existing.update(row) || changed;
281
- resolved.push(existing);
282
- continue;
283
- }
284
- let current = row;
285
- const record: StableRow<Row> = Object.freeze({
286
- id,
287
- value: (): Row => {
288
- revision();
289
- return current;
290
- },
291
- update: (next: Row): boolean => {
292
- if (Object.is(current, next)) return false;
293
- current = next;
294
- return true;
295
- },
296
- });
297
- cache.set(id, record);
298
- resolved.push(record);
299
- }
300
- for (const id of cache.keys()) if (!retained.has(id)) cache.delete(id);
301
- if (changed) setRevision(value => value + 1);
302
- return Object.freeze(resolved);
303
- };
304
- }
305
-
306
- interface ClientStableRows<Row extends object> {
307
- readonly update: (rows: readonly Row[]) => void;
308
- readonly resolve: (row: Row, index: number) => StableRow<Row>;
309
- readonly has: (id: string) => boolean;
310
- }
311
-
312
- function createClientStableRows<Row extends object>(getRowId: (row: Row) => string): ClientStableRows<Row> {
313
- const cache = new Map<string, StableRow<Row>>();
314
- let retained: ReadonlySet<string> = new Set();
315
- const known = new WeakMap<Row, string>();
316
- const [revision, setRevision] = createSignal(0);
317
- function create(id: string, row: Row): StableRow<Row> {
318
- let current = row;
319
- const record: StableRow<Row> = Object.freeze({
320
- id,
321
- value: (): Row => {
322
- revision();
323
- return current;
324
- },
325
- update: (next: Row): boolean => {
326
- if (Object.is(current, next)) return false;
327
- current = next;
328
- return true;
329
- },
330
- });
331
- cache.set(id, record);
332
- known.set(row, id);
333
- return record;
334
- }
335
- return Object.freeze({
336
- update(rows: readonly Row[]): void {
337
- if (!Array.isArray(rows)) throw new Error("Table rows must be an array");
338
- const ids = new Set<string>();
339
- let changed = false;
340
- for (let index = 0; index < rows.length; index++) {
341
- const row = rows[index];
342
- if (typeof row !== "object" || row === null) throw new Error(`rows[${index}] must be an object`);
343
- const id = getRowId(row);
344
- if (typeof id !== "string" || !id || id.trim() !== id) throw new Error(`rows[${index}] has an invalid stable ID`);
345
- if (ids.has(id)) throw new Error(`rows[${index}] duplicates row ID ${id}`);
346
- const prior = known.get(row);
347
- if (prior !== undefined && prior !== id) throw new Error(`rows[${index}] changed stable ID from ${prior} to ${id}`);
348
- ids.add(id);
349
- const existing = cache.get(id);
350
- if (existing) {
351
- known.set(row, id);
352
- changed = existing.update(row) || changed;
353
- }
354
- }
355
- for (const id of cache.keys()) if (!ids.has(id)) cache.delete(id);
356
- retained = ids;
357
- if (changed) setRevision(value => value + 1);
358
- },
359
- resolve(row: Row, index: number): StableRow<Row> {
360
- const id = getRowId(row);
361
- if (!retained.has(id)) throw new Error(`Client result row at index ${index} is not part of the supplied data`);
362
- return cache.get(id) ?? create(id, row);
363
- },
364
- has: (id: string) => retained.has(id),
365
- });
230
+ function sameSelection(left: BulkSelection | undefined, right: BulkSelection | undefined): boolean {
231
+ return left === right || JSON.stringify(left) === JSON.stringify(right);
366
232
  }
367
233
 
368
- function defaultCell(value: ColumnValue): JSX.Element {
369
- if (value === null) return "";
370
- if (typeof value === "boolean") return value ? "Yes" : "No";
371
- 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]);
372
236
  }
373
237
 
374
238
  function errorMessage(value: unknown): string {
@@ -404,14 +268,6 @@ function exportResetKey(options: false | DataTableExportOptions | undefined): st
404
268
  return key;
405
269
  }
406
270
 
407
- function editorAccepts<Row extends object>(editor: ColumnEditor<Row>, value: ColumnValue): boolean {
408
- if (value === null) return editor.nullable === true;
409
- if (editor.type === "text") return typeof value === "string";
410
- if (editor.type === "number") return typeof value === "number";
411
- if (editor.type === "boolean") return typeof value === "boolean";
412
- if (editor.type === "select") return typeof value === "string" && editor.options.includes(value);
413
- return false;
414
- }
415
271
 
416
272
  function filterActive(filter: FilterNode): boolean {
417
273
  if (filter.kind === "and" || filter.kind === "or") return filter.children.some(filterActive);
@@ -530,18 +386,17 @@ function clampColumnWidth(value: number, minimum: number | null, maximum: number
530
386
  }
531
387
 
532
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 {
533
394
  if (props.mode === "server" && typeof props.onStateChange !== "function") throw new Error("Server mode requires onStateChange");
534
395
  if (props.mode !== "server" && !Array.isArray(props.data)) throw new Error("Client mode requires a complete data array");
535
396
  if (props.mode !== "server" && props.initialResult !== undefined) throw new Error("initialResult is available only in server mode");
536
397
  if (props.selection && (props.selection.mode !== "multiple" || typeof props.selection.onChange !== "function")) throw new Error("DataTable selection requires multiple mode and onChange");
537
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");
538
399
  if (props.grouping && props.hierarchy) throw new Error("DataTable grouping and hierarchy are separate presentation modes");
539
- if (props.grouping && props.mode !== "server" && props.pagination !== false) throw new Error("Client grouping requires complete continuous data with pagination=false");
540
- if (props.grouping && (typeof props.grouping.by !== "string" || !props.grouping.by.trim())) throw new Error("DataTable grouping requires a column ID");
541
- if (props.grouping?.getLabel !== undefined && typeof props.grouping.getLabel !== "function") throw new Error("DataTable grouping getLabel must be a function");
542
- if (props.hierarchy && !props.hierarchy.getChildren && !props.hierarchy.onLoadChildren) throw new Error("DataTable hierarchy requires getChildren or onLoadChildren");
543
- if (props.hierarchy?.onLoadChildren && !props.hierarchy.hasChildren) throw new Error("Async DataTable hierarchy requires hasChildren");
544
- if (typeof props.hierarchy?.resetKey === "number" && !Number.isFinite(props.hierarchy.resetKey)) throw new Error("DataTable hierarchy resetKey must be a finite number or string");
545
400
  if (typeof props.editResetKey === "number" && !Number.isFinite(props.editResetKey)) throw new Error("DataTable editResetKey must be a finite number or string");
546
401
  const variant = () => {
547
402
  const value: unknown = props.variant;
@@ -569,38 +424,15 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
569
424
  const searchOptions = resolveSearchOptions(props.search, searchableDefinitions.length);
570
425
  const mobileLayout = resolveMobileLayout(props.mobileLayout);
571
426
  if (mobileLayout?.titleColumn && !definitions.some(column => column.id === mobileLayout.titleColumn)) throw new Error(`Unknown mobileLayout title column: ${mobileLayout.titleColumn}`);
572
- const editableDefinitions = definitions.filter(column => column.editor !== null);
573
- if (editableDefinitions.length > 0 && !props.onCellCommit) throw new Error("DataTable editable columns require onCellCommit");
574
- if (editableDefinitions.length === 0 && props.onCellCommit) throw new Error("DataTable onCellCommit requires at least one editable column");
575
- for (const column of editableDefinitions) {
576
- if (!column.accessor || !column.editor) throw new Error(`Editable column ${column.id} requires an accessor and editor`);
577
- }
578
- const editToaster = props.onCellCommit ? createToaster() : undefined;
579
427
  const initialState = initialTableState(props);
580
- const groupingColumn = props.grouping ? definitions.find(column => column.id === props.grouping?.by) : undefined;
581
- if (props.grouping && !groupingColumn?.accessor) throw new Error(`Grouping column ${props.grouping.by} must be an accessor column`);
582
428
  const selection = props.selection ? createTableSelection(initialState.filter, schema.filterColumns) : undefined;
583
- const [selectionRevision, setSelectionRevision] = createSignal(0);
584
429
  let selectionAnchorId: string | undefined;
585
430
  let selectionSearch = initialState.search;
586
431
  let selectionResetKey = props.selection?.resetKey;
587
- const hierarchy = props.hierarchy ? createRowHierarchy<Row>({
588
- getRowId: props.getRowId,
589
- ...(props.hierarchy.getChildren ? { getChildren: props.hierarchy.getChildren } : {}),
590
- ...(props.hierarchy.hasChildren ? { canLoadChildren: props.hierarchy.hasChildren } : {}),
591
- ...(props.hierarchy.onLoadChildren ? { loadChildren: props.hierarchy.onLoadChildren } : {}),
592
- ...(props.hierarchy.defaultExpanded !== undefined ? { defaultExpanded: props.hierarchy.defaultExpanded } : {}),
593
- }) : undefined;
594
- const [hierarchyRevision, setHierarchyRevision] = createSignal(0);
595
- let hierarchyResetKey = props.hierarchy?.resetKey;
596
- const groupExpansion = new Map<string, boolean>();
597
- const [groupRevision, setGroupRevision] = createSignal(0);
598
432
  const [clientState, setClientState] = createSignal(initialState);
599
433
  const [searchDraft, setSearchDraft] = createSignal(initialState.search);
600
434
  const [searchScheduled, setSearchScheduled] = createSignal(false);
601
435
  const [layoutColumns, setLayoutColumns] = createSignal(initialState.columns);
602
- const [serverRevision, setServerRevision] = createSignal(0);
603
- const [exportRevision, setExportRevision] = createSignal(0);
604
436
  const [clientExportError, setClientExportError] = createSignal<unknown>(null);
605
437
  const [lastDownload, setLastDownload] = createSignal<{ readonly href: string; readonly filename: string }>();
606
438
  const [coldVisible, setColdVisible] = createSignal(false);
@@ -623,10 +455,12 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
623
455
  return artifact;
624
456
  })
625
457
  : undefined;
626
- const serverSnapshot = (): TableRequestSnapshot<TableState, DataTableResult<Row>> | undefined => {
627
- serverRevision();
628
- return requests?.getSnapshot();
629
- };
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;
630
464
 
631
465
  const getValue = (row: Row, columnId: string): ColumnValue => {
632
466
  const column = definitionById.get(columnId);
@@ -653,17 +487,17 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
653
487
  });
654
488
 
655
489
  onMount(() => {
656
- if (!requests || serverSnapshot()?.accepted) return;
657
- const completion = requests.request(initialState);
658
- setServerRevision(revision => revision + 1);
659
- void completion.finally(() => setServerRevision(revision => revision + 1));
490
+ if (!requests || !server || serverSnapshot()?.accepted) return;
491
+ void server.track(requests.request(initialState));
660
492
  });
661
493
  createEffect(() => {
662
494
  const nextResetKey = exportResetKey(props.export);
663
495
  if (Object.is(nextResetKey, configuredExportResetKey)) return;
664
496
  configuredExportResetKey = nextResetKey;
665
497
  serverExports?.clear();
666
- setExportRevision(revision => revision + 1);
498
+ clientExportGeneration++;
499
+ clientExportInFlight = false;
500
+ exportStore?.sync();
667
501
  setClientExportError(null);
668
502
  const download = lastDownload();
669
503
  if (download) URL.revokeObjectURL(download.href);
@@ -672,7 +506,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
672
506
  onCleanup(() => {
673
507
  if (searchTimer !== undefined) window.clearTimeout(searchTimer);
674
508
  requests?.dispose();
675
- hierarchy?.dispose();
509
+ clientExportGeneration++;
676
510
  serverExports?.dispose();
677
511
  const download = lastDownload();
678
512
  if (download) URL.revokeObjectURL(download.href);
@@ -710,15 +544,12 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
710
544
  });
711
545
 
712
546
  async function transition(next: TableState): Promise<TableRequestOutcome | "client"> {
713
- if (!requests) {
547
+ if (!requests || !server) {
714
548
  setClientState(next);
715
549
  props.onAcceptedStateChange?.(Object.freeze({ ...next, columns: layoutColumns() }));
716
550
  return "client";
717
551
  }
718
- const completion = requests.request(next);
719
- setServerRevision(revision => revision + 1);
720
- const outcome = await completion;
721
- setServerRevision(revision => revision + 1);
552
+ const outcome = await server.track(requests.request(next));
722
553
  const accepted = requests.getSnapshot().accepted;
723
554
  if (outcome === "accepted" && accepted) props.onAcceptedStateChange?.(Object.freeze({ ...accepted.state, columns: layoutColumns() }));
724
555
  return outcome;
@@ -737,6 +568,12 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
737
568
  });
738
569
  }, { defer: true }));
739
570
 
571
+ createEffect(on(() => props.refreshKey, () => {
572
+ if (!requests) return;
573
+ const snapshot = requests.getSnapshot();
574
+ void transition(snapshot.requested ?? snapshot.accepted?.state ?? initialState);
575
+ }, { defer: true }));
576
+
740
577
  const searchLabel = () => (searchOptions?.label ?? messages().searchTable).replaceAll("{caption}", props.caption);
741
578
  const searchPlaceholder = () => (searchOptions?.placeholder ?? searchLabel()).replaceAll("{caption}", props.caption);
742
579
  const searchShortcut = createMemo<ShortcutAction | undefined>(() => searchOptions?.shortcut ? Object.freeze({
@@ -859,163 +696,126 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
859
696
  }
860
697
 
861
698
  function retry(): void {
862
- if (!requests || busy()) return;
863
- const completion = requests.retry();
864
- setServerRevision(revision => revision + 1);
865
- void completion.then(outcome => {
866
- setServerRevision(revision => revision + 1);
699
+ if (!requests || !server || busy()) return;
700
+ void server.track(requests.retry()).then(outcome => {
867
701
  const accepted = requests.getSnapshot().accepted;
868
702
  if (outcome === "accepted" && accepted) props.onAcceptedStateChange?.(Object.freeze({ ...accepted.state, columns: layoutColumns() }));
869
703
  });
870
704
  }
871
705
 
872
- const reconcileRows = createStableRows(props.getRowId);
873
- const clientStableRows = createClientStableRows(props.getRowId);
874
- const flatDisplayCache = new Map<string, DisplayDataRow<Row>>();
875
- const clientRowIndex = createMemo(() => {
876
- if (props.mode === "server") return undefined;
877
- const source = props.data ?? [];
878
- clientStableRows.update(source);
879
- for (const id of flatDisplayCache.keys()) if (!clientStableRows.has(id)) flatDisplayCache.delete(id);
880
- return clientStableRows;
881
- });
882
- function stableResultRows(rows: readonly Row[]): readonly StableRow<Row>[] {
883
- const client = clientRowIndex();
884
- if (!client) return reconcileRows(rows);
885
- return rows.map((row, index) => client.resolve(row, index));
886
- }
706
+ const stableRows = createStableRows(props.getRowId, () => props.mode === "server" ? result().rows : props.data ?? []);
707
+ const flatDisplayCache = new WeakMap<StableRow<Row>, DisplayDataRow<Row>>();
887
708
  function flatDisplayRow(row: StableRow<Row>, index: number, setSize: number): DisplayDataRow<Row> {
888
- const existing = flatDisplayCache.get(row.id);
889
- 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;
890
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 });
891
- flatDisplayCache.set(row.id, created);
712
+ flatDisplayCache.set(row, created);
892
713
  return created;
893
714
  }
894
- const groupNumberFormatter = createMemo(() => new Intl.NumberFormat(locale()));
895
- function groupLabel(group: ClientRowGroup<Row>): string {
896
- const supplied = props.grouping?.getLabel?.(group.value);
897
- const label = supplied ?? (group.value === null ? messages().groupMissing : typeof group.value === "number" ? groupNumberFormatter().format(group.value) : String(group.value));
898
- if (typeof label !== "string" || !label.trim()) throw new Error(`Group ${group.id} requires a nonempty label`);
899
- return label;
900
- }
901
- function groupExpanded(id: string): boolean {
902
- groupRevision();
903
- const existing = groupExpansion.get(id);
904
- if (existing !== undefined) return existing;
905
- const initial = props.grouping?.collapsible === false || props.grouping?.defaultExpanded !== false;
906
- groupExpansion.set(id, initial);
907
- return initial;
908
- }
909
- function setGroupExpanded(id: string, expanded: boolean): void {
910
- if (pending() || props.grouping?.collapsible === false || groupExpanded(id) === expanded) return;
911
- groupExpansion.set(id, expanded);
912
- setGroupRevision(revision => revision + 1);
913
- }
914
- const structuredRows = createMemo<readonly DisplayRow<Row>[]>(() => {
915
- if (hierarchy) {
916
- hierarchyRevision();
917
- const nextResetKey = props.hierarchy?.resetKey;
918
- if (!Object.is(nextResetKey, hierarchyResetKey)) hierarchy.reset();
919
- hierarchyResetKey = nextResetKey;
920
- hierarchy.updateRoots(result().rows);
921
- const snapshot = hierarchy.getSnapshot();
922
- const stable = reconcileRows(snapshot.map(item => item.row));
923
- const stableById = new Map(stable.map(row => [row.id, row]));
924
- return Object.freeze(snapshot.map((item: HierarchyRow<Row>): DisplayDataRow<Row> => {
925
- const row = stableById.get(item.id);
926
- if (!row) throw new Error(`Missing stable hierarchy row: ${item.id}`);
927
- 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 });
928
- }));
929
- }
930
- if (props.grouping && groupingColumn?.accessor) {
931
- groupRevision();
932
- if (props.mode === "server" && serverSnapshot()?.accepted === null) return Object.freeze([]);
933
- const current = result();
934
- const aggregateColumns = definitions.flatMap(column => column.aggregate && column.accessor ? [{ id: column.id, aggregate: column.aggregate, getValue: column.accessor }] : []);
935
- const groups = props.mode === "server"
936
- ? normalizeServerGroups(current.rows, current.groups, { column: groupingColumn.id, aggregateColumns: aggregateColumns.map(column => column.id), getRowId: props.getRowId })
937
- : groupClientRows(current.rows, { column: groupingColumn.id, getValue: groupingColumn.accessor, aggregates: aggregateColumns });
938
- const stable = props.mode === "server" ? reconcileRows(current.rows) : stableResultRows(current.rows);
939
- const stableById = new Map(stable.map(row => [row.id, row]));
940
- const rows: DisplayRow<Row>[] = [];
941
- for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
942
- const group = groups[groupIndex]!;
943
- const expanded = groupExpanded(group.id);
944
- rows.push(Object.freeze({ kind: "group", key: group.id, group, label: groupLabel(group), position: groupIndex + 1, setSize: groups.length, expanded }));
945
- if (!expanded) continue;
946
- for (let rowIndex = 0; rowIndex < group.rows.length; rowIndex++) {
947
- const id = props.getRowId(group.rows[rowIndex]!);
948
- const row = stableById.get(id);
949
- if (!row) throw new Error(`Missing stable grouped row: ${id}`);
950
- 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 }));
951
- }
952
- }
953
- return Object.freeze(rows);
954
- }
955
- 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,
956
731
  });
957
- const flatResultRows = createMemo<readonly Row[]>(() => hierarchy || props.grouping ? Object.freeze([]) : result().rows);
958
- 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([]));
959
744
  function flatStableRow(index: number): StableRow<Row> | undefined {
960
745
  const row = flatResultRows()[index];
961
746
  if (!row) return undefined;
962
- const client = clientRowIndex();
963
- if (client) return client.resolve(row, index);
964
- return serverFlatStableRows()[index];
747
+ return props.mode === "server" ? serverFlatStableRows()[index] : stableRows.resolve(row, index);
965
748
  }
966
- const rowCount = (): number => hierarchy || props.grouping ? structuredRows().length : flatResultRows().length;
749
+ const rowCount = (): number => presentation ? presentation.rows().length : flatResultRows().length;
967
750
  function rowAt(index: number): DisplayRow<Row> | undefined {
968
- if (hierarchy || props.grouping) return structuredRows()[index];
751
+ if (presentation) return presentation.rows()[index];
969
752
  const row = flatStableRow(index);
970
753
  return row ? flatDisplayRow(row, index, flatResultRows().length) : undefined;
971
754
  }
972
- function rowIndex(key: string): number {
973
- if (hierarchy || props.grouping) return structuredRows().findIndex(row => row.key === key);
974
- for (let index = 0; index < flatResultRows().length; index++) if (`row:${flatStableRow(index)?.id ?? ""}` === key) return index;
975
- return -1;
976
- }
977
- let selectionInitialized = false;
978
- const selectableRows = createMemo(() => {
979
- const rows = hierarchy || props.grouping
980
- ? structuredRows().flatMap(row => row.kind === "data" ? [row.row] : [])
981
- : props.mode === "server" ? serverFlatStableRows()
982
- : selection || actions().length > 0 ? stableResultRows(flatResultRows()) : Object.freeze([]);
983
- if (!selection) return { rows, before: "", payload: undefined };
984
- const before = JSON.stringify(selection.getPayload());
985
- const nextResetKey = props.selection?.resetKey;
986
- const nextSearch = acceptedState().search;
987
- if (!Object.is(nextResetKey, selectionResetKey) || nextSearch !== selectionSearch) {
988
- selection.reset();
989
- selectionAnchorId = undefined;
990
- }
991
- selectionResetKey = nextResetKey;
992
- selectionSearch = nextSearch;
993
- selection.setFilter(acceptedState().filter);
994
- selection.setLoadedIds(rows.map(row => row.id));
995
- return { rows, before, payload: selection.getPayload() };
996
- });
997
- createEffect(() => {
998
- const synchronized = selectableRows();
999
- if (!selection || !synchronized.payload) return;
1000
- setSelectionRevision(revision => revision + 1);
1001
- if (selectionInitialized && JSON.stringify(synchronized.payload) !== synchronized.before) props.selection?.onChange(synchronized.payload);
1002
- 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
+ });
1003
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 }));
1004
797
  function publishSelection(): void {
1005
798
  if (!selection) return;
1006
799
  const payload = selection.getPayload();
1007
- setSelectionRevision(revision => revision + 1);
800
+ notifiedSelection = payload;
801
+ setSelectionPayload(payload);
1008
802
  props.selection?.onChange(payload);
1009
803
  }
804
+ const selectionMarks = createMemo<ReadonlySet<string>>(() => {
805
+ const payload = selectionPayload();
806
+ return new Set(payload?.kind === "query" ? payload.excluded : payload?.ids ?? []);
807
+ });
1010
808
  function rowSelected(id: string): boolean {
1011
- selectionRevision();
1012
- selectableRows();
1013
- 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);
1014
815
  }
1015
816
  function changeRowSelection(id: string, selected: boolean, range: boolean): void {
1016
817
  if (!selection || pending()) return;
1017
- const anchorLoaded = selectionAnchorId !== undefined && selectableRows().rows.some(row => row.id === selectionAnchorId);
1018
- if (range && anchorLoaded && selectionAnchorId) selection.selectRange(selectionAnchorId, id, selected);
818
+ if (range && selectionAnchorId !== undefined && selectionAnchorLoaded(selectionAnchorId)) selection.selectRange(selectionAnchorId, id, selected);
1019
819
  else {
1020
820
  selection.setSelected(id, selected);
1021
821
  selectionAnchorId = id;
@@ -1038,10 +838,13 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1038
838
  selectionAnchorId = undefined;
1039
839
  publishSelection();
1040
840
  }
1041
- const selectedLoadedCount = createMemo(() => selectableRows().rows.filter(row => rowSelected(row.id)).length);
1042
- const selectionPayload = createMemo(() => {
1043
- selectionRevision();
1044
- 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;
1045
848
  });
1046
849
  const selectionActive = createMemo(() => {
1047
850
  const payload = selectionPayload();
@@ -1057,10 +860,10 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1057
860
  function actionContext(anchor?: StableRow<Row>): DataTableActionContext<Row> {
1058
861
  const payload = anchor ? rowActionSelection(anchor) : selectionPayload();
1059
862
  if (!payload) throw new Error("DataTable selection actions require an active selection");
1060
- const loadedRows = selectableRows().rows
863
+ const selectedRows = loadedRows()
1061
864
  .filter(row => payload.kind === "query" ? !payload.excluded.includes(row.id) : payload.ids.includes(row.id))
1062
865
  .map(row => row.value());
1063
- 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() } : {}) });
1064
867
  }
1065
868
 
1066
869
  function actionDisabled(action: DataTableAction<Row>, context: DataTableActionContext<Row>): boolean {
@@ -1124,14 +927,15 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1124
927
  if (typeof label !== "string" || !label.trim()) throw new Error(`Selection label for ${row.id} must be nonempty`);
1125
928
  return label;
1126
929
  }
930
+ const acceptedColumns = createMemo(() => acceptedState().columns);
931
+ const acceptedColumnById = createMemo(() => new Map(acceptedColumns().map(column => [column.id, column])));
1127
932
  const columnRecords = definitions.map((definition, index) => {
1128
933
  const initial = initialState.columns.find(column => column.id === definition.id);
1129
934
  if (!initial) throw new Error(`Missing initial state for table column: ${definition.id}`);
1130
- const [state, updateState] = createSignal(initial);
1131
- 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() });
1132
937
  });
1133
938
  const columnRecordById = new Map(columnRecords.map(column => [column.definition.id, column]));
1134
- const acceptedColumns = createMemo(() => acceptedState().columns);
1135
939
  const orderedColumnStates = createMemo(() => orderColumnStates(acceptedColumns()));
1136
940
  const summaryEligible = createMemo(() => {
1137
941
  const ids = props.summarizeColumns ?? [];
@@ -1170,81 +974,18 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1170
974
  });
1171
975
  };
1172
976
  const visibleDefinitions = createMemo(() => {
1173
- const ordered = orderedColumnStates();
1174
- for (const state of ordered) columnRecordById.get(state.id)?.updateState(state);
1175
- return ordered.flatMap(state => {
977
+ return orderedColumnStates().flatMap(state => {
1176
978
  const record = columnRecordById.get(state.id);
1177
979
  return record && state.visible && !summarizedIds().has(state.id) ? [record] : [];
1178
980
  });
1179
981
  });
1180
- type CellEditController = ReturnType<typeof createCellEdit<ColumnValue, string>>;
1181
- interface CellEditRecord {
1182
- readonly controller: CellEditController;
1183
- readonly revision: Accessor<number>;
1184
- readonly publish: () => void;
1185
- }
1186
- const cellEditRecords = new Map<string, Map<string, CellEditRecord>>();
1187
- const [editGeneration, setEditGeneration] = createSignal(0);
1188
- let currentEditResetKey = props.editResetKey;
1189
-
1190
- function cellEditRecord(row: StableRow<Row>, column: (typeof columnRecords)[number]): CellEditRecord | undefined {
1191
- editGeneration();
1192
- const editor = column.definition.editor;
1193
- const accessor = column.definition.accessor;
1194
- const commit = props.onCellCommit;
1195
- if (!editor || !accessor || !commit) return undefined;
1196
- const existing = cellEditRecords.get(row.id)?.get(column.definition.id);
1197
- if (existing) return existing;
1198
- const initial = accessor(row.value());
1199
- if (!editorAccepts(editor, initial)) throw new Error(`Initial value for editable cell ${row.id}/${column.definition.id} does not match its editor`);
1200
- const [revision, setRevision] = createSignal(0);
1201
- const publish = () => setRevision(value => value + 1);
1202
- const controller = createCellEdit<ColumnValue, string>(initial, async (request, signal) => {
1203
- const applicationRequest: DataTableCellCommitRequest<Row> = Object.freeze({ ...request, rowId: row.id, row: row.value(), column: column.definition.id });
1204
- const result = await commit(applicationRequest, signal);
1205
- const value = result.kind === "accepted" ? result.value : result.current;
1206
- if (!editorAccepts(editor, value)) throw new Error(`Committed value for ${row.id}/${column.definition.id} does not match its editor`);
1207
- return result;
1208
- }, { validate: value => {
1209
- if (!editorAccepts(editor, value)) return value === null ? messages().cellValueRequired : messages().cellValueInvalid;
1210
- return editor.validate?.(value, row.value()) ?? null;
1211
- } });
1212
- const record = Object.freeze({ controller, revision, publish });
1213
- const rowRecords = cellEditRecords.get(row.id) ?? new Map<string, CellEditRecord>();
1214
- rowRecords.set(column.definition.id, record);
1215
- cellEditRecords.set(row.id, rowRecords);
1216
- return record;
1217
- }
1218
-
1219
- function editSnapshot(record: CellEditRecord | undefined): CellEditSnapshot<ColumnValue, string> | undefined {
1220
- record?.revision();
1221
- return record?.controller.getSnapshot();
1222
- }
1223
-
1224
- createEffect(() => {
1225
- const nextResetKey = props.editResetKey;
1226
- if (typeof nextResetKey === "number" && !Number.isFinite(nextResetKey)) throw new Error("DataTable editResetKey must be a finite number or string");
1227
- if (Object.is(nextResetKey, currentEditResetKey)) return;
1228
- currentEditResetKey = nextResetKey;
1229
- for (const columns of cellEditRecords.values()) for (const record of columns.values()) record.controller.dispose();
1230
- cellEditRecords.clear();
1231
- editToaster?.clear();
1232
- setEditGeneration(generation => generation + 1);
1233
- });
1234
- onCleanup(() => {
1235
- for (const columns of cellEditRecords.values()) for (const record of columns.values()) record.controller.dispose();
1236
- cellEditRecords.clear();
1237
- });
1238
982
  const availableExportFormats = createMemo<readonly DataTableExportFormat[]>(() => {
1239
983
  const hasVisibleValue = visibleDefinitions().some(column => column.definition.accessor !== null);
1240
984
  if (!hasVisibleValue || configuredExportFormats.length === 0) return Object.freeze([]);
1241
985
  if (props.mode === "server" && !serverExports) return Object.freeze([]);
1242
986
  return configuredExportFormats;
1243
987
  });
1244
- const serverExportSnapshot = (): ServerExportSnapshot<Blob> | undefined => {
1245
- exportRevision();
1246
- return serverExports?.getSnapshot();
1247
- };
988
+ const serverExportSnapshot = () => exportStore?.snapshot();
1248
989
  const exportPending = (): boolean => serverExportSnapshot()?.pending ?? false;
1249
990
  const exportError = (): unknown => serverExportSnapshot()?.error ?? clientExportError();
1250
991
 
@@ -1260,29 +1001,35 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1260
1001
  anchor.click();
1261
1002
  }
1262
1003
 
1263
- function exportClient(format: DataTableExportFormat): void {
1264
- if (props.mode === "server") return;
1004
+ async function exportClient(format: DataTableExportFormat): Promise<void> {
1005
+ if (props.mode === "server" || clientExportInFlight) return;
1265
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;
1266
1010
  try {
1267
1011
  const view = clientView()?.view ?? [];
1268
1012
  const payload = selectionActive() ? selectionPayload() : undefined;
1269
1013
  const rows = payload ? selectClientRows(view, payload, { locale: locale(), filterColumns: schema.filterColumns, getRowId: props.getRowId, getValue }) : view;
1270
- const exported = createClientExport(rows, visibleDefinitions().flatMap(column => column.definition.accessor
1014
+ const columns = visibleDefinitions().flatMap(column => column.definition.accessor
1271
1015
  ? [{ id: column.definition.id, header: column.definition.header, value: column.definition.accessor }]
1272
- : []));
1016
+ : []);
1017
+ const { createClientExport } = await import("./export.ts");
1018
+ if (generation !== clientExportGeneration) return;
1019
+ const exported = createClientExport(rows, columns);
1273
1020
  const content = format === "csv" ? exported.toCSV() : exported.toJSON();
1274
1021
  publishDownload(new Blob([content], { type: format === "csv" ? "text/csv;charset=utf-8" : "application/json;charset=utf-8" }), format);
1275
1022
  } catch (value) {
1276
- setClientExportError(value);
1023
+ if (generation === clientExportGeneration) setClientExportError(value);
1024
+ } finally {
1025
+ if (generation === clientExportGeneration) clientExportInFlight = false;
1277
1026
  }
1278
1027
  }
1279
1028
 
1280
1029
  async function finishServerExport(completion: Promise<ServerExportOutcome>): Promise<void> {
1281
- setExportRevision(revision => revision + 1);
1282
- const outcome = await completion;
1283
- setExportRevision(revision => revision + 1);
1030
+ const outcome = await (exportStore ? exportStore.track(completion) : completion);
1284
1031
  if (outcome !== "accepted") return;
1285
- const accepted = serverExports?.getSnapshot().accepted;
1032
+ const accepted = serverExportSnapshot()?.accepted;
1286
1033
  if (accepted) publishDownload(accepted.artifact, accepted.request.format);
1287
1034
  }
1288
1035
 
@@ -1295,7 +1042,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1295
1042
  function requestExport(format: DataTableExportFormat): void {
1296
1043
  if (pending() || exportPending()) return;
1297
1044
  if (props.mode === "server") exportServer(format);
1298
- else exportClient(format);
1045
+ else void exportClient(format);
1299
1046
  }
1300
1047
 
1301
1048
  function retryExport(): void {
@@ -1358,9 +1105,12 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1358
1105
  }
1359
1106
 
1360
1107
  function autoFitColumn(column: (typeof columnRecords)[number]): void {
1361
- const measured = [...tableElement?.querySelectorAll<HTMLElement>("[data-column]") ?? []]
1362
- .filter(element => element.dataset.column === column.definition.id)
1363
- .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] ?? ""; });
1364
1114
  setColumnWidth(column, measured > 0 ? measured : currentColumnWidth(column));
1365
1115
  }
1366
1116
 
@@ -1418,7 +1168,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1418
1168
  });
1419
1169
  const toolbarActions = createMemo<readonly DataTableToolbarAction[]>(() => {
1420
1170
  const next: DataTableToolbarAction[] = [];
1421
- 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 });
1422
1172
  if (availableExportFormats().length > 0) next.push({ kind: "menu", id: "export", label: messages().export, disabled: pending() || exportPending(), items: exportMenuItems() });
1423
1173
  if (lastDownload()) next.push({ kind: "action", id: "download", label: messages().downloadLastExport, onSelect: downloadLastExport });
1424
1174
  if (props.columnControls !== false) next.push({ kind: "menu", id: "columns", label: messages().columns, items: columnMenuItems() });
@@ -1649,41 +1399,55 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1649
1399
  measuredDensity = currentDensity;
1650
1400
  if (virtualizerMounted && changed) virtualizer.measure();
1651
1401
  });
1652
- const renderedRowCache = new Map<string, RenderedRow<Row>>();
1653
- const renderedRows = createMemo<readonly RenderedRow<Row>[]>(() => {
1654
- const retained = new Set<string>();
1655
- const rows: RenderedRow<Row>[] = [];
1402
+ const virtualRows = createMemo<ReadonlyMap<string, VirtualRow<Row>>>(() => {
1403
+ const rows = new Map<string, VirtualRow<Row>>();
1656
1404
  for (const item of virtualizer.getVirtualItems()) {
1657
1405
  const row = rowAt(item.index);
1658
- if (!row) continue;
1659
- retained.add(row.key);
1660
- const existing = renderedRowCache.get(row.key);
1661
- if (existing) {
1662
- existing.updateRow(row);
1663
- existing.updateItem(item);
1664
- rows.push(existing);
1665
- continue;
1666
- }
1667
- const [currentRow, setCurrentRow] = createSignal(row);
1668
- const [currentItem, setCurrentItem] = createSignal(item);
1669
- const rendered = Object.freeze({ key: row.key, row: currentRow, updateRow: (next: DisplayRow<Row>): void => { setCurrentRow(next); }, item: currentItem, updateItem: (next: VirtualItem): void => { setCurrentItem(next); } });
1670
- renderedRowCache.set(row.key, rendered);
1671
- rows.push(rendered);
1406
+ if (row) rows.set(row.key, { row, item });
1672
1407
  }
1673
- for (const id of renderedRowCache.keys()) if (!retained.has(id)) renderedRowCache.delete(id);
1674
1408
  return rows;
1675
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
+ }
1676
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
+ }
1677
1441
  const focusableRowKey = createMemo<string | null>(() => {
1678
- if (!props.onRowActivate && !selection && !hierarchy && !props.grouping && actions().length === 0) return null;
1442
+ if (!props.onRowActivate && !selection && !treePresentation && actions().length === 0) return null;
1679
1443
  const active = activeRowKey();
1680
- return active && rowIndex(active) >= 0 ? active : rowAt(0)?.key ?? null;
1444
+ return active && rowIndex(active, activeRowHint) >= 0 ? active : rowAt(0)?.key ?? null;
1681
1445
  });
1682
1446
  let focusFrame: number | undefined;
1683
1447
  function focusRow(index: number): void {
1684
1448
  const row = rowAt(index);
1685
1449
  if (!row || !viewport) return;
1686
- setActiveRowKey(row.key);
1450
+ activateRow(row.key, index);
1687
1451
  virtualizer.scrollToIndex(index, { align: "auto" });
1688
1452
  let attempts = 10;
1689
1453
  const realize = (): void => {
@@ -1699,60 +1463,14 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1699
1463
  if (focusFrame !== undefined) cancelAnimationFrame(focusFrame);
1700
1464
  focusFrame = requestAnimationFrame(realize);
1701
1465
  }
1702
- function changeHierarchyExpansion(row: DisplayDataRow<Row>, expanded: boolean): void {
1703
- if (!hierarchy || pending()) return;
1704
- const completion = hierarchy.setExpanded(row.row.id, expanded);
1705
- setHierarchyRevision(revision => revision + 1);
1706
- void completion.finally(() => setHierarchyRevision(revision => revision + 1));
1707
- }
1708
- function retryHierarchy(row: DisplayDataRow<Row>): void {
1709
- if (!hierarchy || pending()) return;
1710
- const completion = hierarchy.retry(row.row.id);
1711
- setHierarchyRevision(revision => revision + 1);
1712
- void completion.finally(() => setHierarchyRevision(revision => revision + 1));
1713
- }
1714
- const [hierarchyMounted, setHierarchyMounted] = createSignal(false);
1715
- onMount(() => { setHierarchyMounted(true); });
1716
- createEffect(() => {
1717
- if (!hierarchy || !hierarchyMounted()) return;
1718
- for (const row of structuredRows()) if (row.kind === "data" && row.expanded && row.unloaded && !row.pending && row.error === null) changeHierarchyExpansion(row, true);
1719
- });
1720
- function handleRowKeyDown(event: KeyboardEvent, row: DisplayRow<Row>): void {
1466
+ function handleRowKeyDown(event: KeyboardEvent, row: DisplayRow<Row>, index: number): void {
1721
1467
  if (event.target !== event.currentTarget || event.altKey) return;
1722
1468
  if (selection && !pending() && row.kind === "data" && (event.ctrlKey || event.metaKey) && !event.shiftKey && event.key.toLowerCase() === "a") {
1723
1469
  event.preventDefault();
1724
1470
  selectLoadedRows(true);
1725
1471
  return;
1726
1472
  }
1727
- if (row.kind === "group" && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === " " || event.key === "Enter")) {
1728
- event.preventDefault();
1729
- setGroupExpanded(row.group.id, !row.expanded);
1730
- return;
1731
- }
1732
- if (row.kind === "group" && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
1733
- event.preventDefault();
1734
- setGroupExpanded(row.group.id, event.key === "ArrowRight");
1735
- return;
1736
- }
1737
- if (hierarchy && row.kind === "data" && row.canExpand && !event.ctrlKey && !event.metaKey && !event.shiftKey && event.key === "ArrowRight") {
1738
- event.preventDefault();
1739
- if (!row.expanded) changeHierarchyExpansion(row, true);
1740
- else {
1741
- const current = rowIndex(row.key);
1742
- const child = rowAt(current + 1);
1743
- if (child?.kind === "data" && child.parentId === row.row.id) focusRow(current + 1);
1744
- }
1745
- return;
1746
- }
1747
- if (hierarchy && row.kind === "data" && !event.ctrlKey && !event.metaKey && !event.shiftKey && event.key === "ArrowLeft") {
1748
- event.preventDefault();
1749
- if (row.expanded) changeHierarchyExpansion(row, false);
1750
- else if (row.parentId) {
1751
- const parent = structuredRows().findIndex(candidate => candidate.kind === "data" && candidate.row.id === row.parentId);
1752
- if (parent >= 0) focusRow(parent);
1753
- }
1754
- return;
1755
- }
1473
+ if (presentation?.keyDown(event, row, index, "table")) return;
1756
1474
  if (selection && !pending() && row.kind === "data" && !event.ctrlKey && !event.metaKey && event.key === " ") {
1757
1475
  event.preventDefault();
1758
1476
  changeRowSelection(row.row.id, !rowSelected(row.row.id), event.shiftKey);
@@ -1764,7 +1482,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1764
1482
  return;
1765
1483
  }
1766
1484
  if (event.ctrlKey || event.metaKey || (event.shiftKey && !selection)) return;
1767
- const current = rowIndex(row.key);
1485
+ const current = rowIndex(row.key, index);
1768
1486
  if (current < 0) return;
1769
1487
  const page = Math.max(1, Math.floor((viewport?.clientHeight ?? estimatedRowHeight()) / estimatedRowHeight()));
1770
1488
  const last = Math.max(0, rowCount() - 1);
@@ -1779,7 +1497,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1779
1497
  event.preventDefault();
1780
1498
  const nextRow = rowAt(next);
1781
1499
  if (selection && row.kind === "data" && event.shiftKey && nextRow?.kind === "data") {
1782
- if (!selectionAnchorId || !selectableRows().rows.some(candidate => candidate.id === selectionAnchorId)) selectionAnchorId = row.row.id;
1500
+ if (!selectionAnchorId || !selectionAnchorLoaded(selectionAnchorId)) selectionAnchorId = row.row.id;
1783
1501
  selection.selectRange(selectionAnchorId, nextRow.row.id, true);
1784
1502
  publishSelection();
1785
1503
  }
@@ -1809,7 +1527,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1809
1527
  const top = viewport.scrollTop;
1810
1528
  const item = virtualizer.getVirtualItems().find(candidate => candidate.end > top);
1811
1529
  const row = item ? rowAt(item.index) : undefined;
1812
- 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 };
1813
1531
  return;
1814
1532
  }
1815
1533
  const bounds = viewport.getBoundingClientRect();
@@ -1819,7 +1537,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1819
1537
  const index = Number(row.dataset.index);
1820
1538
  const item = virtualizer.getVirtualItems().find(candidate => candidate.index === index);
1821
1539
  if (!item) return;
1822
- scrollAnchor = { id: row.dataset.rowKey, offset: viewport.scrollTop - item.start };
1540
+ scrollAnchor = { id: row.dataset.rowKey, index, offset: viewport.scrollTop - item.start };
1823
1541
  }
1824
1542
  function scheduleScrollAnchorCapture(): void {
1825
1543
  if (anchorFrame !== undefined) cancelAnimationFrame(anchorFrame);
@@ -1829,7 +1547,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1829
1547
  });
1830
1548
  }
1831
1549
  onCleanup(() => { if (anchorFrame !== undefined) cancelAnimationFrame(anchorFrame); });
1832
- const currentRowCollection = (): readonly DisplayRow<Row>[] | readonly Row[] => hierarchy || props.grouping ? structuredRows() : flatResultRows();
1550
+ const currentRowCollection = (): readonly DisplayRow<Row>[] | readonly Row[] => presentation ? presentation.rows() : flatResultRows();
1833
1551
  let previousRows = currentRowCollection();
1834
1552
  let previousState = serializeState(acceptedState(), schema);
1835
1553
  createEffect(() => {
@@ -1837,7 +1555,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1837
1555
  const nextState = serializeState(acceptedState(), schema);
1838
1556
  const anchor = scrollAnchor;
1839
1557
  if (viewport && anchor && nextRows !== previousRows && nextState === previousState) {
1840
- const index = rowIndex(anchor.id);
1558
+ const index = rowIndex(anchor.id, anchor.index);
1841
1559
  const offset = index < 0 ? undefined : virtualizer.getOffsetForIndex(index, "start")?.[0];
1842
1560
  if (offset !== undefined) viewport.scrollTop = Math.max(0, offset + anchor.offset);
1843
1561
  }
@@ -1922,16 +1640,8 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1922
1640
  selectMobileRows(true);
1923
1641
  return;
1924
1642
  }
1925
- if (row.kind === "group" && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === " " || event.key === "Enter" || event.key === "ArrowRight" || event.key === "ArrowLeft")) {
1926
- event.preventDefault();
1927
- setGroupExpanded(row.group.id, event.key === "ArrowRight" ? true : event.key === "ArrowLeft" ? false : !row.expanded);
1928
- return;
1929
- }
1930
- if (hierarchy && row.kind === "data" && row.canExpand && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
1931
- event.preventDefault();
1932
- changeHierarchyExpansion(row, event.key === "ArrowRight");
1933
- return;
1934
- }
1643
+ const current = mobileRows().findIndex(candidate => candidate.key === row.key);
1644
+ if (presentation?.keyDown(event, row, current, "cards")) return;
1935
1645
  if (selection && !pending() && row.kind === "data" && !event.ctrlKey && !event.metaKey && event.key === " ") {
1936
1646
  event.preventDefault();
1937
1647
  changeRowSelection(row.row.id, !rowSelected(row.row.id), event.shiftKey);
@@ -1943,7 +1653,6 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1943
1653
  return;
1944
1654
  }
1945
1655
  if (event.ctrlKey || event.metaKey || event.shiftKey) return;
1946
- const current = mobileRows().findIndex(candidate => candidate.key === row.key);
1947
1656
  const last = Math.max(0, mobileRows().length - 1);
1948
1657
  const next = event.key === "ArrowDown" ? Math.min(last, current + 1)
1949
1658
  : event.key === "ArrowUp" ? Math.max(0, current - 1)
@@ -1962,7 +1671,6 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1962
1671
  onCheckedChange={checked => { changeRowSelection(cellProps.row.id, checked, selectRange); selectRange = false; }} />
1963
1672
  </td>;
1964
1673
  }
1965
- const treePresentation = Boolean(hierarchy || props.grouping);
1966
1674
  function logicalColumnIndex(id: string): number {
1967
1675
  const index = orderedColumnStates().findIndex(column => column.id === id);
1968
1676
  if (index < 0) throw new Error(`Missing accepted state for table column: ${id}`);
@@ -1977,157 +1685,33 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1977
1685
  ? undefined
1978
1686
  : treePresentation ? -1 : result().total + 1 + (hasFooter() ? 1 : 0);
1979
1687
  const footerRowIndex = (): number => treePresentation ? rowCount() + 2 : result().total + 2;
1980
- function expansionLabel(row: DisplayDataRow<Row>): string {
1981
- return `${row.expanded ? messages().collapse : messages().expand} ${row.row.id}`;
1982
- }
1983
- function EditableCellValue(cellProps: { readonly row: DisplayDataRow<Row>; readonly column: (typeof columnRecords)[number]; readonly record: CellEditRecord }): JSX.Element {
1984
- const editor = cellProps.column.definition.editor;
1985
- const accessor = cellProps.column.definition.accessor;
1986
- if (!editor || !accessor) throw new Error(`Editable cell ${cellProps.row.row.id}/${cellProps.column.definition.id} is missing its editor`);
1987
- const activeEditor = editor;
1988
- const id = createUniqueId();
1989
- let editorElement: HTMLInputElement | HTMLSelectElement | undefined;
1990
- let restingElement: HTMLSpanElement | undefined;
1991
- let restoringRestingFocus = false;
1992
- let incoming = accessor(cellProps.row.row.value());
1993
- const snapshot = (): CellEditSnapshot<ColumnValue, string> => {
1994
- cellProps.record.revision();
1995
- return cellProps.record.controller.getSnapshot();
1996
- };
1997
- const draft = (): ColumnValue => snapshot().draft?.value ?? snapshot().committed;
1998
- const label = () => messages().editCell.replaceAll("{column}", cellProps.column.definition.header).replaceAll("{id}", cellProps.row.row.id);
1999
- const message = () => {
2000
- const current = snapshot();
2001
- if (current.invalid) return current.invalid;
2002
- if (current.conflict) return messages().cellConflict.replaceAll("{value}", current.conflict.current === null ? messages().noValue : String(current.conflict.current));
2003
- return current.error ? messages().cellUpdateFailedDescription : null;
2004
- };
2005
- const content = () => cellProps.column.definition.cell?.(snapshot().committed, cellProps.row.row.value()) ?? defaultCell(snapshot().committed);
2006
-
2007
- createEffect(() => {
2008
- const next = accessor(cellProps.row.row.value());
2009
- if (Object.is(next, incoming)) return;
2010
- incoming = next;
2011
- cellProps.record.controller.acceptRefetch(next);
2012
- cellProps.record.publish();
2013
- });
2014
-
2015
- function focusEditor(): void { queueMicrotask(() => editorElement?.focus({ preventScroll: true })); }
2016
- function focusResting(): void {
2017
- queueMicrotask(() => {
2018
- restoringRestingFocus = true;
2019
- try { restingElement?.focus({ preventScroll: true }); }
2020
- finally { restoringRestingFocus = false; }
2021
- });
2022
- }
2023
- function begin(): void {
2024
- if (restoringRestingFocus || pending()) return;
2025
- if (cellProps.record.controller.begin()) {
2026
- cellProps.record.publish();
2027
- focusEditor();
2028
- }
2029
- }
2030
- function update(value: ColumnValue): void {
2031
- cellProps.record.controller.setDraft(value);
2032
- cellProps.record.publish();
2033
- }
2034
- async function finish(completion: Promise<CellCommitOutcome>, restore: boolean, notify = true): Promise<CellCommitOutcome> {
2035
- cellProps.record.publish();
2036
- const outcome = await completion;
2037
- cellProps.record.publish();
2038
- const current = snapshot();
2039
- if (outcome === "accepted" && !current.editing && restore) focusResting();
2040
- if ((outcome === "invalid" || outcome === "conflict") && restore) focusEditor();
2041
- if (outcome === "failed" && notify && editToaster) editToaster.show({
2042
- title: messages().cellUpdateFailed,
2043
- description: messages().cellUpdateFailedDescription,
2044
- tone: "danger",
2045
- priority: "assertive",
2046
- duration: null,
2047
- action: {
2048
- label: messages().retry,
2049
- retryLabel: messages().retry,
2050
- errorMessage: messages().retryFailed,
2051
- run: async () => {
2052
- const retried = await finish(cellProps.record.controller.retry(), false, false);
2053
- if (retried !== "accepted") throw new Error(`Cell retry was not accepted: ${retried}`);
2054
- focusResting();
2055
- },
2056
- },
2057
- });
2058
- return outcome;
2059
- }
2060
- function commit(restore: boolean): void { void finish(cellProps.record.controller.commit(), restore); }
2061
- function blur(): void {
2062
- const current = snapshot();
2063
- const unchangedFailure = (current.error !== null || current.conflict !== null) && current.attempt !== null && current.draft !== null && Object.is(current.attempt.value, current.draft.value);
2064
- if (!unchangedFailure) commit(false);
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;
2065
1692
  }
2066
- function keyDown(event: KeyboardEvent): void {
2067
- if (event.key === "Enter") {
2068
- event.preventDefault();
2069
- commit(true);
2070
- } else if (event.key === "Escape") {
2071
- event.preventDefault();
2072
- cellProps.record.controller.discard();
2073
- cellProps.record.publish();
2074
- focusResting();
2075
- }
2076
- }
2077
- function EditorControl(): JSX.Element {
2078
- const invalid = () => snapshot().invalid !== null || snapshot().error !== null || undefined;
2079
- const describedBy = () => message() ? `${id}-message` : undefined;
2080
- 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"
2081
- aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown} onChange={event => update(event.currentTarget.checked)} />;
2082
- if (activeEditor.type === "select") return <select ref={element => { editorElement = element; element.value = draft() === null ? "" : String(draft()); }} class="sheen-data-table-editor"
2083
- 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)}>
2084
- <Show when={activeEditor.nullable}><option value="">{messages().noValue}</option></Show>
2085
- <For each={activeEditor.options}>{option => <option value={option}>{option}</option>}</For>
2086
- </select>;
2087
- 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"
2088
- aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown}
2089
- onInput={event => update(event.currentTarget.value === "" ? null : event.currentTarget.valueAsNumber)} />;
2090
- return <input ref={element => { editorElement = element; element.value = draft() === null ? "" : String(draft()); }} class="sheen-data-table-editor" type="text"
2091
- aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown}
2092
- onInput={event => update(event.currentTarget.value === "" && activeEditor.nullable ? null : event.currentTarget.value)} />;
2093
- }
2094
- return <span class="sheen-data-table-edit-value">
2095
- <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}
2096
- onKeyDown={event => { if (event.key === "Enter") { event.preventDefault(); begin(); } }}>{content()}</span>}>
2097
- <EditorControl />
2098
- </Show>
2099
- <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>
2100
- </span>;
2101
- }
2102
- 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 {
2103
1696
  const definition = cellProps.column.definition;
2104
1697
  const input = createMemo(() => {
2105
1698
  const row = cellProps.row.row.value();
2106
1699
  return { row, value: definition.accessor?.(row) ?? null };
2107
1700
  }, undefined, { equals: (previous, next) => Object.is(previous.value, next.value) && (definition.cell === null
2108
1701
  || (definition.cellDependencies === null ? previous.row === next.row : definition.cellDependencies.every(key => Object.is(previous.row[key], next.row[key])))) });
2109
- const content = () => cellProps.edit ? <EditableCellValue row={cellProps.row} column={cellProps.column} record={cellProps.edit} /> : definition.cell?.(input().value, input().row) ?? defaultCell(input().value);
2110
- if (!treePresentation || !cellProps.first) return <>{content()}</>;
2111
- return <div class="sheen-data-table-tree-cell" style={{ "--sheen-table-depth": Math.max(0, cellProps.row.depth - 1) }}>
2112
- <Show when={cellProps.row.canExpand} fallback={<span class="sheen-data-table-expander-space" aria-hidden="true" />}>
2113
- <button type="button" class="sheen-data-table-expander" aria-label={expansionLabel(cellProps.row)} aria-expanded={cellProps.row.expanded} disabled={pending()}
2114
- onClick={() => changeHierarchyExpansion(cellProps.row, !cellProps.row.expanded)}>{cellProps.row.expanded ? "▾" : "▸"}</button>
2115
- </Show>
2116
- <span class="sheen-data-table-tree-value">{content()}</span>
2117
- <Show when={cellProps.row.pending}><span class="sheen-data-table-row-status" role="status">{messages().loadingChildren}</span></Show>
2118
- <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>
2119
- </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>;
2120
1711
  }
2121
1712
  function GroupCellContent(cellProps: { readonly row: DisplayGroupRow<Row>; readonly column: (typeof columnRecords)[number]; readonly labelColumn: boolean }): JSX.Element {
2122
- if (cellProps.labelColumn) return <div class="sheen-data-table-tree-cell" style={{ "--sheen-table-depth": 0 }}>
2123
- <Show when={props.grouping?.collapsible !== false} fallback={<span class="sheen-data-table-expander-space" aria-hidden="true" />}>
2124
- <button type="button" class="sheen-data-table-expander" disabled={pending()} aria-label={`${cellProps.row.expanded ? messages().collapse : messages().expand} ${cellProps.row.label}`}
2125
- aria-expanded={cellProps.row.expanded} onClick={() => setGroupExpanded(cellProps.row.group.id, !cellProps.row.expanded)}>{cellProps.row.expanded ? "▾" : "▸"}</button>
2126
- </Show>
2127
- <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>
2128
- </div>;
2129
- const aggregate = cellProps.row.group.aggregates.find(value => value.column === cellProps.column.definition.id)?.value ?? null;
2130
- return defaultCell(aggregate);
1713
+ const GroupCell = presentation?.GroupCell;
1714
+ return GroupCell ? <GroupCell row={cellProps.row} column={cellProps.column.definition} label={cellProps.labelColumn} /> : null;
2131
1715
  }
2132
1716
  function MobileSelectionControl(controlProps: { readonly row: StableRow<Row> }): JSX.Element {
2133
1717
  let selectRange = false;
@@ -2137,21 +1721,15 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2137
1721
  }
2138
1722
  function MobileCellContent(cellProps: { readonly row: DisplayRow<Row>; readonly column: (typeof columnRecords)[number]; readonly title: boolean }): JSX.Element {
2139
1723
  const data = () => displayDataRow(cellProps.row);
2140
- const edit = createMemo(() => {
2141
- const current = data();
2142
- return current ? cellEditRecord(current.row, cellProps.column) : undefined;
2143
- });
2144
- const state = () => editSnapshot(edit());
2145
- const invalid = () => {
2146
- const current = state();
2147
- return Boolean(current && (current.invalid !== null || current.error !== null));
2148
- };
1724
+ const cell = bindCell(data, cellProps.column);
1725
+ const attributes = (): DataTableCellAttributes => cell?.attributes() ?? {};
1726
+ let host: HTMLDivElement | undefined;
2149
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}>
2150
1728
  <GroupCellContent row={group()} column={cellProps.column} labelColumn={cellProps.title} />
2151
1729
  </div>}</Show>}>
2152
- {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}
2153
- data-editable={edit() ? "" : undefined} data-invalid={invalid() ? "" : undefined} data-stale={state()?.stale ? "" : undefined} data-pending={state()?.pending ? "" : undefined} data-conflict={state()?.conflict ? "" : undefined}>
2154
- <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} />
2155
1733
  </div>}
2156
1734
  </Show>;
2157
1735
  }
@@ -2165,7 +1743,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2165
1743
  <div class="sheen-data-table-mobile-title">
2166
1744
  <Show when={title()} fallback={data()?.row.id ?? displayGroupRow(cardProps.row)?.label ?? ""}>{column => <MobileCellContent row={cardProps.row} column={column()} title />}</Show>
2167
1745
  </div>
2168
- <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>
2169
1747
  </div>
2170
1748
  <Show when={details().length > 0}><dl class="sheen-data-table-mobile-fields">
2171
1749
  <For each={details()}>{column => <div class="sheen-data-table-mobile-field">
@@ -2175,18 +1753,17 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2175
1753
  </dl></Show>
2176
1754
  </>;
2177
1755
  }
2178
- 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 }) }}>
2179
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>
2180
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>
2181
1759
  <DataTableToolbar label={messages().tableControls.replace("{caption}", props.caption)} result={resultCount()} resultPrevious={previous() ? messages().previousResults : undefined} actions={toolbarActions()}
2182
- query={searchOptions || (props.filterBar !== false && schema.filterColumns.length > 0) || columnSummaries().length > 0 ? <>
1760
+ query={searchOptions || queryExtensions.some(query => query.visible()) || columnSummaries().length > 0 ? <>
2183
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}
2184
1762
  onValueChange={updateSearchDraft} onCompositionStart={startSearchComposition} onCompositionEnd={event => finishSearchComposition(event.currentTarget.value)} />
2185
1763
  <Show when={searchOptions?.exactMatch}><DropdownMenu class="sheen-data-table-search-mode-menu" trigger={<span>{searchMode() === "exact" ? messages().searchExact : messages().searchRanked}</span>}
2186
1764
  triggerLabel={`${messages().searchMatchMode}: ${searchMode() === "exact" ? messages().searchExact : messages().searchRanked}`} items={searchModeItems()} disabled={pending()} /></Show>
2187
1765
  </div></Show>
2188
- <Show when={props.filterBar !== false && schema.filterColumns.length > 0}><FilterBar columns={props.columns} value={acceptedState().filter} facets={result().facets} disabled={pending()} onChange={requestFilter}
2189
- {...(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>
2190
1767
  <Show when={columnSummaries().length > 0}><div class="sheen-data-table-constraints" role="group" aria-label={messages().constrainedColumns}>
2191
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>
2192
1769
  </div></Show>
@@ -2201,9 +1778,9 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2201
1778
  <thead><tr aria-rowindex="1" style={{ "grid-template-columns": template() }}>
2202
1779
  <Show when={selection}><th class="sheen-data-table-selection-cell" scope="col" role={treePresentation ? "columnheader" : undefined} aria-colindex="1">
2203
1780
  <Checkbox data-sheen-selection-control="" class="sheen-data-table-selection-control" label={messages().selectPage}
2204
- checked={selectableRows().rows.length > 0 && selectedLoadedCount() === selectableRows().rows.length}
2205
- indeterminate={selectedLoadedCount() > 0 && selectedLoadedCount() < selectableRows().rows.length}
2206
- 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} />
2207
1784
  </th></Show>
2208
1785
  <For each={visibleDefinitions()}>{column => {
2209
1786
  const sorted = () => acceptedState().sorting.find(entry => entry.column === column.definition.id);
@@ -2219,11 +1796,11 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2219
1796
  const reportedWidth = () => column.state().width ?? (typeof column.definition.width === "number" ? column.definition.width : column.definition.minWidth ?? 160);
2220
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)}
2221
1798
  aria-sort={sortPosition() === 1 ? sorted()?.direction === "asc" ? "ascending" : sorted()?.direction === "desc" ? "descending" : undefined : undefined}>
2222
- <div class="sheen-data-table-header-content">
1799
+ <div class="sheen-data-table-header-content" title={column.definition.header}>
2223
1800
  <Show when={column.definition.sort} fallback={<span class="sheen-data-table-header-label">{column.definition.header}</span>}>
2224
1801
  <button class="sheen-data-table-sort" type="button" disabled={pending()} aria-describedby={column.sortDescriptionId} onClick={event => requestSort(column.definition.id, event.shiftKey)}>
2225
1802
  <span class="sheen-data-table-sort-label">{column.definition.header}</span>
2226
- <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>
2227
1804
  </button>
2228
1805
  <span id={column.sortDescriptionId} class="sheen-data-table-state-label">{sortDescription()}</span>
2229
1806
  </Show>
@@ -2252,15 +1829,17 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2252
1829
  <Show when={bodyState() === "empty"}><EmptyState kind="empty" /></Show>
2253
1830
  </td></tr></tbody>}>
2254
1831
  <tbody style={{ height: `${virtualizer.getTotalSize()}px` }}>
2255
- <For each={renderedRows()}>{current => {
2256
- 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);
2257
1836
  const dataRow = treePresentation ? () => displayDataRow(row()) : createMemo(() => displayDataRow(row()), undefined, {
2258
1837
  equals: (previous, next) => previous?.row === next?.row,
2259
1838
  });
2260
1839
  const groupRow = () => displayGroupRow(row());
2261
1840
  const labelColumn = () => {
2262
1841
  const visible = visibleDefinitions();
2263
- 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;
2264
1843
  };
2265
1844
  function RowCells(): JSX.Element {
2266
1845
  return <>
@@ -2270,59 +1849,53 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2270
1849
  </Show>
2271
1850
  </Show>
2272
1851
  <For each={visibleDefinitions()}>{column => {
2273
- const edit = column.definition.editor ? createMemo(() => {
2274
- const value = dataRow();
2275
- return value ? cellEditRecord(value.row, column) : undefined;
2276
- }) : () => undefined;
2277
- const state = () => editSnapshot(edit());
2278
- const invalid = () => {
2279
- const currentState = state();
2280
- return Boolean(currentState && (currentState.invalid !== null || currentState.error !== null));
2281
- };
2282
- 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}
2283
- data-editable={edit() ? "" : undefined} data-invalid={invalid() ? "" : undefined}
2284
- 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"]}>
2285
1858
  <Show when={dataRow()} fallback={<Show when={groupRow()}>{value => <GroupCellContent row={value()} column={column} labelColumn={column.definition.id === labelColumn()} />}</Show>}>
2286
- {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} />}
2287
1860
  </Show>
2288
1861
  </td>;
2289
1862
  }}</For>
2290
1863
  </>;
2291
1864
  }
2292
- if (props.actions === undefined) return <tr data-row-key={current.key} data-row-id={dataRow()?.row.id} data-group-id={groupRow()?.group.id}
2293
- 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}
2294
1867
  data-loading={dataRow()?.pending ? "" : undefined} data-load-error={dataRow() && dataRow()?.error !== null ? "" : undefined}
2295
- tabIndex={focusableRowKey() === current.key ? 0 : props.onRowActivate || selection || treePresentation ? -1 : undefined}
2296
- aria-rowindex={logicalRowIndex(current.item().index)}
1868
+ tabIndex={focusableRowKey() === key ? 0 : props.onRowActivate || selection || treePresentation ? -1 : undefined}
1869
+ aria-rowindex={logicalRowIndex(item().index)}
2297
1870
  aria-level={treePresentation ? dataRow()?.depth ?? 1 : undefined}
2298
1871
  aria-posinset={treePresentation ? row().position : undefined} aria-setsize={treePresentation ? row().setSize : undefined}
2299
1872
  aria-expanded={groupRow()?.expanded ?? (dataRow()?.canExpand ? dataRow()?.expanded : undefined)}
2300
1873
  aria-selected={selection && dataRow() ? rowSelected(dataRow()?.row.id ?? "") : undefined}
2301
1874
  aria-busy={dataRow()?.pending ? true : undefined}
2302
- onFocus={() => setActiveRowKey(current.key)} onKeyDown={event => handleRowKeyDown(event, row())} onClick={event => handleRowClick(event, row())}
2303
- ref={element => bindVirtualRow(element, current.item().index)}
2304
- 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 }}>
2305
1878
  <RowCells />
2306
1879
  </tr>;
2307
1880
  const contextRow = dataRow();
2308
1881
  return <ContextMenu as="tr" items={contextRow ? rowActionItems(contextRow.row) : []} disabled={!contextRow || actions().length === 0 || pending()}
2309
1882
  onContextMenu={() => { const value = dataRow(); if (value) prepareContextSelection(value.row); }}
2310
- data-row-key={current.key} data-row-id={dataRow()?.row.id} data-group-id={groupRow()?.group.id}
2311
- 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}
2312
1885
  data-loading={dataRow()?.pending ? "" : undefined} data-load-error={dataRow() && dataRow()?.error !== null ? "" : undefined}
2313
- tabIndex={focusableRowKey() === current.key ? 0 : props.onRowActivate || selection || treePresentation || actions().length > 0 ? -1 : undefined}
2314
- 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)}
2315
1888
  aria-level={treePresentation ? dataRow()?.depth ?? 1 : undefined}
2316
1889
  aria-posinset={treePresentation ? row().position : undefined} aria-setsize={treePresentation ? row().setSize : undefined}
2317
1890
  aria-expanded={groupRow()?.expanded ?? (dataRow()?.canExpand ? dataRow()?.expanded : undefined)}
2318
1891
  aria-selected={selection && dataRow() ? rowSelected(dataRow()?.row.id ?? "") : undefined}
2319
1892
  aria-busy={dataRow()?.pending ? true : undefined}
2320
- 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())}
2321
1894
  ref={element => {
2322
1895
  if (!(element instanceof HTMLTableRowElement)) throw new Error("DataTable context rows must render as table rows");
2323
- bindVirtualRow(element, current.item().index);
1896
+ bindVirtualRow(element, item().index);
2324
1897
  }}
2325
- 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 }}>
2326
1899
  <RowCells />
2327
1900
  </ContextMenu>;
2328
1901
  }}</For>
@@ -2376,7 +1949,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2376
1949
  </Show>
2377
1950
  </div></Show>
2378
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}>
2379
- <strong>{messages().selectedCount.replaceAll("{count}", groupNumberFormatter().format(selectionCount()))}</strong>
1952
+ <strong>{messages().selectedCount.replaceAll("{count}", resultNumber().format(selectionCount()))}</strong>
2380
1953
  <For each={actions()}>{action => {
2381
1954
  const context = () => actionContext();
2382
1955
  return <Button size="sm" tone={action.tone ?? "neutral"} disabled={actionDisabled(action, context())} onClick={() => action.onSelect(actionContext())}>{action.label}</Button>;
@@ -2385,6 +1958,6 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2385
1958
  </div></Show>
2386
1959
  </div>
2387
1960
  <Show when={range()}>{page => <Pagination class="sheen-data-table-pagination" pageIndex={page().pageIndex} pageCount={page().pageCount} pending={busy()} disabled={previous()} onPageChange={requestPage} />}</Show>
2388
- <Show when={editToaster}>{controller => <Toaster controller={controller()} />}</Show>
1961
+ <For each={overlays}>{overlay => overlay()}</For>
2389
1962
  </section>;
2390
1963
  }