@gemologic/sheen-table 0.1.0-rc.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 (106) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +19 -0
  3. package/dist/DataTable.d.ts +159 -0
  4. package/dist/DataTable.js +2724 -0
  5. package/dist/DataTableToolbar.d.ts +28 -0
  6. package/dist/DataTableToolbar.js +132 -0
  7. package/dist/FilterBar.d.ts +24 -0
  8. package/dist/FilterBar.js +681 -0
  9. package/dist/QueryBuilder.d.ts +11 -0
  10. package/dist/QueryBuilder.js +693 -0
  11. package/dist/cell-edit.d.ts +50 -0
  12. package/dist/cell-edit.js +178 -0
  13. package/dist/client-state.d.ts +28 -0
  14. package/dist/client-state.js +57 -0
  15. package/dist/client-view.d.ts +31 -0
  16. package/dist/client-view.js +30 -0
  17. package/dist/column-layout.d.ts +10 -0
  18. package/dist/column-layout.js +34 -0
  19. package/dist/columns.d.ts +108 -0
  20. package/dist/columns.js +217 -0
  21. package/dist/core.d.ts +54 -0
  22. package/dist/core.js +28 -0
  23. package/dist/export.d.ts +14 -0
  24. package/dist/export.js +27 -0
  25. package/dist/facets.d.ts +15 -0
  26. package/dist/facets.js +41 -0
  27. package/dist/filter-bar-state.d.ts +22 -0
  28. package/dist/filter-bar-state.js +128 -0
  29. package/dist/filter-client.d.ts +9 -0
  30. package/dist/filter-client.js +69 -0
  31. package/dist/filter.d.ts +64 -0
  32. package/dist/filter.js +132 -0
  33. package/dist/grouping.d.ts +37 -0
  34. package/dist/grouping.js +126 -0
  35. package/dist/index.d.ts +7 -0
  36. package/dist/index.js +31 -0
  37. package/dist/messages.d.ts +115 -0
  38. package/dist/messages.js +121 -0
  39. package/dist/pagination.d.ts +36 -0
  40. package/dist/pagination.js +102 -0
  41. package/dist/query-builder-state.d.ts +28 -0
  42. package/dist/query-builder-state.js +128 -0
  43. package/dist/requests.d.ts +26 -0
  44. package/dist/requests.js +106 -0
  45. package/dist/row-hierarchy.d.ts +32 -0
  46. package/dist/row-hierarchy.js +170 -0
  47. package/dist/row-identity.d.ts +11 -0
  48. package/dist/row-identity.js +36 -0
  49. package/dist/saved-views.d.ts +52 -0
  50. package/dist/saved-views.js +153 -0
  51. package/dist/search-controller.d.ts +22 -0
  52. package/dist/search-controller.js +75 -0
  53. package/dist/search.d.ts +28 -0
  54. package/dist/search.js +111 -0
  55. package/dist/selection-client.d.ts +9 -0
  56. package/dist/selection-client.js +14 -0
  57. package/dist/selection.d.ts +25 -0
  58. package/dist/selection.js +60 -0
  59. package/dist/server-export.d.ts +27 -0
  60. package/dist/server-export.js +105 -0
  61. package/dist/sorting.d.ts +17 -0
  62. package/dist/sorting.js +58 -0
  63. package/dist/table-state-changes.d.ts +27 -0
  64. package/dist/table-state-changes.js +67 -0
  65. package/dist/table-state.d.ts +20 -0
  66. package/dist/table-state.js +77 -0
  67. package/dist/text-normalization.d.ts +2 -0
  68. package/dist/text-normalization.js +12 -0
  69. package/dist/url-state.d.ts +39 -0
  70. package/dist/url-state.js +75 -0
  71. package/package.json +66 -0
  72. package/src/DataTable.tsx +2322 -0
  73. package/src/DataTableToolbar.tsx +69 -0
  74. package/src/FilterBar.tsx +396 -0
  75. package/src/QueryBuilder.tsx +274 -0
  76. package/src/cell-edit.ts +187 -0
  77. package/src/client-state.ts +52 -0
  78. package/src/client-view.ts +61 -0
  79. package/src/column-layout.ts +47 -0
  80. package/src/columns.ts +271 -0
  81. package/src/core.ts +54 -0
  82. package/src/export.ts +39 -0
  83. package/src/facets.ts +46 -0
  84. package/src/filter-bar-state.ts +118 -0
  85. package/src/filter-client.ts +79 -0
  86. package/src/filter.ts +113 -0
  87. package/src/grouping.ts +185 -0
  88. package/src/index.ts +7 -0
  89. package/src/messages.ts +29 -0
  90. package/src/pagination.ts +81 -0
  91. package/src/query-builder-state.ts +105 -0
  92. package/src/requests.ts +85 -0
  93. package/src/row-hierarchy.ts +280 -0
  94. package/src/row-identity.ts +39 -0
  95. package/src/saved-views.ts +143 -0
  96. package/src/search-controller.ts +61 -0
  97. package/src/search.ts +137 -0
  98. package/src/selection-client.ts +23 -0
  99. package/src/selection.ts +62 -0
  100. package/src/server-export.ts +89 -0
  101. package/src/sorting.ts +63 -0
  102. package/src/styles.css +197 -0
  103. package/src/table-state-changes.ts +51 -0
  104. package/src/table-state.ts +72 -0
  105. package/src/text-normalization.ts +14 -0
  106. package/src/url-state.ts +62 -0
@@ -0,0 +1,2322 @@
1
+ import { Button, Checkbox, ContextMenu, DropdownMenu, EmptyState, Pagination, SearchInput, Skeleton, Toaster, createToaster, useTheme } from "@gemologic/sheen";
2
+ import type { MenuItem, ShortcutAction } from "@gemologic/sheen";
3
+ import { createVirtualizer } from "@tanstack/solid-virtual";
4
+ import type { VirtualItem } from "@tanstack/solid-virtual";
5
+ import { For, Index, Show, createEffect, createMemo, createSignal, createUniqueId, on, onCleanup, onMount } from "solid-js";
6
+ import type { Accessor, JSX } from "solid-js";
7
+ import { changeTableState } from "./table-state-changes.ts";
8
+ import { canMoveColumn, moveColumn, orderColumnStates, placeColumn } from "./column-layout.ts";
9
+ import type { ColumnDropPlacement, ColumnMoveDirection } from "./column-layout.ts";
10
+ import { columnStateSchema, readColumnDefinitions } from "./columns.ts";
11
+ import type { ColumnEditor, ColumnValue, SheenColumns } from "./columns.ts";
12
+ import { createClientView } from "./client-view.ts";
13
+ import type { ClientView } from "./client-view.ts";
14
+ import { formatSearchQuery, parseSearchQuery } from "./search.ts";
15
+ import type { SearchMode } from "./search.ts";
16
+ import { getPageRange, resolvePagination } from "./pagination.ts";
17
+ import type { PageResult, TablePagination } from "./pagination.ts";
18
+ import { createRowIdentity } from "./row-identity.ts";
19
+ import { groupClientRows, normalizeServerGroups } from "./grouping.ts";
20
+ import type { ClientRowGroup, ServerRowGroup } from "./grouping.ts";
21
+ import { createRowHierarchy } from "./row-hierarchy.ts";
22
+ import type { HierarchyRow } from "./row-hierarchy.ts";
23
+ import { createTableRequests } from "./requests.ts";
24
+ import type { TableRequestOutcome, TableRequestSnapshot } from "./requests.ts";
25
+ import { createTableSelection } from "./selection.ts";
26
+ import type { BulkSelection } from "./selection.ts";
27
+ import { parseTableState, serializeState } from "./table-state.ts";
28
+ import type { ColumnState, TableState } from "./table-state.ts";
29
+ import { FilterBar } from "./FilterBar.tsx";
30
+ import { DataTableToolbar } from "./DataTableToolbar.tsx";
31
+ import type { DataTableToolbarAction } from "./DataTableToolbar.tsx";
32
+ import { parseFilter, serializeFilter } from "./filter.ts";
33
+ import type { FilterNode } from "./filter.ts";
34
+ import type { FilterDateEditor } from "./FilterBar.tsx";
35
+ import { createClientExport } from "./export.ts";
36
+ import { selectClientRows } from "./selection-client.ts";
37
+ import { createServerExport } from "./server-export.ts";
38
+ import type { ServerExportOutcome, ServerExportSnapshot, TableExportRequest } from "./server-export.ts";
39
+ import { createCellEdit } from "./cell-edit.ts";
40
+ import type { CellCommitOutcome, CellCommitRequest, CellCommitResult, CellEditSnapshot } from "./cell-edit.ts";
41
+ import { resolveTableMessages } from "./messages.ts";
42
+
43
+ export interface DataTableResult<Row extends object> extends PageResult<Row> {
44
+ readonly facets?: Readonly<Record<string, Readonly<Record<string, number>>>>;
45
+ /** Required for delegated server grouping; describes the accepted page with full-group totals. */
46
+ readonly groups?: readonly ServerRowGroup[];
47
+ }
48
+
49
+ export interface DataTableInitialState {
50
+ readonly search?: string;
51
+ readonly filter?: TableState["filter"];
52
+ readonly sorting?: TableState["sorting"];
53
+ readonly columns?: readonly ColumnState[];
54
+ }
55
+
56
+ export interface DataTableSelectionOptions<Row extends object> {
57
+ readonly mode: "multiple";
58
+ /** Receives a fresh immutable ID or query/exclusion payload after each user change. */
59
+ readonly onChange: (selection: BulkSelection) => void;
60
+ /** Overrides the localized stable-ID label used by each row checkbox. */
61
+ readonly getRowLabel?: (row: Row) => string;
62
+ /** Clear selection and loaded-row eligibility when an account or permission boundary changes. */
63
+ readonly resetKey?: string | number;
64
+ }
65
+
66
+ export interface DataTableGroupingOptions {
67
+ /** Accessor column whose scalar values define first-seen groups. */
68
+ readonly by: string;
69
+ readonly collapsible?: boolean;
70
+ readonly defaultExpanded?: boolean;
71
+ readonly getLabel?: (value: ColumnValue) => string;
72
+ }
73
+
74
+ export interface DataTableHierarchyOptions<Row extends object> {
75
+ /** Return known child rows synchronously. Undefined represents an unloaded subtree. */
76
+ readonly getChildren?: (row: Row) => readonly Row[] | undefined;
77
+ /** Required with onLoadChildren so known leaves are not presented as expandable. */
78
+ readonly hasChildren?: (row: Row) => boolean;
79
+ readonly onLoadChildren?: (row: Row, signal: AbortSignal) => Promise<readonly Row[]>;
80
+ readonly defaultExpanded?: boolean | readonly string[];
81
+ /** Clear expansion and loaded subtrees when an account or permission boundary changes. */
82
+ readonly resetKey?: string | number;
83
+ }
84
+
85
+ export type DataTableExportFormat = "csv" | "json";
86
+
87
+ export interface DataTableExportOptions {
88
+ /** Formats shown in the export menu. Defaults to CSV and JSON. */
89
+ readonly formats?: readonly DataTableExportFormat[];
90
+ /** Download filename without an extension. Defaults to a slug derived from the caption. */
91
+ readonly filename?: string;
92
+ /** Aborts work and revokes the retained artifact when an account or permission boundary changes. */
93
+ readonly resetKey?: string | number;
94
+ }
95
+
96
+ export interface DataTableCellCommitRequest<Row extends object> extends CellCommitRequest<ColumnValue> {
97
+ readonly rowId: string;
98
+ readonly row: Row;
99
+ readonly column: string;
100
+ }
101
+
102
+ export interface DataTableActionContext<Row extends object> {
103
+ /** Immutable explicit-ID or all-matching selection passed to the application action. */
104
+ readonly selection: BulkSelection;
105
+ /** Selected rows that are present in the accepted page/view. Never implies complete query materialization. */
106
+ readonly loadedRows: readonly Row[];
107
+ /** Row that opened a context menu. Omitted for the selection action bar. */
108
+ readonly anchor?: Row;
109
+ }
110
+
111
+ export interface DataTableAction<Row extends object> {
112
+ readonly id: string;
113
+ readonly label: string;
114
+ readonly shortcut?: string;
115
+ readonly tone?: "neutral" | "accent" | "danger" | "success";
116
+ readonly disabled?: boolean | ((context: DataTableActionContext<Row>) => boolean);
117
+ readonly onSelect: (context: DataTableActionContext<Row>) => void;
118
+ }
119
+
120
+ export interface DataTableMobileLayoutOptions {
121
+ /** Number of cards per local page in continuous mode. Numbered tables keep their configured page size. */
122
+ readonly pageSize?: number;
123
+ /** Visible column used as the card heading. Falls back to the first visible column when omitted or hidden. */
124
+ readonly titleColumn?: string;
125
+ }
126
+
127
+ export type DataTableVariant = "integrated" | "framed";
128
+ export type DataTableDensity = "compact" | "comfortable" | "spacious";
129
+
130
+ export interface DataTableSearchOptions {
131
+ /** Visible-to-assistive-technology input label. Defaults to a localized caption-specific label. */
132
+ readonly label?: string;
133
+ /** Input placeholder. Defaults to the resolved label. */
134
+ readonly placeholder?: string;
135
+ /** Trailing delay in milliseconds. Defaults to 120. */
136
+ readonly debounce?: number;
137
+ /** Optional application shortcut, for example mod+f. */
138
+ readonly shortcut?: string;
139
+ /** Enables a visible Smart/Exact control whose Exact mode matches one literal phrase within a searchable column. */
140
+ readonly exactMatch?: boolean;
141
+ }
142
+
143
+ export interface DataTableFilterBarOptions {
144
+ /** Optional date package adapter. Omission keeps the native date-input fallback and table bundle boundary. */
145
+ readonly dateEditor?: FilterDateEditor;
146
+ }
147
+
148
+ interface DataTableBaseProps<Row extends object> {
149
+ readonly columns: SheenColumns<Row>;
150
+ readonly getRowId: (row: Row) => string;
151
+ readonly caption: string;
152
+ /** Framed is a standalone surface. Integrated joins application-pane chrome. DataTablePage supplies integrated context when omitted. */
153
+ readonly variant?: DataTableVariant;
154
+ /** Optional local density for table chrome and rows. Omission inherits the surrounding application density. */
155
+ readonly density?: DataTableDensity;
156
+ readonly pagination?: TablePagination;
157
+ readonly initialState?: DataTableInitialState;
158
+ /** Reactively applies an app-owned accepted filter. Use onAcceptedStateChange to keep table-authored changes synchronized. */
159
+ readonly filter?: FilterNode;
160
+ readonly rowHeight?: string;
161
+ readonly variableRowHeight?: boolean;
162
+ readonly estimatedRowHeight?: number;
163
+ readonly initialViewportHeight?: number;
164
+ readonly class?: string;
165
+ readonly onAcceptedStateChange?: (state: TableState) => void;
166
+ readonly onRowActivate?: (row: Row) => void;
167
+ readonly selection?: DataTableSelectionOptions<Row>;
168
+ /** One action model rendered in both the selection bar and each row context menu. */
169
+ readonly actions?: readonly DataTableAction<Row>[];
170
+ /** Opt into a card presentation below 768px. Continuous results receive bounded local paging. */
171
+ readonly mobileLayout?: boolean | DataTableMobileLayoutOptions;
172
+ readonly grouping?: DataTableGroupingOptions;
173
+ readonly hierarchy?: DataTableHierarchyOptions<Row>;
174
+ /** Configure global search declared by columns. False hides and disables table search. */
175
+ readonly search?: false | DataTableSearchOptions;
176
+ /** Show filters configured by column definitions in the table toolbar. */
177
+ readonly filterBar?: boolean | DataTableFilterBarOptions;
178
+ /** Show the keyboard-accessible visibility, order, pin, and sizing menu. */
179
+ readonly columnControls?: boolean;
180
+ /** Client exports are enabled by default. False hides them; options customize format and filename. */
181
+ readonly export?: false | DataTableExportOptions;
182
+ /** Commits values from columns that declare an editor. Required when any editor is present. */
183
+ readonly onCellCommit?: (request: DataTableCellCommitRequest<Row>, signal: AbortSignal) => Promise<CellCommitResult<ColumnValue, string>>;
184
+ /** Discards drafts and aborts commits when an account or permission boundary changes. */
185
+ readonly editResetKey?: string | number;
186
+ }
187
+
188
+ export interface ClientDataTableProps<Row extends object> extends DataTableBaseProps<Row> {
189
+ readonly mode?: "client";
190
+ readonly data: readonly Row[];
191
+ readonly initialResult?: never;
192
+ readonly onStateChange?: never;
193
+ readonly onExport?: never;
194
+ }
195
+
196
+ export interface ServerDataTableProps<Row extends object> extends DataTableBaseProps<Row> {
197
+ readonly mode: "server";
198
+ readonly pagination: TablePagination;
199
+ readonly data?: never;
200
+ readonly initialResult?: DataTableResult<Row>;
201
+ readonly onStateChange: (state: TableState, signal: AbortSignal) => Promise<DataTableResult<Row>>;
202
+ /** Creates a complete server-side export for the captured accepted query and selection. Without this adapter, export UI is hidden. */
203
+ readonly onExport?: (request: TableExportRequest, signal: AbortSignal) => Promise<Blob>;
204
+ }
205
+
206
+ export type DataTableProps<Row extends object> = ClientDataTableProps<Row> | ServerDataTableProps<Row>;
207
+
208
+ interface StableRow<Row extends object> {
209
+ readonly id: string;
210
+ readonly value: Accessor<Row>;
211
+ readonly update: (row: Row) => boolean;
212
+ }
213
+
214
+ interface ScrollAnchor {
215
+ readonly id: string;
216
+ readonly offset: number;
217
+ }
218
+
219
+ interface RenderedRow<Row extends object> {
220
+ readonly key: string;
221
+ readonly row: Accessor<DisplayRow<Row>>;
222
+ readonly updateRow: (row: DisplayRow<Row>) => void;
223
+ readonly item: Accessor<VirtualItem>;
224
+ readonly updateItem: (item: VirtualItem) => void;
225
+ }
226
+
227
+ interface DisplayDataRow<Row extends object> {
228
+ readonly kind: "data";
229
+ readonly key: string;
230
+ readonly row: StableRow<Row>;
231
+ readonly parentId: string | null;
232
+ readonly depth: number;
233
+ position: number;
234
+ setSize: number;
235
+ readonly canExpand: boolean;
236
+ readonly expanded: boolean;
237
+ readonly unloaded: boolean;
238
+ readonly pending: boolean;
239
+ readonly error: unknown;
240
+ }
241
+
242
+ interface DisplayGroupRow<Row extends object> {
243
+ readonly kind: "group";
244
+ readonly key: string;
245
+ readonly group: ClientRowGroup<Row>;
246
+ readonly label: string;
247
+ readonly position: number;
248
+ readonly setSize: number;
249
+ readonly expanded: boolean;
250
+ }
251
+
252
+ type DisplayRow<Row extends object> = DisplayDataRow<Row> | DisplayGroupRow<Row>;
253
+
254
+ function displayDataRow<Row extends object>(row: DisplayRow<Row>): DisplayDataRow<Row> | undefined {
255
+ return row.kind === "data" ? row : undefined;
256
+ }
257
+
258
+ function displayGroupRow<Row extends object>(row: DisplayRow<Row>): DisplayGroupRow<Row> | undefined {
259
+ return row.kind === "group" ? row : undefined;
260
+ }
261
+
262
+ function createStableRows<Row extends object>(getRowId: (row: Row) => string): (rows: readonly Row[]) => readonly StableRow<Row>[] {
263
+ const identity = createRowIdentity(getRowId);
264
+ const cache = new Map<string, StableRow<Row>>();
265
+ const [revision, setRevision] = createSignal(0);
266
+ return rows => {
267
+ const ids = identity.resolveIds(rows);
268
+ const retained = new Set<string>();
269
+ const resolved: StableRow<Row>[] = [];
270
+ let changed = false;
271
+ for (let index = 0; index < rows.length; index++) {
272
+ const row = rows[index]!;
273
+ const id = ids[index]!;
274
+ retained.add(id);
275
+ const existing = cache.get(id);
276
+ if (existing) {
277
+ changed = existing.update(row) || changed;
278
+ resolved.push(existing);
279
+ continue;
280
+ }
281
+ let current = row;
282
+ const record: StableRow<Row> = Object.freeze({
283
+ id,
284
+ value: (): Row => {
285
+ revision();
286
+ return current;
287
+ },
288
+ update: (next: Row): boolean => {
289
+ if (Object.is(current, next)) return false;
290
+ current = next;
291
+ return true;
292
+ },
293
+ });
294
+ cache.set(id, record);
295
+ resolved.push(record);
296
+ }
297
+ for (const id of cache.keys()) if (!retained.has(id)) cache.delete(id);
298
+ if (changed) setRevision(value => value + 1);
299
+ return Object.freeze(resolved);
300
+ };
301
+ }
302
+
303
+ interface ClientStableRows<Row extends object> {
304
+ readonly update: (rows: readonly Row[]) => void;
305
+ readonly resolve: (row: Row, index: number) => StableRow<Row>;
306
+ readonly has: (id: string) => boolean;
307
+ }
308
+
309
+ function createClientStableRows<Row extends object>(getRowId: (row: Row) => string): ClientStableRows<Row> {
310
+ const cache = new Map<string, StableRow<Row>>();
311
+ let retained: ReadonlySet<string> = new Set();
312
+ const known = new WeakMap<Row, string>();
313
+ const [revision, setRevision] = createSignal(0);
314
+ function create(id: string, row: Row): StableRow<Row> {
315
+ let current = row;
316
+ const record: StableRow<Row> = Object.freeze({
317
+ id,
318
+ value: (): Row => {
319
+ revision();
320
+ return current;
321
+ },
322
+ update: (next: Row): boolean => {
323
+ if (Object.is(current, next)) return false;
324
+ current = next;
325
+ return true;
326
+ },
327
+ });
328
+ cache.set(id, record);
329
+ known.set(row, id);
330
+ return record;
331
+ }
332
+ return Object.freeze({
333
+ update(rows: readonly Row[]): void {
334
+ if (!Array.isArray(rows)) throw new Error("Table rows must be an array");
335
+ const ids = new Set<string>();
336
+ let changed = false;
337
+ for (let index = 0; index < rows.length; index++) {
338
+ const row = rows[index];
339
+ if (typeof row !== "object" || row === null) throw new Error(`rows[${index}] must be an object`);
340
+ const id = getRowId(row);
341
+ if (typeof id !== "string" || !id || id.trim() !== id) throw new Error(`rows[${index}] has an invalid stable ID`);
342
+ if (ids.has(id)) throw new Error(`rows[${index}] duplicates row ID ${id}`);
343
+ const prior = known.get(row);
344
+ if (prior !== undefined && prior !== id) throw new Error(`rows[${index}] changed stable ID from ${prior} to ${id}`);
345
+ ids.add(id);
346
+ const existing = cache.get(id);
347
+ if (existing) {
348
+ known.set(row, id);
349
+ changed = existing.update(row) || changed;
350
+ }
351
+ }
352
+ for (const id of cache.keys()) if (!ids.has(id)) cache.delete(id);
353
+ retained = ids;
354
+ if (changed) setRevision(value => value + 1);
355
+ },
356
+ resolve(row: Row, index: number): StableRow<Row> {
357
+ const id = getRowId(row);
358
+ if (!retained.has(id)) throw new Error(`Client result row at index ${index} is not part of the supplied data`);
359
+ return cache.get(id) ?? create(id, row);
360
+ },
361
+ has: (id: string) => retained.has(id),
362
+ });
363
+ }
364
+
365
+ function defaultCell(value: ColumnValue): JSX.Element {
366
+ if (value === null) return "";
367
+ if (typeof value === "boolean") return value ? "Yes" : "No";
368
+ return String(value);
369
+ }
370
+
371
+ function errorMessage(value: unknown): string {
372
+ return value instanceof Error ? value.message : "Table request failed";
373
+ }
374
+
375
+ function exportFormats(options: false | DataTableExportOptions | undefined): readonly DataTableExportFormat[] {
376
+ if (options === false) return Object.freeze([]);
377
+ const formats = options?.formats ?? ["csv", "json"];
378
+ if (!Array.isArray(formats) || formats.length === 0) throw new Error("DataTable export formats must be a nonempty array");
379
+ const unique = new Set<DataTableExportFormat>();
380
+ for (const format of formats) {
381
+ if (format !== "csv" && format !== "json") throw new Error("DataTable export formats must contain only csv or json");
382
+ if (unique.has(format)) throw new Error("DataTable export formats must be unique");
383
+ unique.add(format);
384
+ }
385
+ return Object.freeze([...unique]);
386
+ }
387
+
388
+ function exportBaseName(caption: string, options: false | DataTableExportOptions | undefined): string {
389
+ const supplied = options === false ? undefined : options?.filename;
390
+ if (supplied !== undefined) {
391
+ if (typeof supplied !== "string" || !supplied.trim() || /[/\\]/u.test(supplied)) throw new Error("DataTable export filename must be nonempty and cannot contain path separators");
392
+ return supplied.trim();
393
+ }
394
+ return caption.normalize("NFKD").replaceAll(/[^\p{Letter}\p{Number}]+/gu, "-").replaceAll(/^-|-$/g, "").toLocaleLowerCase() || "table";
395
+ }
396
+
397
+ function exportResetKey(options: false | DataTableExportOptions | undefined): string | number | undefined {
398
+ if (options === false) return undefined;
399
+ const key = options?.resetKey;
400
+ if (typeof key === "number" && !Number.isFinite(key)) throw new Error("DataTable export resetKey must be a finite number or string");
401
+ return key;
402
+ }
403
+
404
+ function editorAccepts<Row extends object>(editor: ColumnEditor<Row>, value: ColumnValue): boolean {
405
+ if (value === null) return editor.nullable === true;
406
+ if (editor.type === "text") return typeof value === "string";
407
+ if (editor.type === "number") return typeof value === "number";
408
+ if (editor.type === "boolean") return typeof value === "boolean";
409
+ if (editor.type === "select") return typeof value === "string" && editor.options.includes(value);
410
+ return false;
411
+ }
412
+
413
+ function filterActive(filter: FilterNode): boolean {
414
+ if (filter.kind === "and" || filter.kind === "or") return filter.children.some(filterActive);
415
+ return true;
416
+ }
417
+
418
+ function validateActions<Row extends object>(actions: readonly DataTableAction<Row>[]): readonly DataTableAction<Row>[] {
419
+ if (!Array.isArray(actions)) throw new Error("DataTable actions must be an array");
420
+ const ids = new Set<string>();
421
+ for (const action of actions) {
422
+ if (typeof action.id !== "string" || !action.id.trim() || ids.has(action.id)) throw new Error("DataTable action IDs must be unique nonempty strings");
423
+ ids.add(action.id);
424
+ if (typeof action.label !== "string" || !action.label.trim()) throw new Error(`DataTable action ${action.id} requires a nonempty label`);
425
+ if (typeof action.onSelect !== "function") throw new Error(`DataTable action ${action.id} requires onSelect`);
426
+ if (action.shortcut !== undefined && (typeof action.shortcut !== "string" || !action.shortcut.trim())) throw new Error(`DataTable action ${action.id} has an invalid shortcut`);
427
+ if (action.disabled !== undefined && typeof action.disabled !== "boolean" && typeof action.disabled !== "function") throw new Error(`DataTable action ${action.id} has an invalid disabled value`);
428
+ if (action.tone !== undefined && action.tone !== "neutral" && action.tone !== "accent" && action.tone !== "danger" && action.tone !== "success") throw new Error(`DataTable action ${action.id} has an invalid tone`);
429
+ }
430
+ return actions;
431
+ }
432
+
433
+ interface ResolvedMobileLayout {
434
+ readonly pageSize: number;
435
+ readonly titleColumn?: string;
436
+ }
437
+
438
+ interface ResolvedSearchOptions {
439
+ readonly label?: string;
440
+ readonly placeholder?: string;
441
+ readonly debounce: number;
442
+ readonly shortcut?: string;
443
+ readonly exactMatch: boolean;
444
+ }
445
+
446
+ function resolveSearchOptions(value: false | DataTableSearchOptions | undefined, searchableColumns: number): ResolvedSearchOptions | null {
447
+ if (value === false || (value === undefined && searchableColumns === 0)) return null;
448
+ if (searchableColumns === 0) throw new Error("DataTable search requires at least one searchable column");
449
+ if (value === undefined) return Object.freeze({ debounce: 120, exactMatch: false });
450
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("DataTable search must be false or an options object");
451
+ const prototype = Object.getPrototypeOf(value);
452
+ if (prototype !== Object.prototype && prototype !== null) throw new Error("DataTable search must be a plain options object");
453
+ for (const key of Object.keys(value)) if (key !== "label" && key !== "placeholder" && key !== "debounce" && key !== "shortcut" && key !== "exactMatch") throw new Error(`DataTable search has unknown field ${key}`);
454
+ if (value.label !== undefined && (typeof value.label !== "string" || !value.label.trim())) throw new Error("DataTable search label must be a nonempty string");
455
+ if (value.placeholder !== undefined && (typeof value.placeholder !== "string" || !value.placeholder.trim())) throw new Error("DataTable search placeholder must be a nonempty string");
456
+ const debounce = value.debounce ?? 120;
457
+ if (!Number.isFinite(debounce) || debounce < 0 || debounce > 5_000) throw new Error("DataTable search debounce must be from 0 to 5000 milliseconds");
458
+ if (value.shortcut !== undefined && (typeof value.shortcut !== "string" || !value.shortcut.trim())) throw new Error("DataTable search shortcut must be a nonempty string");
459
+ if (value.exactMatch !== undefined && typeof value.exactMatch !== "boolean") throw new Error("DataTable search exactMatch must be boolean");
460
+ return Object.freeze({
461
+ debounce,
462
+ exactMatch: value.exactMatch ?? false,
463
+ ...(value.label === undefined ? {} : { label: value.label }),
464
+ ...(value.placeholder === undefined ? {} : { placeholder: value.placeholder }),
465
+ ...(value.shortcut === undefined ? {} : { shortcut: value.shortcut }),
466
+ });
467
+ }
468
+
469
+ function resolveMobileLayout(value: boolean | DataTableMobileLayoutOptions | undefined): ResolvedMobileLayout | null {
470
+ if (value === undefined || value === false) return null;
471
+ if (value === true) return Object.freeze({ pageSize: 20 });
472
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("DataTable mobileLayout must be boolean or an options object");
473
+ for (const key of Object.keys(value)) if (key !== "pageSize" && key !== "titleColumn") throw new Error(`DataTable mobileLayout has unknown field ${key}`);
474
+ const pageSize = value.pageSize ?? 20;
475
+ if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 100) throw new Error("DataTable mobileLayout pageSize must be an integer from 1 to 100");
476
+ if (value.titleColumn !== undefined && (typeof value.titleColumn !== "string" || !value.titleColumn.trim())) throw new Error("DataTable mobileLayout titleColumn must be a nonempty string");
477
+ return Object.freeze({ pageSize, ...(value.titleColumn ? { titleColumn: value.titleColumn } : {}) });
478
+ }
479
+
480
+ function clientFacetRecord<Row>(view: ClientView<Row>): Readonly<Record<string, Readonly<Record<string, number>>>> {
481
+ const result: Record<string, Readonly<Record<string, number>>> = {};
482
+ for (const facet of view.facets) {
483
+ const options: Record<string, number> = {};
484
+ for (const option of facet.options) options[option.value] = option.count;
485
+ result[facet.column] = Object.freeze(options);
486
+ }
487
+ return Object.freeze(result);
488
+ }
489
+
490
+ function initialTableState<Row extends object>(props: DataTableProps<Row>): TableState {
491
+ const schema = columnStateSchema(props.columns);
492
+ const definitions = readColumnDefinitions(props.columns);
493
+ const pagination = resolvePagination(props.mode ?? "client", props.pagination);
494
+ const state = parseTableState({
495
+ search: props.initialState?.search ?? "",
496
+ filter: props.filter ?? props.initialState?.filter ?? { kind: "and", children: [] },
497
+ sorting: props.initialState?.sorting ?? [],
498
+ pagination,
499
+ columns: props.initialState?.columns ?? definitions.map(column => ({ id: column.id, visible: column.visible, width: typeof column.width === "number" ? column.width : null, pin: column.pin })),
500
+ }, schema);
501
+ for (const columnState of state.columns) {
502
+ const definition = definitions.find(column => column.id === columnState.id);
503
+ if (!definition) throw new Error(`Unknown table column: ${columnState.id}`);
504
+ if (columnState.width !== null && ((definition.minWidth !== null && columnState.width < definition.minWidth) || (definition.maxWidth !== null && columnState.width > definition.maxWidth))) {
505
+ throw new Error(`Initial width for ${columnState.id} must be within its column bounds`);
506
+ }
507
+ if (columnState.pin !== false && columnState.width === null && typeof definition.width !== "number") {
508
+ throw new Error(`Pinned column ${columnState.id} requires an explicit numeric width`);
509
+ }
510
+ }
511
+ return state;
512
+ }
513
+
514
+ function samePagination(left: TablePagination, right: TablePagination): boolean {
515
+ return left === false ? right === false : right !== false && left.pageIndex === right.pageIndex && left.pageSize === right.pageSize;
516
+ }
517
+
518
+ function columnTrack(width: number | "fill" | "content", minimum: number | null, maximum: number | null): string {
519
+ const min = minimum ?? 80;
520
+ if (typeof width === "number") return `${width}px`;
521
+ if (width === "content") return `minmax(${min}px, max-content)`;
522
+ return `minmax(${min}px, ${maximum === null ? "1fr" : `min(1fr, ${maximum}px)`})`;
523
+ }
524
+
525
+ function clampColumnWidth(value: number, minimum: number | null, maximum: number | null): number {
526
+ return Math.min(maximum ?? 4096, Math.max(minimum ?? 80, Math.round(value)));
527
+ }
528
+
529
+ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.Element {
530
+ if (props.mode === "server" && typeof props.onStateChange !== "function") throw new Error("Server mode requires onStateChange");
531
+ if (props.mode !== "server" && !Array.isArray(props.data)) throw new Error("Client mode requires a complete data array");
532
+ if (props.mode !== "server" && props.initialResult !== undefined) throw new Error("initialResult is available only in server mode");
533
+ if (props.selection && (props.selection.mode !== "multiple" || typeof props.selection.onChange !== "function")) throw new Error("DataTable selection requires multiple mode and onChange");
534
+ if (typeof props.selection?.resetKey === "number" && !Number.isFinite(props.selection.resetKey)) throw new Error("DataTable selection resetKey must be a finite number or string");
535
+ if (props.grouping && props.hierarchy) throw new Error("DataTable grouping and hierarchy are separate presentation modes");
536
+ if (props.grouping && props.mode !== "server" && props.pagination !== false) throw new Error("Client grouping requires complete continuous data with pagination=false");
537
+ if (props.grouping && (typeof props.grouping.by !== "string" || !props.grouping.by.trim())) throw new Error("DataTable grouping requires a column ID");
538
+ if (props.grouping?.getLabel !== undefined && typeof props.grouping.getLabel !== "function") throw new Error("DataTable grouping getLabel must be a function");
539
+ if (props.hierarchy && !props.hierarchy.getChildren && !props.hierarchy.onLoadChildren) throw new Error("DataTable hierarchy requires getChildren or onLoadChildren");
540
+ if (props.hierarchy?.onLoadChildren && !props.hierarchy.hasChildren) throw new Error("Async DataTable hierarchy requires hasChildren");
541
+ if (typeof props.hierarchy?.resetKey === "number" && !Number.isFinite(props.hierarchy.resetKey)) throw new Error("DataTable hierarchy resetKey must be a finite number or string");
542
+ if (typeof props.editResetKey === "number" && !Number.isFinite(props.editResetKey)) throw new Error("DataTable editResetKey must be a finite number or string");
543
+ const variant = () => {
544
+ const value: unknown = props.variant;
545
+ if (value !== undefined && value !== "integrated" && value !== "framed") throw new Error("DataTable variant must be integrated or framed");
546
+ return value;
547
+ };
548
+ const density = (): DataTableDensity | undefined => {
549
+ const value: unknown = props.density;
550
+ if (value !== undefined && value !== "compact" && value !== "comfortable" && value !== "spacious") throw new Error("DataTable density must be compact, comfortable, or spacious");
551
+ return value;
552
+ };
553
+ const actions = createMemo(() => validateActions(props.actions ?? []));
554
+ const configuredExportFormats = exportFormats(props.export);
555
+ const configuredExportBaseName = exportBaseName(props.caption, props.export);
556
+ let configuredExportResetKey = exportResetKey(props.export);
557
+ const schema = columnStateSchema(props.columns);
558
+ const tableId = createUniqueId();
559
+ const theme = useTheme();
560
+ const locale = createMemo(() => theme.state().locale);
561
+ const messages = createMemo(() => resolveTableMessages(theme.messages()));
562
+ const definitions = readColumnDefinitions(props.columns);
563
+ const definitionById = new Map(definitions.map(column => [column.id, column]));
564
+ const searchableDefinitions = definitions.filter(column => column.search !== null);
565
+ const searchableDefinitionById = new Map(searchableDefinitions.map(column => [column.id, column]));
566
+ const searchOptions = resolveSearchOptions(props.search, searchableDefinitions.length);
567
+ const mobileLayout = resolveMobileLayout(props.mobileLayout);
568
+ if (mobileLayout?.titleColumn && !definitions.some(column => column.id === mobileLayout.titleColumn)) throw new Error(`Unknown mobileLayout title column: ${mobileLayout.titleColumn}`);
569
+ const editableDefinitions = definitions.filter(column => column.editor !== null);
570
+ if (editableDefinitions.length > 0 && !props.onCellCommit) throw new Error("DataTable editable columns require onCellCommit");
571
+ if (editableDefinitions.length === 0 && props.onCellCommit) throw new Error("DataTable onCellCommit requires at least one editable column");
572
+ for (const column of editableDefinitions) {
573
+ if (!column.accessor || !column.editor) throw new Error(`Editable column ${column.id} requires an accessor and editor`);
574
+ }
575
+ const editToaster = props.onCellCommit ? createToaster() : undefined;
576
+ const initialState = initialTableState(props);
577
+ const groupingColumn = props.grouping ? definitions.find(column => column.id === props.grouping?.by) : undefined;
578
+ if (props.grouping && !groupingColumn?.accessor) throw new Error(`Grouping column ${props.grouping.by} must be an accessor column`);
579
+ const selection = props.selection ? createTableSelection(initialState.filter, schema.filterColumns) : undefined;
580
+ const [selectionRevision, setSelectionRevision] = createSignal(0);
581
+ let selectionAnchorId: string | undefined;
582
+ let selectionSearch = initialState.search;
583
+ let selectionResetKey = props.selection?.resetKey;
584
+ const hierarchy = props.hierarchy ? createRowHierarchy<Row>({
585
+ getRowId: props.getRowId,
586
+ ...(props.hierarchy.getChildren ? { getChildren: props.hierarchy.getChildren } : {}),
587
+ ...(props.hierarchy.hasChildren ? { canLoadChildren: props.hierarchy.hasChildren } : {}),
588
+ ...(props.hierarchy.onLoadChildren ? { loadChildren: props.hierarchy.onLoadChildren } : {}),
589
+ ...(props.hierarchy.defaultExpanded !== undefined ? { defaultExpanded: props.hierarchy.defaultExpanded } : {}),
590
+ }) : undefined;
591
+ const [hierarchyRevision, setHierarchyRevision] = createSignal(0);
592
+ let hierarchyResetKey = props.hierarchy?.resetKey;
593
+ const groupExpansion = new Map<string, boolean>();
594
+ const [groupRevision, setGroupRevision] = createSignal(0);
595
+ const [clientState, setClientState] = createSignal(initialState);
596
+ const [searchDraft, setSearchDraft] = createSignal(initialState.search);
597
+ const [searchScheduled, setSearchScheduled] = createSignal(false);
598
+ const [layoutColumns, setLayoutColumns] = createSignal(initialState.columns);
599
+ const [serverRevision, setServerRevision] = createSignal(0);
600
+ const [exportRevision, setExportRevision] = createSignal(0);
601
+ const [clientExportError, setClientExportError] = createSignal<unknown>(null);
602
+ const [lastDownload, setLastDownload] = createSignal<{ readonly href: string; readonly filename: string }>();
603
+ const [coldVisible, setColdVisible] = createSignal(false);
604
+ const [refreshVisible, setRefreshVisible] = createSignal(false);
605
+ const [mobilePageIndex, setMobilePageIndex] = createSignal(0);
606
+ let root: HTMLElement | undefined;
607
+ let viewport: HTMLDivElement | undefined;
608
+ let mobileViewport: HTMLDivElement | undefined;
609
+ let tableElement: HTMLTableElement | undefined;
610
+ let searchTimer: number | undefined;
611
+ let searchComposing = false;
612
+
613
+ const requests = props.mode === "server" && props.onStateChange
614
+ ? createTableRequests<TableState, DataTableResult<Row>>(props.onStateChange, props.initialResult ? { state: initialState, result: props.initialResult } : undefined)
615
+ : undefined;
616
+ const serverExports = props.mode === "server" && props.onExport
617
+ ? createServerExport<Blob>(schema, async (request, signal) => {
618
+ const artifact = await props.onExport?.(request, signal);
619
+ if (!(artifact instanceof Blob)) throw new Error("DataTable onExport must resolve to a Blob");
620
+ return artifact;
621
+ })
622
+ : undefined;
623
+ const serverSnapshot = (): TableRequestSnapshot<TableState, DataTableResult<Row>> | undefined => {
624
+ serverRevision();
625
+ return requests?.getSnapshot();
626
+ };
627
+
628
+ const getValue = (row: Row, columnId: string): ColumnValue => {
629
+ const column = definitionById.get(columnId);
630
+ return column?.accessor?.(row) ?? null;
631
+ };
632
+ const getSearchValue = (row: Row, columnId: string): string | number | null => {
633
+ const column = searchableDefinitionById.get(columnId);
634
+ return column?.search?.(row) ?? null;
635
+ };
636
+ const clientView = createMemo<ClientView<Row> | undefined>(() => props.mode === "server" ? undefined : createClientView(props.data ?? [], clientState(), {
637
+ locale: locale(),
638
+ searchColumns: searchableDefinitions.map(column => column.id),
639
+ exactMatch: searchOptions?.exactMatch ?? false,
640
+ filterColumns: schema.filterColumns,
641
+ sortColumns: schema.sortColumns,
642
+ getValue,
643
+ getSearchValue,
644
+ }));
645
+
646
+ createEffect(() => {
647
+ const view = clientView();
648
+ if (!view || samePagination(clientState().pagination, view.pagination)) return;
649
+ setClientState(state => parseTableState({ ...state, pagination: view.pagination }, schema));
650
+ });
651
+
652
+ onMount(() => {
653
+ if (!requests || serverSnapshot()?.accepted) return;
654
+ const completion = requests.request(initialState);
655
+ setServerRevision(revision => revision + 1);
656
+ void completion.finally(() => setServerRevision(revision => revision + 1));
657
+ });
658
+ createEffect(() => {
659
+ const nextResetKey = exportResetKey(props.export);
660
+ if (Object.is(nextResetKey, configuredExportResetKey)) return;
661
+ configuredExportResetKey = nextResetKey;
662
+ serverExports?.clear();
663
+ setExportRevision(revision => revision + 1);
664
+ setClientExportError(null);
665
+ const download = lastDownload();
666
+ if (download) URL.revokeObjectURL(download.href);
667
+ setLastDownload(undefined);
668
+ });
669
+ onCleanup(() => {
670
+ if (searchTimer !== undefined) window.clearTimeout(searchTimer);
671
+ requests?.dispose();
672
+ hierarchy?.dispose();
673
+ serverExports?.dispose();
674
+ const download = lastDownload();
675
+ if (download) URL.revokeObjectURL(download.href);
676
+ });
677
+
678
+ const acceptedState = createMemo<TableState>(() => {
679
+ const state = serverSnapshot()?.accepted?.state ?? clientState();
680
+ return Object.freeze({ ...state, columns: layoutColumns() });
681
+ });
682
+ const result = (): DataTableResult<Row> => {
683
+ const accepted = serverSnapshot()?.accepted?.result;
684
+ if (accepted) return accepted;
685
+ const view = clientView();
686
+ return view ? { rows: view.rows, total: view.total, facets: clientFacetRecord(view) } : { rows: [], total: 0 };
687
+ };
688
+ const acceptedAvailable = (): boolean => props.mode !== "server" || serverSnapshot()?.accepted !== null;
689
+ const busy = (): boolean => searchScheduled() || (serverSnapshot()?.pending ?? false);
690
+ const pending = (): boolean => busy() || searchDraft() !== acceptedState().search || Boolean(acceptedAvailable() && serverSnapshot()?.requested);
691
+ const previous = (): boolean => pending() && acceptedAvailable();
692
+ const error = (): unknown => serverSnapshot()?.error;
693
+
694
+ onMount(() => {
695
+ createEffect(() => {
696
+ const waiting = busy();
697
+ const accepted = acceptedAvailable();
698
+ setColdVisible(false);
699
+ setRefreshVisible(false);
700
+ if (!waiting) return;
701
+ const timer = window.setTimeout(() => {
702
+ if (accepted) setRefreshVisible(true);
703
+ else setColdVisible(true);
704
+ }, accepted ? 500 : 200);
705
+ onCleanup(() => window.clearTimeout(timer));
706
+ });
707
+ });
708
+
709
+ async function transition(next: TableState): Promise<TableRequestOutcome | "client"> {
710
+ if (!requests) {
711
+ setClientState(next);
712
+ props.onAcceptedStateChange?.(Object.freeze({ ...next, columns: layoutColumns() }));
713
+ return "client";
714
+ }
715
+ const completion = requests.request(next);
716
+ setServerRevision(revision => revision + 1);
717
+ const outcome = await completion;
718
+ setServerRevision(revision => revision + 1);
719
+ const accepted = requests.getSnapshot().accepted;
720
+ if (outcome === "accepted" && accepted) props.onAcceptedStateChange?.(Object.freeze({ ...accepted.state, columns: layoutColumns() }));
721
+ return outcome;
722
+ }
723
+
724
+ createEffect(on(() => props.filter, filter => {
725
+ if (filter === undefined) return;
726
+ const parsed = parseFilter(filter, schema.filterColumns);
727
+ const current = serverSnapshot()?.requested ?? acceptedState();
728
+ if (serializeFilter(parsed, schema.filterColumns) === serializeFilter(current.filter, schema.filterColumns)) return;
729
+ const pagination = current.pagination === false ? false : { ...current.pagination, pageIndex: 0 };
730
+ const next = parseTableState({ ...current, filter: parsed, pagination }, schema);
731
+ setMobilePageIndex(0);
732
+ void transition(next).then(outcome => {
733
+ if (outcome === "accepted" || outcome === "client") viewport?.scrollTo({ top: 0 });
734
+ });
735
+ }, { defer: true }));
736
+
737
+ const searchLabel = () => (searchOptions?.label ?? messages().searchTable).replaceAll("{caption}", props.caption);
738
+ const searchPlaceholder = () => (searchOptions?.placeholder ?? searchLabel()).replaceAll("{caption}", props.caption);
739
+ const searchShortcut = createMemo<ShortcutAction | undefined>(() => searchOptions?.shortcut ? Object.freeze({
740
+ keys: searchOptions.shortcut,
741
+ scope: "global",
742
+ label: searchLabel(),
743
+ group: messages().tableShortcuts,
744
+ }) : undefined);
745
+ const searchQuery = createMemo(() => parseSearchQuery(searchDraft(), searchOptions?.exactMatch ?? false));
746
+ const searchMode = () => searchQuery().mode;
747
+ const searchModeItems = createMemo<readonly MenuItem[]>(() => [{
748
+ kind: "radio",
749
+ id: "search-mode",
750
+ label: messages().searchMatchMode,
751
+ value: searchMode(),
752
+ onValueChange: value => changeSearchMode(value),
753
+ options: [
754
+ { id: "ranked", label: messages().searchRanked },
755
+ { id: "exact", label: messages().searchExact },
756
+ ],
757
+ }]);
758
+
759
+ function changeSearchMode(value: string): void {
760
+ if (value !== "ranked" && value !== "exact") throw new Error(`Unsupported DataTable search mode ${JSON.stringify(value)}`);
761
+ const mode: SearchMode = value;
762
+ updateSearchDraft(formatSearchQuery(searchQuery().value, mode));
763
+ }
764
+
765
+ function cancelSearchSchedule(): void {
766
+ if (searchTimer !== undefined) window.clearTimeout(searchTimer);
767
+ searchTimer = undefined;
768
+ }
769
+
770
+ function scheduleSearch(query: string): void {
771
+ if (!searchOptions) return;
772
+ cancelSearchSchedule();
773
+ const request = serverSnapshot();
774
+ if (query === acceptedState().search && (!request?.pending || request.requested?.search === query)) {
775
+ setSearchScheduled(false);
776
+ return;
777
+ }
778
+ setSearchScheduled(true);
779
+ searchTimer = window.setTimeout(() => {
780
+ searchTimer = undefined;
781
+ if (searchComposing || searchDraft() !== query) return;
782
+ setSearchScheduled(false);
783
+ const requested = serverSnapshot()?.requested;
784
+ const basis = requested ? Object.freeze({ ...requested, columns: layoutColumns() }) : acceptedState();
785
+ const next = changeTableState(basis, { kind: "query", change: { kind: "search", value: query } }, schema);
786
+ setMobilePageIndex(0);
787
+ void transition(next).then(outcome => {
788
+ if (outcome === "accepted" || outcome === "client") viewport?.scrollTo({ top: 0 });
789
+ });
790
+ }, searchOptions.debounce);
791
+ }
792
+
793
+ function updateSearchDraft(query: string): void {
794
+ setSearchDraft(query);
795
+ if (searchComposing) {
796
+ cancelSearchSchedule();
797
+ setSearchScheduled(false);
798
+ return;
799
+ }
800
+ scheduleSearch(query);
801
+ }
802
+
803
+ function startSearchComposition(): void {
804
+ searchComposing = true;
805
+ cancelSearchSchedule();
806
+ setSearchScheduled(false);
807
+ }
808
+
809
+ function finishSearchComposition(query: string): void {
810
+ searchComposing = false;
811
+ setSearchDraft(query);
812
+ scheduleSearch(query);
813
+ }
814
+
815
+ function requestPage(pageIndex: number): void {
816
+ const current = acceptedState();
817
+ if (current.pagination === false || pending()) return;
818
+ const next = changeTableState(current, { kind: "query", change: { kind: "pagination", value: { ...current.pagination, pageIndex } } }, schema);
819
+ void transition(next).then(outcome => {
820
+ if (outcome !== "accepted" && outcome !== "client") return;
821
+ viewport?.scrollTo({ top: 0 });
822
+ mobileViewport?.scrollIntoView({ block: "nearest" });
823
+ });
824
+ }
825
+
826
+ function requestSort(column: string, multiple: boolean): void {
827
+ const requested = serverSnapshot()?.requested;
828
+ const basis = requested ? Object.freeze({ ...requested, columns: layoutColumns() }) : acceptedState();
829
+ const next = changeTableState(basis, { kind: "sortCycle", column, multiple }, schema);
830
+ setMobilePageIndex(0);
831
+ void transition(next);
832
+ }
833
+
834
+ function requestFilter(filter: FilterNode): void {
835
+ if (pending()) return;
836
+ const next = changeTableState(acceptedState(), { kind: "query", change: { kind: "filter", value: filter } }, schema);
837
+ setMobilePageIndex(0);
838
+ void transition(next).then(outcome => { if (outcome === "accepted" || outcome === "client") viewport?.scrollTo({ top: 0 }); });
839
+ }
840
+
841
+ function clearQuery(): void {
842
+ if (pending()) return;
843
+ cancelSearchSchedule();
844
+ setSearchScheduled(false);
845
+ setSearchDraft("");
846
+ const current = acceptedState();
847
+ const pagination = current.pagination === false ? false : { ...current.pagination, pageIndex: 0 };
848
+ const next = parseTableState({ ...current, search: "", filter: { kind: "and", children: [] }, pagination }, schema);
849
+ setMobilePageIndex(0);
850
+ void transition(next).then(outcome => {
851
+ if (outcome === "accepted" || outcome === "client") queueMicrotask(() => {
852
+ const mobileTarget = mobileViewport && mobileViewport.getClientRects().length > 0 ? mobileViewport : undefined;
853
+ (mobileTarget ?? viewport)?.focus({ preventScroll: true });
854
+ });
855
+ });
856
+ }
857
+
858
+ function retry(): void {
859
+ if (!requests || busy()) return;
860
+ const completion = requests.retry();
861
+ setServerRevision(revision => revision + 1);
862
+ void completion.then(outcome => {
863
+ setServerRevision(revision => revision + 1);
864
+ const accepted = requests.getSnapshot().accepted;
865
+ if (outcome === "accepted" && accepted) props.onAcceptedStateChange?.(Object.freeze({ ...accepted.state, columns: layoutColumns() }));
866
+ });
867
+ }
868
+
869
+ const reconcileRows = createStableRows(props.getRowId);
870
+ const clientStableRows = createClientStableRows(props.getRowId);
871
+ const flatDisplayCache = new Map<string, DisplayDataRow<Row>>();
872
+ const clientRowIndex = createMemo(() => {
873
+ if (props.mode === "server") return undefined;
874
+ const source = props.data ?? [];
875
+ clientStableRows.update(source);
876
+ for (const id of flatDisplayCache.keys()) if (!clientStableRows.has(id)) flatDisplayCache.delete(id);
877
+ return clientStableRows;
878
+ });
879
+ function stableResultRows(rows: readonly Row[]): readonly StableRow<Row>[] {
880
+ const client = clientRowIndex();
881
+ if (!client) return reconcileRows(rows);
882
+ return rows.map((row, index) => client.resolve(row, index));
883
+ }
884
+ function flatDisplayRow(row: StableRow<Row>, index: number, setSize: number): DisplayDataRow<Row> {
885
+ const existing = flatDisplayCache.get(row.id);
886
+ if (existing) {
887
+ existing.position = index + 1;
888
+ existing.setSize = setSize;
889
+ return existing;
890
+ }
891
+ const created: DisplayDataRow<Row> = { 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 };
892
+ flatDisplayCache.set(row.id, created);
893
+ return created;
894
+ }
895
+ const groupNumberFormatter = createMemo(() => new Intl.NumberFormat(locale()));
896
+ function groupLabel(group: ClientRowGroup<Row>): string {
897
+ const supplied = props.grouping?.getLabel?.(group.value);
898
+ const label = supplied ?? (group.value === null ? messages().groupMissing : typeof group.value === "number" ? groupNumberFormatter().format(group.value) : String(group.value));
899
+ if (typeof label !== "string" || !label.trim()) throw new Error(`Group ${group.id} requires a nonempty label`);
900
+ return label;
901
+ }
902
+ function groupExpanded(id: string): boolean {
903
+ groupRevision();
904
+ const existing = groupExpansion.get(id);
905
+ if (existing !== undefined) return existing;
906
+ const initial = props.grouping?.collapsible === false || props.grouping?.defaultExpanded !== false;
907
+ groupExpansion.set(id, initial);
908
+ return initial;
909
+ }
910
+ function setGroupExpanded(id: string, expanded: boolean): void {
911
+ if (pending() || props.grouping?.collapsible === false || groupExpanded(id) === expanded) return;
912
+ groupExpansion.set(id, expanded);
913
+ setGroupRevision(revision => revision + 1);
914
+ }
915
+ const structuredRows = createMemo<readonly DisplayRow<Row>[]>(() => {
916
+ if (hierarchy) {
917
+ hierarchyRevision();
918
+ const nextResetKey = props.hierarchy?.resetKey;
919
+ if (!Object.is(nextResetKey, hierarchyResetKey)) hierarchy.reset();
920
+ hierarchyResetKey = nextResetKey;
921
+ hierarchy.updateRoots(result().rows);
922
+ const snapshot = hierarchy.getSnapshot();
923
+ const stable = reconcileRows(snapshot.map(item => item.row));
924
+ const stableById = new Map(stable.map(row => [row.id, row]));
925
+ return Object.freeze(snapshot.map((item: HierarchyRow<Row>): DisplayDataRow<Row> => {
926
+ const row = stableById.get(item.id);
927
+ if (!row) throw new Error(`Missing stable hierarchy row: ${item.id}`);
928
+ 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 });
929
+ }));
930
+ }
931
+ if (props.grouping && groupingColumn?.accessor) {
932
+ groupRevision();
933
+ if (props.mode === "server" && serverSnapshot()?.accepted === null) return Object.freeze([]);
934
+ const current = result();
935
+ const aggregateColumns = definitions.flatMap(column => column.aggregate && column.accessor ? [{ id: column.id, aggregate: column.aggregate, getValue: column.accessor }] : []);
936
+ const groups = props.mode === "server"
937
+ ? normalizeServerGroups(current.rows, current.groups, { column: groupingColumn.id, aggregateColumns: aggregateColumns.map(column => column.id), getRowId: props.getRowId })
938
+ : groupClientRows(current.rows, { column: groupingColumn.id, getValue: groupingColumn.accessor, aggregates: aggregateColumns });
939
+ const stable = props.mode === "server" ? reconcileRows(current.rows) : stableResultRows(current.rows);
940
+ const stableById = new Map(stable.map(row => [row.id, row]));
941
+ const rows: DisplayRow<Row>[] = [];
942
+ for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
943
+ const group = groups[groupIndex]!;
944
+ const expanded = groupExpanded(group.id);
945
+ rows.push(Object.freeze({ kind: "group", key: group.id, group, label: groupLabel(group), position: groupIndex + 1, setSize: groups.length, expanded }));
946
+ if (!expanded) continue;
947
+ for (let rowIndex = 0; rowIndex < group.rows.length; rowIndex++) {
948
+ const id = props.getRowId(group.rows[rowIndex]!);
949
+ const row = stableById.get(id);
950
+ if (!row) throw new Error(`Missing stable grouped row: ${id}`);
951
+ 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 }));
952
+ }
953
+ }
954
+ return Object.freeze(rows);
955
+ }
956
+ return Object.freeze([]);
957
+ });
958
+ const flatResultRows = createMemo<readonly Row[]>(() => hierarchy || props.grouping ? Object.freeze([]) : result().rows);
959
+ const serverFlatStableRows = createMemo<readonly StableRow<Row>[]>(() => props.mode === "server" && !hierarchy && !props.grouping ? Object.freeze(stableResultRows(flatResultRows())) : Object.freeze([]));
960
+ function flatStableRow(index: number): StableRow<Row> | undefined {
961
+ const row = flatResultRows()[index];
962
+ if (!row) return undefined;
963
+ const client = clientRowIndex();
964
+ if (client) return client.resolve(row, index);
965
+ return serverFlatStableRows()[index];
966
+ }
967
+ const rowCount = (): number => hierarchy || props.grouping ? structuredRows().length : flatResultRows().length;
968
+ function rowAt(index: number): DisplayRow<Row> | undefined {
969
+ if (hierarchy || props.grouping) return structuredRows()[index];
970
+ const row = flatStableRow(index);
971
+ return row ? flatDisplayRow(row, index, flatResultRows().length) : undefined;
972
+ }
973
+ function rowIndex(key: string): number {
974
+ if (hierarchy || props.grouping) return structuredRows().findIndex(row => row.key === key);
975
+ for (let index = 0; index < flatResultRows().length; index++) if (`row:${flatStableRow(index)?.id ?? ""}` === key) return index;
976
+ return -1;
977
+ }
978
+ let selectionInitialized = false;
979
+ const selectableRows = createMemo(() => {
980
+ const rows = hierarchy || props.grouping
981
+ ? structuredRows().flatMap(row => row.kind === "data" ? [row.row] : [])
982
+ : props.mode === "server" ? serverFlatStableRows()
983
+ : selection || actions().length > 0 ? stableResultRows(flatResultRows()) : Object.freeze([]);
984
+ if (!selection) return { rows, before: "", payload: undefined };
985
+ const before = JSON.stringify(selection.getPayload());
986
+ const nextResetKey = props.selection?.resetKey;
987
+ const nextSearch = acceptedState().search;
988
+ if (!Object.is(nextResetKey, selectionResetKey) || nextSearch !== selectionSearch) {
989
+ selection.reset();
990
+ selectionAnchorId = undefined;
991
+ }
992
+ selectionResetKey = nextResetKey;
993
+ selectionSearch = nextSearch;
994
+ selection.setFilter(acceptedState().filter);
995
+ selection.setLoadedIds(rows.map(row => row.id));
996
+ return { rows, before, payload: selection.getPayload() };
997
+ });
998
+ createEffect(() => {
999
+ const synchronized = selectableRows();
1000
+ if (!selection || !synchronized.payload) return;
1001
+ setSelectionRevision(revision => revision + 1);
1002
+ if (selectionInitialized && JSON.stringify(synchronized.payload) !== synchronized.before) props.selection?.onChange(synchronized.payload);
1003
+ selectionInitialized = true;
1004
+ });
1005
+ function publishSelection(): void {
1006
+ if (!selection) return;
1007
+ const payload = selection.getPayload();
1008
+ setSelectionRevision(revision => revision + 1);
1009
+ props.selection?.onChange(payload);
1010
+ }
1011
+ function rowSelected(id: string): boolean {
1012
+ selectionRevision();
1013
+ selectableRows();
1014
+ return selection?.isSelected(id) ?? false;
1015
+ }
1016
+ function changeRowSelection(id: string, selected: boolean, range: boolean): void {
1017
+ if (!selection || pending()) return;
1018
+ const anchorLoaded = selectionAnchorId !== undefined && selectableRows().rows.some(row => row.id === selectionAnchorId);
1019
+ if (range && anchorLoaded && selectionAnchorId) selection.selectRange(selectionAnchorId, id, selected);
1020
+ else {
1021
+ selection.setSelected(id, selected);
1022
+ selectionAnchorId = id;
1023
+ }
1024
+ publishSelection();
1025
+ }
1026
+ function selectLoadedRows(selected: boolean): void {
1027
+ if (!selection || pending()) return;
1028
+ selection.selectLoaded(selected);
1029
+ publishSelection();
1030
+ }
1031
+ function selectAllMatchingRows(): void {
1032
+ if (!selection || pending() || acceptedState().search.length > 0) return;
1033
+ selection.selectAllMatching();
1034
+ publishSelection();
1035
+ }
1036
+ function clearSelection(): void {
1037
+ if (!selection) return;
1038
+ selection.clear();
1039
+ selectionAnchorId = undefined;
1040
+ publishSelection();
1041
+ }
1042
+ const selectedLoadedCount = createMemo(() => selectableRows().rows.filter(row => rowSelected(row.id)).length);
1043
+ const selectionPayload = createMemo(() => {
1044
+ selectionRevision();
1045
+ return selection?.getPayload();
1046
+ });
1047
+ const selectionActive = createMemo(() => {
1048
+ const payload = selectionPayload();
1049
+ return payload?.kind === "query" || Boolean(payload?.ids.length);
1050
+ });
1051
+
1052
+ function rowActionSelection(row: StableRow<Row>): BulkSelection {
1053
+ const payload = selectionPayload();
1054
+ if (selection && payload && rowSelected(row.id) && selectionActive()) return payload;
1055
+ return Object.freeze({ kind: "ids", ids: Object.freeze([row.id]) });
1056
+ }
1057
+
1058
+ function actionContext(anchor?: StableRow<Row>): DataTableActionContext<Row> {
1059
+ const payload = anchor ? rowActionSelection(anchor) : selectionPayload();
1060
+ if (!payload) throw new Error("DataTable selection actions require an active selection");
1061
+ const loadedRows = selectableRows().rows
1062
+ .filter(row => payload.kind === "query" ? !payload.excluded.includes(row.id) : payload.ids.includes(row.id))
1063
+ .map(row => row.value());
1064
+ return Object.freeze({ selection: payload, loadedRows: Object.freeze(loadedRows), ...(anchor ? { anchor: anchor.value() } : {}) });
1065
+ }
1066
+
1067
+ function actionDisabled(action: DataTableAction<Row>, context: DataTableActionContext<Row>): boolean {
1068
+ return pending() || (typeof action.disabled === "function" ? action.disabled(context) : action.disabled === true);
1069
+ }
1070
+
1071
+ function prepareContextSelection(row: StableRow<Row>): void {
1072
+ if (!selection || pending() || rowSelected(row.id)) return;
1073
+ selection.clear();
1074
+ selection.setSelected(row.id, true);
1075
+ selectionAnchorId = row.id;
1076
+ publishSelection();
1077
+ }
1078
+
1079
+ function rowActionItems(row: StableRow<Row>): readonly MenuItem[] {
1080
+ const context = actionContext(row);
1081
+ return actions().map(action => ({
1082
+ kind: "action",
1083
+ id: action.id,
1084
+ label: action.label,
1085
+ ...(action.shortcut ? { shortcut: action.shortcut } : {}),
1086
+ disabled: actionDisabled(action, context),
1087
+ onSelect: () => action.onSelect(context),
1088
+ }));
1089
+ }
1090
+
1091
+ const selectionCount = createMemo(() => {
1092
+ const payload = selectionPayload();
1093
+ if (!payload) return 0;
1094
+ return payload.kind === "query" ? Math.max(0, result().total - payload.excluded.length) : payload.ids.length;
1095
+ });
1096
+ const [selectionBarPresent, setSelectionBarPresent] = createSignal(false);
1097
+ const [selectionBarOpen, setSelectionBarOpen] = createSignal(false);
1098
+ let selectionBarTimer: number | undefined;
1099
+ createEffect(() => {
1100
+ const active = selectionActive();
1101
+ if (selectionBarTimer !== undefined) window.clearTimeout(selectionBarTimer);
1102
+ selectionBarTimer = undefined;
1103
+ if (active) {
1104
+ setSelectionBarPresent(true);
1105
+ setSelectionBarOpen(true);
1106
+ return;
1107
+ }
1108
+ setSelectionBarOpen(false);
1109
+ if (selectionBarPresent()) selectionBarTimer = window.setTimeout(() => {
1110
+ selectionBarTimer = undefined;
1111
+ setSelectionBarPresent(false);
1112
+ }, 250);
1113
+ });
1114
+ onCleanup(() => { if (selectionBarTimer !== undefined) window.clearTimeout(selectionBarTimer); });
1115
+
1116
+ function finishSelectionBarExit(event: AnimationEvent): void {
1117
+ if (event.target !== event.currentTarget || selectionBarOpen()) return;
1118
+ if (selectionBarTimer !== undefined) window.clearTimeout(selectionBarTimer);
1119
+ selectionBarTimer = undefined;
1120
+ setSelectionBarPresent(false);
1121
+ }
1122
+
1123
+ function selectionLabel(row: StableRow<Row>): string {
1124
+ const label = props.selection?.getRowLabel?.(row.value()) ?? messages().selectRow.replaceAll("{id}", row.id);
1125
+ if (typeof label !== "string" || !label.trim()) throw new Error(`Selection label for ${row.id} must be nonempty`);
1126
+ return label;
1127
+ }
1128
+ const columnRecords = definitions.map((definition, index) => {
1129
+ const initial = initialState.columns.find(column => column.id === definition.id);
1130
+ if (!initial) throw new Error(`Missing initial state for table column: ${definition.id}`);
1131
+ const [state, updateState] = createSignal(initial);
1132
+ return Object.freeze({ definition, state, updateState, variable: `--sheen-table-column-${index}`, sortDescriptionId: createUniqueId() });
1133
+ });
1134
+ const columnRecordById = new Map(columnRecords.map(column => [column.definition.id, column]));
1135
+ const orderedColumnStates = createMemo(() => orderColumnStates(acceptedState().columns));
1136
+ const visibleDefinitions = createMemo(() => {
1137
+ const ordered = orderedColumnStates();
1138
+ for (const state of ordered) columnRecordById.get(state.id)?.updateState(state);
1139
+ return ordered.flatMap(state => {
1140
+ const record = columnRecordById.get(state.id);
1141
+ return record && state.visible ? [record] : [];
1142
+ });
1143
+ });
1144
+ type CellEditController = ReturnType<typeof createCellEdit<ColumnValue, string>>;
1145
+ interface CellEditRecord {
1146
+ readonly controller: CellEditController;
1147
+ readonly revision: Accessor<number>;
1148
+ readonly publish: () => void;
1149
+ }
1150
+ const cellEditRecords = new Map<string, Map<string, CellEditRecord>>();
1151
+ const [editGeneration, setEditGeneration] = createSignal(0);
1152
+ let currentEditResetKey = props.editResetKey;
1153
+
1154
+ function cellEditRecord(row: StableRow<Row>, column: (typeof columnRecords)[number]): CellEditRecord | undefined {
1155
+ editGeneration();
1156
+ const editor = column.definition.editor;
1157
+ const accessor = column.definition.accessor;
1158
+ const commit = props.onCellCommit;
1159
+ if (!editor || !accessor || !commit) return undefined;
1160
+ const existing = cellEditRecords.get(row.id)?.get(column.definition.id);
1161
+ if (existing) return existing;
1162
+ const initial = accessor(row.value());
1163
+ if (!editorAccepts(editor, initial)) throw new Error(`Initial value for editable cell ${row.id}/${column.definition.id} does not match its editor`);
1164
+ const [revision, setRevision] = createSignal(0);
1165
+ const publish = () => setRevision(value => value + 1);
1166
+ const controller = createCellEdit<ColumnValue, string>(initial, async (request, signal) => {
1167
+ const applicationRequest: DataTableCellCommitRequest<Row> = Object.freeze({ ...request, rowId: row.id, row: row.value(), column: column.definition.id });
1168
+ const result = await commit(applicationRequest, signal);
1169
+ const value = result.kind === "accepted" ? result.value : result.current;
1170
+ if (!editorAccepts(editor, value)) throw new Error(`Committed value for ${row.id}/${column.definition.id} does not match its editor`);
1171
+ return result;
1172
+ }, { validate: value => {
1173
+ if (!editorAccepts(editor, value)) return value === null ? messages().cellValueRequired : messages().cellValueInvalid;
1174
+ return editor.validate?.(value, row.value()) ?? null;
1175
+ } });
1176
+ const record = Object.freeze({ controller, revision, publish });
1177
+ const rowRecords = cellEditRecords.get(row.id) ?? new Map<string, CellEditRecord>();
1178
+ rowRecords.set(column.definition.id, record);
1179
+ cellEditRecords.set(row.id, rowRecords);
1180
+ return record;
1181
+ }
1182
+
1183
+ function editSnapshot(record: CellEditRecord | undefined): CellEditSnapshot<ColumnValue, string> | undefined {
1184
+ record?.revision();
1185
+ return record?.controller.getSnapshot();
1186
+ }
1187
+
1188
+ createEffect(() => {
1189
+ const nextResetKey = props.editResetKey;
1190
+ if (typeof nextResetKey === "number" && !Number.isFinite(nextResetKey)) throw new Error("DataTable editResetKey must be a finite number or string");
1191
+ if (Object.is(nextResetKey, currentEditResetKey)) return;
1192
+ currentEditResetKey = nextResetKey;
1193
+ for (const columns of cellEditRecords.values()) for (const record of columns.values()) record.controller.dispose();
1194
+ cellEditRecords.clear();
1195
+ editToaster?.clear();
1196
+ setEditGeneration(generation => generation + 1);
1197
+ });
1198
+ onCleanup(() => {
1199
+ for (const columns of cellEditRecords.values()) for (const record of columns.values()) record.controller.dispose();
1200
+ cellEditRecords.clear();
1201
+ });
1202
+ const availableExportFormats = createMemo<readonly DataTableExportFormat[]>(() => {
1203
+ const hasVisibleValue = visibleDefinitions().some(column => column.definition.accessor !== null);
1204
+ if (!hasVisibleValue || configuredExportFormats.length === 0) return Object.freeze([]);
1205
+ if (props.mode === "server" && !serverExports) return Object.freeze([]);
1206
+ return configuredExportFormats;
1207
+ });
1208
+ const serverExportSnapshot = (): ServerExportSnapshot<Blob> | undefined => {
1209
+ exportRevision();
1210
+ return serverExports?.getSnapshot();
1211
+ };
1212
+ const exportPending = (): boolean => serverExportSnapshot()?.pending ?? false;
1213
+ const exportError = (): unknown => serverExportSnapshot()?.error ?? clientExportError();
1214
+
1215
+ function publishDownload(blob: Blob, format: DataTableExportFormat): void {
1216
+ const previousDownload = lastDownload();
1217
+ const href = URL.createObjectURL(blob);
1218
+ const filename = `${configuredExportBaseName}.${format}`;
1219
+ setLastDownload({ href, filename });
1220
+ if (previousDownload) URL.revokeObjectURL(previousDownload.href);
1221
+ const anchor = document.createElement("a");
1222
+ anchor.href = href;
1223
+ anchor.download = filename;
1224
+ anchor.click();
1225
+ }
1226
+
1227
+ function exportClient(format: DataTableExportFormat): void {
1228
+ if (props.mode === "server") return;
1229
+ setClientExportError(null);
1230
+ try {
1231
+ const view = clientView()?.view ?? [];
1232
+ const payload = selectionActive() ? selectionPayload() : undefined;
1233
+ const rows = payload ? selectClientRows(view, payload, { locale: locale(), filterColumns: schema.filterColumns, getRowId: props.getRowId, getValue }) : view;
1234
+ const exported = createClientExport(rows, visibleDefinitions().flatMap(column => column.definition.accessor
1235
+ ? [{ id: column.definition.id, header: column.definition.header, value: column.definition.accessor }]
1236
+ : []));
1237
+ const content = format === "csv" ? exported.toCSV() : exported.toJSON();
1238
+ publishDownload(new Blob([content], { type: format === "csv" ? "text/csv;charset=utf-8" : "application/json;charset=utf-8" }), format);
1239
+ } catch (value) {
1240
+ setClientExportError(value);
1241
+ }
1242
+ }
1243
+
1244
+ async function finishServerExport(completion: Promise<ServerExportOutcome>): Promise<void> {
1245
+ setExportRevision(revision => revision + 1);
1246
+ const outcome = await completion;
1247
+ setExportRevision(revision => revision + 1);
1248
+ if (outcome !== "accepted") return;
1249
+ const accepted = serverExports?.getSnapshot().accepted;
1250
+ if (accepted) publishDownload(accepted.artifact, accepted.request.format);
1251
+ }
1252
+
1253
+ function exportServer(format: DataTableExportFormat): void {
1254
+ if (!serverExports || pending() || exportPending()) return;
1255
+ const payload = selectionActive() ? selectionPayload() ?? null : null;
1256
+ void finishServerExport(serverExports.request({ format, state: acceptedState(), selection: payload }));
1257
+ }
1258
+
1259
+ function requestExport(format: DataTableExportFormat): void {
1260
+ if (pending() || exportPending()) return;
1261
+ if (props.mode === "server") exportServer(format);
1262
+ else exportClient(format);
1263
+ }
1264
+
1265
+ function retryExport(): void {
1266
+ if (!serverExports || pending() || exportPending()) return;
1267
+ void finishServerExport(serverExports.retry());
1268
+ }
1269
+
1270
+ const exportMenuItems = createMemo<readonly MenuItem[]>(() => availableExportFormats().map(format => ({
1271
+ kind: "action",
1272
+ id: format,
1273
+ label: format === "csv" ? messages().exportCSV : messages().exportJSON,
1274
+ disabled: pending() || exportPending(),
1275
+ onSelect: () => requestExport(format),
1276
+ })));
1277
+ const resultNumber = createMemo(() => new Intl.NumberFormat(locale()));
1278
+ const resultCount = () => {
1279
+ if (!acceptedAvailable()) return undefined;
1280
+ const total = result().total;
1281
+ const template = total === 1 ? messages().resultCountOne : messages().resultCount;
1282
+ return template.replace("{count}", resultNumber().format(total));
1283
+ };
1284
+ function downloadLastExport(): void {
1285
+ const download = lastDownload();
1286
+ if (!download) return;
1287
+ const anchor = document.createElement("a");
1288
+ anchor.href = download.href;
1289
+ anchor.download = download.filename;
1290
+ anchor.click();
1291
+ }
1292
+ const track = (column: (typeof columnRecords)[number]): string => `var(${column.variable}, ${columnTrack(column.state().width ?? column.definition.width, column.definition.minWidth, column.definition.maxWidth)})`;
1293
+ const selectionTrack = "var(--sheen-table-selection-column, 2.75rem)";
1294
+ const template = createMemo(() => [...(selection ? [selectionTrack] : []), ...visibleDefinitions().map(track)].join(" "));
1295
+
1296
+ function commitLayout(next: TableState): void {
1297
+ setLayoutColumns(next.columns);
1298
+ const base = serverSnapshot()?.accepted?.state ?? clientState();
1299
+ props.onAcceptedStateChange?.(Object.freeze({ ...base, columns: next.columns }));
1300
+ }
1301
+
1302
+ function changeLayout(change: Parameters<typeof changeTableState>[1]): void {
1303
+ commitLayout(changeTableState(acceptedState(), change, schema));
1304
+ }
1305
+
1306
+ function currentColumnWidth(column: (typeof columnRecords)[number]): number {
1307
+ const header = [...tableElement?.querySelectorAll<HTMLElement>("thead th[data-column]") ?? []].find(element => element.dataset.column === column.definition.id);
1308
+ const measured = header?.getBoundingClientRect().width;
1309
+ const fallback = column.state().width ?? (typeof column.definition.width === "number" ? column.definition.width : column.definition.minWidth ?? 160);
1310
+ return clampColumnWidth(measured && measured > 0 ? measured : fallback, column.definition.minWidth, column.definition.maxWidth);
1311
+ }
1312
+
1313
+ function writeColumnWidth(column: (typeof columnRecords)[number], width: number | null): void {
1314
+ if (width === null) tableElement?.style.removeProperty(column.variable);
1315
+ else tableElement?.style.setProperty(column.variable, `${width}px`);
1316
+ }
1317
+
1318
+ function setColumnWidth(column: (typeof columnRecords)[number], width: number | null): void {
1319
+ const resolved = width === null ? null : clampColumnWidth(width, column.definition.minWidth, column.definition.maxWidth);
1320
+ writeColumnWidth(column, resolved);
1321
+ changeLayout({ kind: "columnWidth", column: column.definition.id, width: resolved });
1322
+ }
1323
+
1324
+ function autoFitColumn(column: (typeof columnRecords)[number]): void {
1325
+ const measured = [...tableElement?.querySelectorAll<HTMLElement>("[data-column]") ?? []]
1326
+ .filter(element => element.dataset.column === column.definition.id)
1327
+ .reduce((maximum, element) => Math.max(maximum, element.scrollWidth + 1), 0);
1328
+ setColumnWidth(column, measured > 0 ? measured : currentColumnWidth(column));
1329
+ }
1330
+
1331
+ function setColumnPin(column: (typeof columnRecords)[number], pin: ColumnState["pin"]): void {
1332
+ let next = acceptedState();
1333
+ if (pin !== false && column.state().width === null && typeof column.definition.width !== "number") {
1334
+ next = changeTableState(next, { kind: "columnWidth", column: column.definition.id, width: currentColumnWidth(column) }, schema);
1335
+ }
1336
+ next = changeTableState(next, { kind: "columnPin", column: column.definition.id, pin }, schema);
1337
+ commitLayout(next);
1338
+ }
1339
+
1340
+ function moveLayoutColumn(id: string, direction: ColumnMoveDirection): void {
1341
+ const columns = moveColumn(acceptedState().columns, id, direction);
1342
+ if (columns === acceptedState().columns) return;
1343
+ const focused = tableElement?.ownerDocument.activeElement;
1344
+ changeLayout({ kind: "columnOrder", ids: columns.map(column => column.id) });
1345
+ if (focused instanceof HTMLElement && tableElement?.contains(focused)) queueMicrotask(() => { if (focused.isConnected) focused.focus({ preventScroll: true }); });
1346
+ }
1347
+
1348
+ function placeLayoutColumn(sourceId: string, targetId: string, placement: ColumnDropPlacement): void {
1349
+ const columns = placeColumn(acceptedState().columns, sourceId, targetId, placement);
1350
+ const focused = tableElement?.ownerDocument.activeElement;
1351
+ changeLayout({ kind: "columnOrder", ids: columns.map(column => column.id) });
1352
+ if (focused instanceof HTMLElement && tableElement?.contains(focused)) queueMicrotask(() => { if (focused.isConnected) focused.focus({ preventScroll: true }); });
1353
+ }
1354
+
1355
+ const columnMenuItems = createMemo<readonly MenuItem[]>(() => {
1356
+ const labels = messages();
1357
+ const state = acceptedState().columns;
1358
+ const visibleCount = state.filter(column => column.visible).length;
1359
+ return state.map(columnState => {
1360
+ const column = columnRecordById.get(columnState.id);
1361
+ if (!column) throw new Error(`Missing table column: ${columnState.id}`);
1362
+ const items: readonly MenuItem[] = [
1363
+ { kind: "checkbox", id: "visible", label: labels.showColumn, checked: columnState.visible, disabled: columnState.visible && visibleCount === 1, onCheckedChange: visible => changeLayout({ kind: "columnVisibility", column: columnState.id, visible }) },
1364
+ { kind: "action", id: "move-start", label: labels.moveColumnStart, disabled: !canMoveColumn(state, columnState.id, "toward-start"), onSelect: () => moveLayoutColumn(columnState.id, "toward-start") },
1365
+ { kind: "action", id: "move-end", label: labels.moveColumnEnd, disabled: !canMoveColumn(state, columnState.id, "toward-end"), onSelect: () => moveLayoutColumn(columnState.id, "toward-end") },
1366
+ { kind: "radio", id: "pin", label: labels.pinColumn, value: columnState.pin === false ? "none" : columnState.pin, onValueChange: value => {
1367
+ if (value !== "none" && value !== "start" && value !== "end") throw new Error("Invalid column pin action");
1368
+ setColumnPin(column, value === "none" ? false : value);
1369
+ }, options: [
1370
+ { id: "none", label: labels.pinNone },
1371
+ { id: "start", label: labels.pinStart },
1372
+ { id: "end", label: labels.pinEnd },
1373
+ ] },
1374
+ { kind: "action", id: "auto-fit", label: labels.autoFitColumn, disabled: !columnState.visible, onSelect: () => autoFitColumn(column) },
1375
+ { kind: "action", id: "reset-width", label: labels.resetColumnWidth, disabled: columnState.width === null || (columnState.pin !== false && typeof column.definition.width !== "number"), onSelect: () => setColumnWidth(column, null) },
1376
+ ];
1377
+ return { kind: "submenu", id: columnState.id, label: column.definition.header, items };
1378
+ });
1379
+ });
1380
+ const toolbarActions = createMemo<readonly DataTableToolbarAction[]>(() => {
1381
+ const next: DataTableToolbarAction[] = [];
1382
+ if (selection && !hierarchy && acceptedState().search.length === 0) next.push({ kind: "action", id: "select-all", label: messages().selectAll, disabled: pending(), onSelect: selectAllMatchingRows });
1383
+ if (availableExportFormats().length > 0) next.push({ kind: "menu", id: "export", label: messages().export, disabled: pending() || exportPending(), items: exportMenuItems() });
1384
+ if (lastDownload()) next.push({ kind: "action", id: "download", label: messages().downloadLastExport, onSelect: downloadLastExport });
1385
+ if (props.columnControls !== false) next.push({ kind: "menu", id: "columns", label: messages().columns, items: columnMenuItems() });
1386
+ return Object.freeze(next);
1387
+ });
1388
+
1389
+ function pinOffset(column: (typeof columnRecords)[number]): string {
1390
+ const visible = visibleDefinitions();
1391
+ const index = visible.findIndex(candidate => candidate.definition.id === column.definition.id);
1392
+ if (index < 0 || column.state().pin === false) return "0px";
1393
+ const adjacent = column.state().pin === "start" ? visible.slice(0, index) : visible.slice(index + 1);
1394
+ const tracks = adjacent.filter(candidate => candidate.state().pin === column.state().pin).map(track);
1395
+ if (column.state().pin === "start" && selection) tracks.unshift(selectionTrack);
1396
+ return tracks.length === 0 ? "0px" : `calc(${tracks.join(" + ")})`;
1397
+ }
1398
+
1399
+ function pinStyle(column: (typeof columnRecords)[number]): JSX.CSSProperties | undefined {
1400
+ if (column.state().pin === "start") return { "inset-inline-start": pinOffset(column) };
1401
+ if (column.state().pin === "end") return { "inset-inline-end": pinOffset(column) };
1402
+ return undefined;
1403
+ }
1404
+
1405
+ function pinEdge(column: (typeof columnRecords)[number]): "start" | "end" | undefined {
1406
+ const visible = visibleDefinitions();
1407
+ if (column.state().pin === "start" && [...visible].reverse().find(candidate => candidate.state().pin === "start") === column) return "start";
1408
+ if (column.state().pin === "end" && visible.find(candidate => candidate.state().pin === "end") === column) return "end";
1409
+ return undefined;
1410
+ }
1411
+
1412
+ let resizeSession: {
1413
+ readonly pointerId: number;
1414
+ readonly column: (typeof columnRecords)[number];
1415
+ readonly handle: HTMLButtonElement;
1416
+ readonly startX: number;
1417
+ readonly startWidth: number;
1418
+ readonly direction: 1 | -1;
1419
+ nextWidth: number;
1420
+ frame: number | undefined;
1421
+ } | undefined;
1422
+
1423
+ function paintResize(): void {
1424
+ const session = resizeSession;
1425
+ if (!session) return;
1426
+ session.frame = undefined;
1427
+ writeColumnWidth(session.column, session.nextWidth);
1428
+ session.handle.setAttribute("aria-valuenow", String(session.nextWidth));
1429
+ session.handle.setAttribute("aria-valuetext", messages().columnWidthPixels.replace("{width}", String(session.nextWidth)));
1430
+ }
1431
+
1432
+ function cancelResize(): void {
1433
+ const session = resizeSession;
1434
+ if (!session) return;
1435
+ if (session.frame !== undefined) cancelAnimationFrame(session.frame);
1436
+ writeColumnWidth(session.column, null);
1437
+ session.handle.removeAttribute("data-resizing");
1438
+ root?.removeAttribute("data-resizing");
1439
+ resizeSession = undefined;
1440
+ }
1441
+
1442
+ function startResize(event: PointerEvent, column: (typeof columnRecords)[number]): void {
1443
+ if (event.button !== 0 || !(event.currentTarget instanceof HTMLButtonElement)) return;
1444
+ cancelResize();
1445
+ event.preventDefault();
1446
+ const handle = event.currentTarget;
1447
+ const width = currentColumnWidth(column);
1448
+ resizeSession = { pointerId: event.pointerId, column, handle, startX: event.clientX, startWidth: width, direction: theme.state().direction === "rtl" ? -1 : 1, nextWidth: width, frame: undefined };
1449
+ handle.setPointerCapture(event.pointerId);
1450
+ handle.setAttribute("data-resizing", "");
1451
+ root?.setAttribute("data-resizing", column.definition.id);
1452
+ }
1453
+
1454
+ function moveResize(event: PointerEvent): void {
1455
+ const session = resizeSession;
1456
+ if (!session || session.pointerId !== event.pointerId) return;
1457
+ session.nextWidth = clampColumnWidth(session.startWidth + (event.clientX - session.startX) * session.direction, session.column.definition.minWidth, session.column.definition.maxWidth);
1458
+ if (session.frame === undefined) session.frame = requestAnimationFrame(paintResize);
1459
+ }
1460
+
1461
+ function finishResize(event: PointerEvent): void {
1462
+ const session = resizeSession;
1463
+ if (!session || session.pointerId !== event.pointerId) return;
1464
+ if (session.frame !== undefined) cancelAnimationFrame(session.frame);
1465
+ resizeSession = undefined;
1466
+ writeColumnWidth(session.column, session.nextWidth);
1467
+ session.handle.setAttribute("aria-valuenow", String(session.nextWidth));
1468
+ session.handle.setAttribute("aria-valuetext", messages().columnWidthPixels.replace("{width}", String(session.nextWidth)));
1469
+ session.handle.removeAttribute("data-resizing");
1470
+ root?.removeAttribute("data-resizing");
1471
+ if (session.handle.hasPointerCapture(event.pointerId)) session.handle.releasePointerCapture(event.pointerId);
1472
+ setColumnWidth(session.column, session.nextWidth);
1473
+ }
1474
+
1475
+ function resizeWithKeyboard(event: KeyboardEvent, column: (typeof columnRecords)[number]): void {
1476
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
1477
+ const minimum = column.definition.minWidth ?? 80;
1478
+ const maximum = column.definition.maxWidth ?? 4096;
1479
+ const current = currentColumnWidth(column);
1480
+ const step = event.shiftKey ? 50 : 10;
1481
+ const direction = theme.state().direction === "rtl" ? -1 : 1;
1482
+ const next = event.key === "ArrowRight" ? current + step * direction
1483
+ : event.key === "ArrowLeft" ? current - step * direction
1484
+ : event.key === "Home" ? minimum
1485
+ : event.key === "End" ? maximum
1486
+ : null;
1487
+ if (next === null) return;
1488
+ event.preventDefault();
1489
+ setColumnWidth(column, next);
1490
+ }
1491
+
1492
+ let reorderSession: {
1493
+ readonly pointerId: number;
1494
+ readonly source: (typeof columnRecords)[number];
1495
+ readonly handle: HTMLButtonElement;
1496
+ readonly startX: number;
1497
+ readonly startY: number;
1498
+ target: (typeof columnRecords)[number] | undefined;
1499
+ placement: ColumnDropPlacement | undefined;
1500
+ dragging: boolean;
1501
+ } | undefined;
1502
+ function clearColumnDrag(): void {
1503
+ reorderSession = undefined;
1504
+ root?.removeAttribute("data-reordering");
1505
+ for (const header of tableElement?.querySelectorAll<HTMLElement>("th[data-drop-placement]") ?? []) header.removeAttribute("data-drop-placement");
1506
+ }
1507
+ function startColumnDrag(event: PointerEvent, column: (typeof columnRecords)[number]): void {
1508
+ if (event.button !== 0 || !(event.currentTarget instanceof HTMLButtonElement)) return;
1509
+ clearColumnDrag();
1510
+ const handle = event.currentTarget;
1511
+ reorderSession = { pointerId: event.pointerId, source: column, handle, startX: event.clientX, startY: event.clientY, target: undefined, placement: undefined, dragging: false };
1512
+ handle.setPointerCapture(event.pointerId);
1513
+ }
1514
+ function moveColumnDrag(event: PointerEvent): void {
1515
+ const session = reorderSession;
1516
+ if (!session || session.pointerId !== event.pointerId) return;
1517
+ if (!session.dragging && Math.hypot(event.clientX - session.startX, event.clientY - session.startY) < 5) return;
1518
+ session.dragging = true;
1519
+ event.preventDefault();
1520
+ root?.setAttribute("data-reordering", session.source.definition.id);
1521
+ const targetElement = session.handle.ownerDocument.elementFromPoint(event.clientX, event.clientY)?.closest<HTMLElement>("th[data-column]");
1522
+ const target = targetElement?.dataset.column ? columnRecordById.get(targetElement.dataset.column) : undefined;
1523
+ for (const header of tableElement?.querySelectorAll<HTMLElement>("th[data-drop-placement]") ?? []) if (header !== targetElement) header.removeAttribute("data-drop-placement");
1524
+ if (!target || target === session.source || target.state().pin !== session.source.state().pin || !targetElement) {
1525
+ session.target = undefined;
1526
+ session.placement = undefined;
1527
+ return;
1528
+ }
1529
+ const bounds = targetElement.getBoundingClientRect();
1530
+ const physicalAfter = event.clientX >= bounds.left + bounds.width / 2;
1531
+ session.target = target;
1532
+ session.placement = theme.state().direction === "rtl" ? physicalAfter ? "before" : "after" : physicalAfter ? "after" : "before";
1533
+ targetElement.setAttribute("data-drop-placement", session.placement);
1534
+ }
1535
+ function finishColumnDrag(event: PointerEvent): void {
1536
+ const session = reorderSession;
1537
+ if (!session || session.pointerId !== event.pointerId) return;
1538
+ const target = session.target;
1539
+ const placement = session.placement;
1540
+ const sourceId = session.source.definition.id;
1541
+ if (session.handle.hasPointerCapture(event.pointerId)) session.handle.releasePointerCapture(event.pointerId);
1542
+ clearColumnDrag();
1543
+ if (target && placement) placeLayoutColumn(sourceId, target.definition.id, placement);
1544
+ }
1545
+ function reorderWithKeyboard(event: KeyboardEvent, column: (typeof columnRecords)[number]): void {
1546
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || (event.key !== "ArrowLeft" && event.key !== "ArrowRight")) return;
1547
+ event.preventDefault();
1548
+ const towardStart = theme.state().direction === "rtl" ? event.key === "ArrowRight" : event.key === "ArrowLeft";
1549
+ moveLayoutColumn(column.definition.id, towardStart ? "toward-start" : "toward-end");
1550
+ }
1551
+ let columnMeasureFrame: number | undefined;
1552
+ onMount(() => {
1553
+ const synchronize = (): void => {
1554
+ columnMeasureFrame = undefined;
1555
+ for (const column of visibleDefinitions()) {
1556
+ const header = [...tableElement?.querySelectorAll<HTMLElement>("thead th[data-column]") ?? []].find(element => element.dataset.column === column.definition.id);
1557
+ header?.querySelector<HTMLElement>('[role="separator"]')?.setAttribute("aria-valuenow", String(currentColumnWidth(column)));
1558
+ }
1559
+ };
1560
+ const schedule = (): void => {
1561
+ if (columnMeasureFrame === undefined) columnMeasureFrame = requestAnimationFrame(synchronize);
1562
+ };
1563
+ const observer = new ResizeObserver(schedule);
1564
+ if (tableElement) observer.observe(tableElement);
1565
+ schedule();
1566
+ onCleanup(() => {
1567
+ observer.disconnect();
1568
+ if (columnMeasureFrame !== undefined) cancelAnimationFrame(columnMeasureFrame);
1569
+ });
1570
+ });
1571
+ onCleanup(() => { cancelResize(); clearColumnDrag(); });
1572
+
1573
+ const rowHeight = props.rowHeight ?? "var(--sheen-table-row-h)";
1574
+ if (typeof rowHeight !== "string" || rowHeight.trim() === "") throw new Error("rowHeight must be a nonempty CSS length");
1575
+ const effectiveDensity = (): DataTableDensity => density() ?? theme.state().density;
1576
+ const estimatedRowHeight = (): number => props.estimatedRowHeight ?? (effectiveDensity() === "compact" ? 28 : effectiveDensity() === "spacious" ? 42 : 34);
1577
+ if (!Number.isFinite(estimatedRowHeight()) || estimatedRowHeight() <= 0) throw new Error("estimatedRowHeight must be a positive finite number");
1578
+ const initialViewportHeight = props.initialViewportHeight ?? 400;
1579
+ if (!Number.isFinite(initialViewportHeight) || initialViewportHeight <= 0) throw new Error("initialViewportHeight must be a positive finite number");
1580
+ const virtualizer = createVirtualizer<HTMLDivElement, HTMLTableRowElement>({
1581
+ get count() { return rowCount(); },
1582
+ getScrollElement: () => viewport ?? null,
1583
+ estimateSize: estimatedRowHeight,
1584
+ getItemKey: index => props.variableRowHeight ? rowAt(index)?.key ?? index : index,
1585
+ initialRect: { width: 1024, height: initialViewportHeight },
1586
+ overscan: 8,
1587
+ useAnimationFrameWithResizeObserver: true,
1588
+ });
1589
+ let virtualizerMounted = false;
1590
+ function bindVirtualRow(element: HTMLTableRowElement, index: number): void {
1591
+ element.setAttribute("data-index", String(index));
1592
+ if (virtualizerMounted && props.variableRowHeight) virtualizer.measureElement(element);
1593
+ }
1594
+ onMount(() => {
1595
+ virtualizerMounted = true;
1596
+ if (props.variableRowHeight) {
1597
+ for (const element of viewport?.querySelectorAll<HTMLTableRowElement>("tbody tr[data-row-key]") ?? []) virtualizer.measureElement(element);
1598
+ }
1599
+ });
1600
+ let measuredDensity = effectiveDensity();
1601
+ createEffect(() => {
1602
+ const currentDensity = effectiveDensity();
1603
+ if (virtualizerMounted && currentDensity !== measuredDensity) virtualizer.measure();
1604
+ measuredDensity = currentDensity;
1605
+ });
1606
+ const renderedRowCache = new Map<string, RenderedRow<Row>>();
1607
+ const renderedRows = createMemo<readonly RenderedRow<Row>[]>(() => {
1608
+ const retained = new Set<string>();
1609
+ const rows = virtualizer.getVirtualItems().flatMap(item => {
1610
+ const row = rowAt(item.index);
1611
+ if (!row) return [];
1612
+ retained.add(row.key);
1613
+ const existing = renderedRowCache.get(row.key);
1614
+ if (existing) {
1615
+ existing.updateRow(row);
1616
+ existing.updateItem(item);
1617
+ return [existing];
1618
+ }
1619
+ const [currentRow, setCurrentRow] = createSignal(row, { equals: false });
1620
+ const [currentItem, setCurrentItem] = createSignal(item, { equals: false });
1621
+ const rendered = Object.freeze({ key: row.key, row: currentRow, updateRow: (next: DisplayRow<Row>): void => { setCurrentRow(next); }, item: currentItem, updateItem: (next: VirtualItem): void => { setCurrentItem(next); } });
1622
+ renderedRowCache.set(row.key, rendered);
1623
+ return [rendered];
1624
+ });
1625
+ for (const id of renderedRowCache.keys()) if (!retained.has(id)) renderedRowCache.delete(id);
1626
+ return rows;
1627
+ });
1628
+ const [activeRowKey, setActiveRowKey] = createSignal<string | null>(null);
1629
+ const focusableRowKey = createMemo<string | null>(() => {
1630
+ if (!props.onRowActivate && !selection && !hierarchy && !props.grouping && actions().length === 0) return null;
1631
+ const active = activeRowKey();
1632
+ return active && rowIndex(active) >= 0 ? active : rowAt(0)?.key ?? null;
1633
+ });
1634
+ let focusFrame: number | undefined;
1635
+ function focusRow(index: number): void {
1636
+ const row = rowAt(index);
1637
+ if (!row || !viewport) return;
1638
+ setActiveRowKey(row.key);
1639
+ virtualizer.scrollToIndex(index, { align: "auto" });
1640
+ let attempts = 10;
1641
+ const realize = (): void => {
1642
+ focusFrame = undefined;
1643
+ const element = [...viewport?.querySelectorAll<HTMLTableRowElement>("tbody tr[data-row-key]") ?? []].find(candidate => candidate.dataset.rowKey === row.key);
1644
+ if (element) {
1645
+ element.focus({ preventScroll: true });
1646
+ return;
1647
+ }
1648
+ attempts--;
1649
+ if (attempts > 0) focusFrame = requestAnimationFrame(realize);
1650
+ };
1651
+ if (focusFrame !== undefined) cancelAnimationFrame(focusFrame);
1652
+ focusFrame = requestAnimationFrame(realize);
1653
+ }
1654
+ function changeHierarchyExpansion(row: DisplayDataRow<Row>, expanded: boolean): void {
1655
+ if (!hierarchy || pending()) return;
1656
+ const completion = hierarchy.setExpanded(row.row.id, expanded);
1657
+ setHierarchyRevision(revision => revision + 1);
1658
+ void completion.finally(() => setHierarchyRevision(revision => revision + 1));
1659
+ }
1660
+ function retryHierarchy(row: DisplayDataRow<Row>): void {
1661
+ if (!hierarchy || pending()) return;
1662
+ const completion = hierarchy.retry(row.row.id);
1663
+ setHierarchyRevision(revision => revision + 1);
1664
+ void completion.finally(() => setHierarchyRevision(revision => revision + 1));
1665
+ }
1666
+ const [hierarchyMounted, setHierarchyMounted] = createSignal(false);
1667
+ onMount(() => { setHierarchyMounted(true); });
1668
+ createEffect(() => {
1669
+ if (!hierarchy || !hierarchyMounted()) return;
1670
+ for (const row of structuredRows()) if (row.kind === "data" && row.expanded && row.unloaded && !row.pending && row.error === null) changeHierarchyExpansion(row, true);
1671
+ });
1672
+ function handleRowKeyDown(event: KeyboardEvent, row: DisplayRow<Row>): void {
1673
+ if (event.target !== event.currentTarget || event.altKey) return;
1674
+ if (selection && !pending() && row.kind === "data" && (event.ctrlKey || event.metaKey) && !event.shiftKey && event.key.toLowerCase() === "a") {
1675
+ event.preventDefault();
1676
+ selectLoadedRows(true);
1677
+ return;
1678
+ }
1679
+ if (row.kind === "group" && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === " " || event.key === "Enter")) {
1680
+ event.preventDefault();
1681
+ setGroupExpanded(row.group.id, !row.expanded);
1682
+ return;
1683
+ }
1684
+ if (row.kind === "group" && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
1685
+ event.preventDefault();
1686
+ setGroupExpanded(row.group.id, event.key === "ArrowRight");
1687
+ return;
1688
+ }
1689
+ if (hierarchy && row.kind === "data" && row.canExpand && !event.ctrlKey && !event.metaKey && !event.shiftKey && event.key === "ArrowRight") {
1690
+ event.preventDefault();
1691
+ if (!row.expanded) changeHierarchyExpansion(row, true);
1692
+ else {
1693
+ const current = rowIndex(row.key);
1694
+ const child = rowAt(current + 1);
1695
+ if (child?.kind === "data" && child.parentId === row.row.id) focusRow(current + 1);
1696
+ }
1697
+ return;
1698
+ }
1699
+ if (hierarchy && row.kind === "data" && !event.ctrlKey && !event.metaKey && !event.shiftKey && event.key === "ArrowLeft") {
1700
+ event.preventDefault();
1701
+ if (row.expanded) changeHierarchyExpansion(row, false);
1702
+ else if (row.parentId) {
1703
+ const parent = structuredRows().findIndex(candidate => candidate.kind === "data" && candidate.row.id === row.parentId);
1704
+ if (parent >= 0) focusRow(parent);
1705
+ }
1706
+ return;
1707
+ }
1708
+ if (selection && !pending() && row.kind === "data" && !event.ctrlKey && !event.metaKey && event.key === " ") {
1709
+ event.preventDefault();
1710
+ changeRowSelection(row.row.id, !rowSelected(row.row.id), event.shiftKey);
1711
+ return;
1712
+ }
1713
+ if (props.onRowActivate && !pending() && row.kind === "data" && !event.ctrlKey && !event.metaKey && !event.shiftKey && event.key === "Enter") {
1714
+ event.preventDefault();
1715
+ props.onRowActivate(row.row.value());
1716
+ return;
1717
+ }
1718
+ if (event.ctrlKey || event.metaKey || (event.shiftKey && !selection)) return;
1719
+ const current = rowIndex(row.key);
1720
+ if (current < 0) return;
1721
+ const page = Math.max(1, Math.floor((viewport?.clientHeight ?? estimatedRowHeight()) / estimatedRowHeight()));
1722
+ const last = Math.max(0, rowCount() - 1);
1723
+ const next = event.key === "ArrowDown" ? Math.min(last, current + 1)
1724
+ : event.key === "ArrowUp" ? Math.max(0, current - 1)
1725
+ : event.key === "PageDown" ? Math.min(last, current + page)
1726
+ : event.key === "PageUp" ? Math.max(0, current - page)
1727
+ : event.key === "Home" ? 0
1728
+ : event.key === "End" ? last
1729
+ : null;
1730
+ if (next === null) return;
1731
+ event.preventDefault();
1732
+ const nextRow = rowAt(next);
1733
+ if (selection && row.kind === "data" && event.shiftKey && nextRow?.kind === "data") {
1734
+ if (!selectionAnchorId || !selectableRows().rows.some(candidate => candidate.id === selectionAnchorId)) selectionAnchorId = row.row.id;
1735
+ selection.selectRange(selectionAnchorId, nextRow.row.id, true);
1736
+ publishSelection();
1737
+ }
1738
+ focusRow(next);
1739
+ }
1740
+ function handleRowClick(event: MouseEvent, row: DisplayRow<Row>): void {
1741
+ if (!selection || pending() || row.kind !== "data" || !(event.target instanceof Element) || event.target.closest("button, input, select, textarea, a, [data-sheen-selection-control]")) return;
1742
+ if (event.shiftKey) changeRowSelection(row.row.id, true, true);
1743
+ else if (event.ctrlKey || event.metaKey) changeRowSelection(row.row.id, !rowSelected(row.row.id), false);
1744
+ else {
1745
+ selection.clear();
1746
+ selection.setSelected(row.row.id, true);
1747
+ selectionAnchorId = row.row.id;
1748
+ publishSelection();
1749
+ }
1750
+ if (event.currentTarget instanceof HTMLElement) event.currentTarget.focus({ preventScroll: true });
1751
+ }
1752
+ onCleanup(() => { if (focusFrame !== undefined) cancelAnimationFrame(focusFrame); });
1753
+ let scrollAnchor: ScrollAnchor | undefined;
1754
+ let anchorFrame: number | undefined;
1755
+ function captureScrollAnchor(): void {
1756
+ if (!viewport) return;
1757
+ const bounds = viewport.getBoundingClientRect();
1758
+ const visibleTop = viewport.querySelector("thead")?.getBoundingClientRect().bottom ?? bounds.top;
1759
+ const row = [...viewport.querySelectorAll<HTMLTableRowElement>("tbody tr[data-row-key]")].find(candidate => candidate.getBoundingClientRect().bottom > visibleTop);
1760
+ if (!row?.dataset.rowKey) return;
1761
+ const index = Number(row.dataset.index);
1762
+ const item = virtualizer.getVirtualItems().find(candidate => candidate.index === index);
1763
+ if (!item) return;
1764
+ scrollAnchor = { id: row.dataset.rowKey, offset: viewport.scrollTop - item.start };
1765
+ }
1766
+ function scheduleScrollAnchorCapture(): void {
1767
+ if (anchorFrame !== undefined) cancelAnimationFrame(anchorFrame);
1768
+ anchorFrame = requestAnimationFrame(() => {
1769
+ anchorFrame = undefined;
1770
+ captureScrollAnchor();
1771
+ });
1772
+ }
1773
+ onCleanup(() => { if (anchorFrame !== undefined) cancelAnimationFrame(anchorFrame); });
1774
+ const currentRowCollection = (): readonly DisplayRow<Row>[] | readonly Row[] => hierarchy || props.grouping ? structuredRows() : flatResultRows();
1775
+ let previousRows = currentRowCollection();
1776
+ let previousState = serializeState(acceptedState(), schema);
1777
+ createEffect(() => {
1778
+ const nextRows = currentRowCollection();
1779
+ const nextState = serializeState(acceptedState(), schema);
1780
+ const anchor = scrollAnchor;
1781
+ if (viewport && anchor && nextRows !== previousRows && nextState === previousState) {
1782
+ const index = rowIndex(anchor.id);
1783
+ const offset = index < 0 ? undefined : virtualizer.getOffsetForIndex(index, "start")?.[0];
1784
+ if (offset !== undefined) viewport.scrollTop = Math.max(0, offset + anchor.offset);
1785
+ }
1786
+ previousRows = nextRows;
1787
+ previousState = nextState;
1788
+ });
1789
+
1790
+ const range = createMemo(() => {
1791
+ const pagination = acceptedState().pagination;
1792
+ return pagination === false ? undefined : getPageRange(pagination, result().total);
1793
+ });
1794
+ const mobileRange = createMemo(() => {
1795
+ if (!mobileLayout || acceptedState().pagination !== false) return undefined;
1796
+ return getPageRange({ pageIndex: mobilePageIndex(), pageSize: mobileLayout.pageSize }, rowCount());
1797
+ });
1798
+ createEffect(() => {
1799
+ const current = mobileRange();
1800
+ if (current && current.pageIndex !== mobilePageIndex()) setMobilePageIndex(current.pageIndex);
1801
+ });
1802
+ const mobileRows = createMemo<readonly DisplayRow<Row>[]>(() => {
1803
+ if (!mobileLayout) return Object.freeze([]);
1804
+ const current = mobileRange();
1805
+ const start = current?.start ?? 0;
1806
+ const end = current?.end ?? rowCount();
1807
+ const rows: DisplayRow<Row>[] = [];
1808
+ for (let index = start; index < end; index++) {
1809
+ const row = rowAt(index);
1810
+ if (row) rows.push(row);
1811
+ }
1812
+ return Object.freeze(rows);
1813
+ });
1814
+ const mobileTitleColumn = createMemo(() => {
1815
+ const visible = visibleDefinitions();
1816
+ return visible.find(column => column.definition.id === mobileLayout?.titleColumn) ?? visible[0];
1817
+ });
1818
+ const mobileDataRows = createMemo(() => mobileRows().flatMap(row => row.kind === "data" ? [row.row] : []));
1819
+ const mobileSelectedCount = createMemo(() => mobileDataRows().filter(row => rowSelected(row.id)).length);
1820
+ const mobileSortItems = createMemo<readonly MenuItem[]>(() => visibleDefinitions().flatMap(column => {
1821
+ if (!column.definition.sort) return [];
1822
+ const direction = acceptedState().sorting.find(entry => entry.column === column.definition.id)?.direction;
1823
+ const state = direction === "asc" ? messages().sortedAscending : direction === "desc" ? messages().sortedDescending : messages().notSorted;
1824
+ return [{ kind: "action", id: `sort:${column.definition.id}`, label: `${messages().sortColumn.replaceAll("{column}", column.definition.header)}, ${state}`, disabled: pending(), onSelect: () => requestSort(column.definition.id, false) }];
1825
+ }));
1826
+ const mobileFocusableKey = createMemo(() => {
1827
+ const active = activeRowKey();
1828
+ return active && mobileRows().some(row => row.key === active) ? active : mobileRows()[0]?.key ?? null;
1829
+ });
1830
+ const queryActive = createMemo(() => acceptedState().search.length > 0 || filterActive(acceptedState().filter));
1831
+ const clearQueryLabel = () => acceptedState().search.length > 0 ? messages().clearSearchAndFilters : messages().clearFilters;
1832
+ const bodyState = createMemo<"cold" | "error" | "no-results" | "empty">(() => {
1833
+ if (!acceptedAvailable()) return error() ? "error" : "cold";
1834
+ return queryActive() ? "no-results" : "empty";
1835
+ });
1836
+ const footerRows = createMemo<readonly Row[]>(() => props.mode === "server" ? result().rows : clientView()?.view ?? []);
1837
+ const hasFooter = createMemo(() => visibleDefinitions().some(column => column.definition.footer !== null));
1838
+ const stateColumnCount = () => Math.max(1, visibleDefinitions().length + (selection ? 1 : 0));
1839
+ const logicalColumnCount = () => definitions.length + (selection ? 1 : 0);
1840
+ const coldRows = Object.freeze([0, 1, 2, 3, 4, 5]);
1841
+ const className = () => `sheen-data-table${props.class ? ` ${props.class}` : ""}`;
1842
+ function requestMobilePage(pageIndex: number): void {
1843
+ const current = mobileRange();
1844
+ if (!current || pending() || pageIndex < 0 || pageIndex >= current.pageCount || pageIndex === current.pageIndex) return;
1845
+ setMobilePageIndex(pageIndex);
1846
+ mobileViewport?.scrollIntoView({ block: "nearest" });
1847
+ }
1848
+ function selectMobileRows(selected: boolean): void {
1849
+ if (!selection || pending()) return;
1850
+ for (const row of mobileDataRows()) selection.setSelected(row.id, selected);
1851
+ publishSelection();
1852
+ }
1853
+ function focusMobileRow(index: number): void {
1854
+ const row = mobileRows()[index];
1855
+ if (!row || !mobileViewport) return;
1856
+ setActiveRowKey(row.key);
1857
+ const element = [...mobileViewport.querySelectorAll<HTMLElement>("[data-mobile-row-key]")].find(candidate => candidate.dataset.mobileRowKey === row.key);
1858
+ element?.focus({ preventScroll: true });
1859
+ }
1860
+ function handleMobileRowKeyDown(event: KeyboardEvent, row: DisplayRow<Row>): void {
1861
+ if (event.target !== event.currentTarget || event.altKey) return;
1862
+ if (selection && !pending() && row.kind === "data" && (event.ctrlKey || event.metaKey) && !event.shiftKey && event.key.toLowerCase() === "a") {
1863
+ event.preventDefault();
1864
+ selectMobileRows(true);
1865
+ return;
1866
+ }
1867
+ if (row.kind === "group" && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === " " || event.key === "Enter" || event.key === "ArrowRight" || event.key === "ArrowLeft")) {
1868
+ event.preventDefault();
1869
+ setGroupExpanded(row.group.id, event.key === "ArrowRight" ? true : event.key === "ArrowLeft" ? false : !row.expanded);
1870
+ return;
1871
+ }
1872
+ if (hierarchy && row.kind === "data" && row.canExpand && !event.ctrlKey && !event.metaKey && !event.shiftKey && (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
1873
+ event.preventDefault();
1874
+ changeHierarchyExpansion(row, event.key === "ArrowRight");
1875
+ return;
1876
+ }
1877
+ if (selection && !pending() && row.kind === "data" && !event.ctrlKey && !event.metaKey && event.key === " ") {
1878
+ event.preventDefault();
1879
+ changeRowSelection(row.row.id, !rowSelected(row.row.id), event.shiftKey);
1880
+ return;
1881
+ }
1882
+ if (props.onRowActivate && !pending() && row.kind === "data" && !event.ctrlKey && !event.metaKey && !event.shiftKey && event.key === "Enter") {
1883
+ event.preventDefault();
1884
+ props.onRowActivate(row.row.value());
1885
+ return;
1886
+ }
1887
+ if (event.ctrlKey || event.metaKey || event.shiftKey) return;
1888
+ const current = mobileRows().findIndex(candidate => candidate.key === row.key);
1889
+ const last = Math.max(0, mobileRows().length - 1);
1890
+ const next = event.key === "ArrowDown" ? Math.min(last, current + 1)
1891
+ : event.key === "ArrowUp" ? Math.max(0, current - 1)
1892
+ : event.key === "Home" ? 0
1893
+ : event.key === "End" ? last
1894
+ : null;
1895
+ if (next === null || current < 0) return;
1896
+ event.preventDefault();
1897
+ focusMobileRow(next);
1898
+ }
1899
+ function RowSelectionCell(cellProps: { readonly row: StableRow<Row> }): JSX.Element {
1900
+ let selectRange = false;
1901
+ return <td role={treePresentation ? "gridcell" : undefined} class="sheen-data-table-selection-cell" aria-colindex="1">
1902
+ <Checkbox data-sheen-selection-control="" class="sheen-data-table-selection-control" label={selectionLabel(cellProps.row)} checked={rowSelected(cellProps.row.id)} disabled={pending()}
1903
+ onPointerDown={event => { selectRange = event.shiftKey; }} onKeyDown={event => { if (event.key === " ") selectRange = event.shiftKey; }}
1904
+ onCheckedChange={checked => { changeRowSelection(cellProps.row.id, checked, selectRange); selectRange = false; }} />
1905
+ </td>;
1906
+ }
1907
+ const treePresentation = Boolean(hierarchy || props.grouping);
1908
+ function logicalColumnIndex(id: string): number {
1909
+ const index = orderedColumnStates().findIndex(column => column.id === id);
1910
+ if (index < 0) throw new Error(`Missing accepted state for table column: ${id}`);
1911
+ return index + 1 + (selection ? 1 : 0);
1912
+ }
1913
+ function logicalRowIndex(index: number): number {
1914
+ const pagination = acceptedState().pagination;
1915
+ if (treePresentation || pagination === false) return index + 2;
1916
+ return getPageRange(pagination, result().total).start + index + 2;
1917
+ }
1918
+ const logicalRowCount = (): number | undefined => rowCount() === 0
1919
+ ? undefined
1920
+ : treePresentation ? -1 : result().total + 1 + (hasFooter() ? 1 : 0);
1921
+ const footerRowIndex = (): number => treePresentation ? rowCount() + 2 : result().total + 2;
1922
+ function expansionLabel(row: DisplayDataRow<Row>): string {
1923
+ return `${row.expanded ? messages().collapse : messages().expand} ${row.row.id}`;
1924
+ }
1925
+ function EditableCellValue(cellProps: { readonly row: DisplayDataRow<Row>; readonly column: (typeof columnRecords)[number]; readonly record: CellEditRecord }): JSX.Element {
1926
+ const editor = cellProps.column.definition.editor;
1927
+ const accessor = cellProps.column.definition.accessor;
1928
+ if (!editor || !accessor) throw new Error(`Editable cell ${cellProps.row.row.id}/${cellProps.column.definition.id} is missing its editor`);
1929
+ const activeEditor = editor;
1930
+ const id = createUniqueId();
1931
+ let editorElement: HTMLInputElement | HTMLSelectElement | undefined;
1932
+ let restingElement: HTMLSpanElement | undefined;
1933
+ let restoringRestingFocus = false;
1934
+ let incoming = accessor(cellProps.row.row.value());
1935
+ const snapshot = (): CellEditSnapshot<ColumnValue, string> => {
1936
+ cellProps.record.revision();
1937
+ return cellProps.record.controller.getSnapshot();
1938
+ };
1939
+ const draft = (): ColumnValue => snapshot().draft?.value ?? snapshot().committed;
1940
+ const label = () => messages().editCell.replaceAll("{column}", cellProps.column.definition.header).replaceAll("{id}", cellProps.row.row.id);
1941
+ const message = () => {
1942
+ const current = snapshot();
1943
+ if (current.invalid) return current.invalid;
1944
+ if (current.conflict) return messages().cellConflict.replaceAll("{value}", current.conflict.current === null ? messages().noValue : String(current.conflict.current));
1945
+ return current.error ? messages().cellUpdateFailedDescription : null;
1946
+ };
1947
+ const content = () => cellProps.column.definition.cell?.(snapshot().committed, cellProps.row.row.value()) ?? defaultCell(snapshot().committed);
1948
+
1949
+ createEffect(() => {
1950
+ const next = accessor(cellProps.row.row.value());
1951
+ if (Object.is(next, incoming)) return;
1952
+ incoming = next;
1953
+ cellProps.record.controller.acceptRefetch(next);
1954
+ cellProps.record.publish();
1955
+ });
1956
+
1957
+ function focusEditor(): void { queueMicrotask(() => editorElement?.focus({ preventScroll: true })); }
1958
+ function focusResting(): void {
1959
+ queueMicrotask(() => {
1960
+ restoringRestingFocus = true;
1961
+ try { restingElement?.focus({ preventScroll: true }); }
1962
+ finally { restoringRestingFocus = false; }
1963
+ });
1964
+ }
1965
+ function begin(): void {
1966
+ if (restoringRestingFocus || pending()) return;
1967
+ if (cellProps.record.controller.begin()) {
1968
+ cellProps.record.publish();
1969
+ focusEditor();
1970
+ }
1971
+ }
1972
+ function update(value: ColumnValue): void {
1973
+ cellProps.record.controller.setDraft(value);
1974
+ cellProps.record.publish();
1975
+ }
1976
+ async function finish(completion: Promise<CellCommitOutcome>, restore: boolean, notify = true): Promise<CellCommitOutcome> {
1977
+ cellProps.record.publish();
1978
+ const outcome = await completion;
1979
+ cellProps.record.publish();
1980
+ const current = snapshot();
1981
+ if (outcome === "accepted" && !current.editing && restore) focusResting();
1982
+ if ((outcome === "invalid" || outcome === "conflict") && restore) focusEditor();
1983
+ if (outcome === "failed" && notify && editToaster) editToaster.show({
1984
+ title: messages().cellUpdateFailed,
1985
+ description: messages().cellUpdateFailedDescription,
1986
+ tone: "danger",
1987
+ priority: "assertive",
1988
+ duration: null,
1989
+ action: {
1990
+ label: messages().retry,
1991
+ retryLabel: messages().retry,
1992
+ errorMessage: messages().retryFailed,
1993
+ run: async () => {
1994
+ const retried = await finish(cellProps.record.controller.retry(), false, false);
1995
+ if (retried !== "accepted") throw new Error(`Cell retry was not accepted: ${retried}`);
1996
+ focusResting();
1997
+ },
1998
+ },
1999
+ });
2000
+ return outcome;
2001
+ }
2002
+ function commit(restore: boolean): void { void finish(cellProps.record.controller.commit(), restore); }
2003
+ function blur(): void {
2004
+ const current = snapshot();
2005
+ const unchangedFailure = (current.error !== null || current.conflict !== null) && current.attempt !== null && current.draft !== null && Object.is(current.attempt.value, current.draft.value);
2006
+ if (!unchangedFailure) commit(false);
2007
+ }
2008
+ function keyDown(event: KeyboardEvent): void {
2009
+ if (event.key === "Enter") {
2010
+ event.preventDefault();
2011
+ commit(true);
2012
+ } else if (event.key === "Escape") {
2013
+ event.preventDefault();
2014
+ cellProps.record.controller.discard();
2015
+ cellProps.record.publish();
2016
+ focusResting();
2017
+ }
2018
+ }
2019
+ function EditorControl(): JSX.Element {
2020
+ const invalid = () => snapshot().invalid !== null || snapshot().error !== null || undefined;
2021
+ const describedBy = () => message() ? `${id}-message` : undefined;
2022
+ 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"
2023
+ aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown} onChange={event => update(event.currentTarget.checked)} />;
2024
+ if (activeEditor.type === "select") return <select ref={element => { editorElement = element; element.value = draft() === null ? "" : String(draft()); }} class="sheen-data-table-editor"
2025
+ 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)}>
2026
+ <Show when={activeEditor.nullable}><option value="">{messages().noValue}</option></Show>
2027
+ <For each={activeEditor.options}>{option => <option value={option}>{option}</option>}</For>
2028
+ </select>;
2029
+ 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"
2030
+ aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown}
2031
+ onInput={event => update(event.currentTarget.value === "" ? null : event.currentTarget.valueAsNumber)} />;
2032
+ return <input ref={element => { editorElement = element; element.value = draft() === null ? "" : String(draft()); }} class="sheen-data-table-editor" type="text"
2033
+ aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown}
2034
+ onInput={event => update(event.currentTarget.value === "" && activeEditor.nullable ? null : event.currentTarget.value)} />;
2035
+ }
2036
+ return <span class="sheen-data-table-edit-value">
2037
+ <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}
2038
+ onKeyDown={event => { if (event.key === "Enter") { event.preventDefault(); begin(); } }}>{content()}</span>}>
2039
+ <EditorControl />
2040
+ </Show>
2041
+ <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>
2042
+ </span>;
2043
+ }
2044
+ function DataCellContent(cellProps: { readonly row: DisplayDataRow<Row>; readonly column: (typeof columnRecords)[number]; readonly first: boolean; readonly edit: CellEditRecord | undefined }): JSX.Element {
2045
+ const value = () => cellProps.column.definition.accessor?.(cellProps.row.row.value()) ?? null;
2046
+ const content = () => cellProps.edit ? <EditableCellValue row={cellProps.row} column={cellProps.column} record={cellProps.edit} /> : cellProps.column.definition.cell?.(value(), cellProps.row.row.value()) ?? defaultCell(value());
2047
+ if (!treePresentation || !cellProps.first) return <>{content()}</>;
2048
+ return <div class="sheen-data-table-tree-cell" style={{ "--sheen-table-depth": Math.max(0, cellProps.row.depth - 1) }}>
2049
+ <Show when={cellProps.row.canExpand} fallback={<span class="sheen-data-table-expander-space" aria-hidden="true" />}>
2050
+ <button type="button" class="sheen-data-table-expander" aria-label={expansionLabel(cellProps.row)} aria-expanded={cellProps.row.expanded} disabled={pending()}
2051
+ onClick={() => changeHierarchyExpansion(cellProps.row, !cellProps.row.expanded)}>{cellProps.row.expanded ? "▾" : "▸"}</button>
2052
+ </Show>
2053
+ <span class="sheen-data-table-tree-value">{content()}</span>
2054
+ <Show when={cellProps.row.pending}><span class="sheen-data-table-row-status" role="status">{messages().loadingChildren}</span></Show>
2055
+ <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>
2056
+ </div>;
2057
+ }
2058
+ function GroupCellContent(cellProps: { readonly row: DisplayGroupRow<Row>; readonly column: (typeof columnRecords)[number]; readonly labelColumn: boolean }): JSX.Element {
2059
+ if (cellProps.labelColumn) return <div class="sheen-data-table-tree-cell" style={{ "--sheen-table-depth": 0 }}>
2060
+ <Show when={props.grouping?.collapsible !== false} fallback={<span class="sheen-data-table-expander-space" aria-hidden="true" />}>
2061
+ <button type="button" class="sheen-data-table-expander" disabled={pending()} aria-label={`${cellProps.row.expanded ? messages().collapse : messages().expand} ${cellProps.row.label}`}
2062
+ aria-expanded={cellProps.row.expanded} onClick={() => setGroupExpanded(cellProps.row.group.id, !cellProps.row.expanded)}>{cellProps.row.expanded ? "▾" : "▸"}</button>
2063
+ </Show>
2064
+ <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>
2065
+ </div>;
2066
+ const aggregate = cellProps.row.group.aggregates.find(value => value.column === cellProps.column.definition.id)?.value ?? null;
2067
+ return defaultCell(aggregate);
2068
+ }
2069
+ function MobileSelectionControl(controlProps: { readonly row: StableRow<Row> }): JSX.Element {
2070
+ let selectRange = false;
2071
+ return <Checkbox data-sheen-selection-control="" class="sheen-data-table-selection-control" label={selectionLabel(controlProps.row)} checked={rowSelected(controlProps.row.id)} disabled={pending()}
2072
+ onPointerDown={event => { selectRange = event.shiftKey; }} onKeyDown={event => { if (event.key === " ") selectRange = event.shiftKey; }}
2073
+ onCheckedChange={checked => { changeRowSelection(controlProps.row.id, checked, selectRange); selectRange = false; }} />;
2074
+ }
2075
+ function MobileCellContent(cellProps: { readonly row: DisplayRow<Row>; readonly column: (typeof columnRecords)[number]; readonly title: boolean }): JSX.Element {
2076
+ const data = () => displayDataRow(cellProps.row);
2077
+ const edit = createMemo(() => {
2078
+ const current = data();
2079
+ return current ? cellEditRecord(current.row, cellProps.column) : undefined;
2080
+ });
2081
+ const state = () => editSnapshot(edit());
2082
+ const invalid = () => {
2083
+ const current = state();
2084
+ return Boolean(current && (current.invalid !== null || current.error !== null));
2085
+ };
2086
+ 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}>
2087
+ <GroupCellContent row={group()} column={cellProps.column} labelColumn={cellProps.title} />
2088
+ </div>}</Show>}>
2089
+ {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}
2090
+ data-editable={edit() ? "" : undefined} data-invalid={invalid() ? "" : undefined} data-stale={state()?.stale ? "" : undefined} data-pending={state()?.pending ? "" : undefined} data-conflict={state()?.conflict ? "" : undefined}>
2091
+ <DataCellContent row={current()} column={cellProps.column} first={cellProps.title} edit={edit()} />
2092
+ </div>}
2093
+ </Show>;
2094
+ }
2095
+ function MobileCardBody(cardProps: { readonly row: DisplayRow<Row> }): JSX.Element {
2096
+ const data = () => displayDataRow(cardProps.row);
2097
+ const title = mobileTitleColumn;
2098
+ const details = () => visibleDefinitions().filter(column => column !== title());
2099
+ return <>
2100
+ <div class="sheen-data-table-mobile-card-header">
2101
+ <Show when={data()}>{value => <Show when={selection}><MobileSelectionControl row={value().row} /></Show>}</Show>
2102
+ <div class="sheen-data-table-mobile-title">
2103
+ <Show when={title()} fallback={data()?.row.id ?? displayGroupRow(cardProps.row)?.label ?? ""}>{column => <MobileCellContent row={cardProps.row} column={column()} title />}</Show>
2104
+ </div>
2105
+ <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>
2106
+ </div>
2107
+ <Show when={details().length > 0}><dl class="sheen-data-table-mobile-fields">
2108
+ <For each={details()}>{column => <div class="sheen-data-table-mobile-field">
2109
+ <dt>{column.definition.header}</dt>
2110
+ <dd><MobileCellContent row={cardProps.row} column={column} title={false} /></dd>
2111
+ </div>}</For>
2112
+ </dl></Show>
2113
+ </>;
2114
+ }
2115
+ 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` }}>
2116
+ <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>
2117
+ <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>
2118
+ <DataTableToolbar label={messages().tableControls.replace("{caption}", props.caption)} result={resultCount()} resultPrevious={previous() ? messages().previousResults : undefined} actions={toolbarActions()}
2119
+ query={searchOptions || (props.filterBar !== false && schema.filterColumns.length > 0) ? <>
2120
+ <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}
2121
+ onValueChange={updateSearchDraft} onCompositionStart={startSearchComposition} onCompositionEnd={event => finishSearchComposition(event.currentTarget.value)} />
2122
+ <Show when={searchOptions?.exactMatch}><DropdownMenu class="sheen-data-table-search-mode-menu" trigger={<span>{searchMode() === "exact" ? messages().searchExact : messages().searchRanked}</span>}
2123
+ triggerLabel={`${messages().searchMatchMode}: ${searchMode() === "exact" ? messages().searchExact : messages().searchRanked}`} items={searchModeItems()} disabled={pending()} /></Show>
2124
+ </div></Show>
2125
+ <Show when={props.filterBar !== false && schema.filterColumns.length > 0}><FilterBar columns={props.columns} value={acceptedState().filter} facets={result().facets} disabled={pending()} onChange={requestFilter}
2126
+ {...(typeof props.filterBar === "object" && props.filterBar.dateEditor ? { dateEditor: props.filterBar.dateEditor } : {})} /></Show>
2127
+ </> : undefined}
2128
+ status={<Show when={exportPending()}><span class="sheen-data-table-export-status" role="status">{messages().preparingExport}</span></Show>} />
2129
+ <div class="sheen-data-table-frame">
2130
+ <Show when={refreshVisible()}><div class="sheen-data-table-refresh" role="status"><span>{messages().refreshing}</span></div></Show>
2131
+ <div class="sheen-data-table-viewport" ref={element => { viewport = element; }} tabindex="-1" onScroll={scheduleScrollAnchorCapture}>
2132
+ <table ref={tableElement} id={tableId} role={treePresentation ? "treegrid" : undefined} aria-multiselectable={treePresentation && selection ? true : undefined}
2133
+ aria-rowcount={logicalRowCount()} aria-colcount={logicalColumnCount()}>
2134
+ <caption>{props.caption}</caption>
2135
+ <thead><tr aria-rowindex="1" style={{ "grid-template-columns": template() }}>
2136
+ <Show when={selection}><th class="sheen-data-table-selection-cell" scope="col" role={treePresentation ? "columnheader" : undefined} aria-colindex="1">
2137
+ <Checkbox data-sheen-selection-control="" class="sheen-data-table-selection-control" label={messages().selectPage}
2138
+ checked={selectableRows().rows.length > 0 && selectedLoadedCount() === selectableRows().rows.length}
2139
+ indeterminate={selectedLoadedCount() > 0 && selectedLoadedCount() < selectableRows().rows.length}
2140
+ disabled={pending() || selectableRows().rows.length === 0} onCheckedChange={selectLoadedRows} />
2141
+ </th></Show>
2142
+ <For each={visibleDefinitions()}>{column => {
2143
+ const sorted = () => acceptedState().sorting.find(entry => entry.column === column.definition.id);
2144
+ const sortPosition = () => acceptedState().sorting.findIndex(entry => entry.column === column.definition.id) + 1;
2145
+ const sortDescription = () => {
2146
+ const direction = sorted()?.direction;
2147
+ const state = direction === "asc" ? messages().sortedAscending : direction === "desc" ? messages().sortedDescending : messages().notSorted;
2148
+ const count = acceptedState().sorting.length;
2149
+ return direction && count > 1 ? `${state}, ${messages().sortPriority.replace("{position}", String(sortPosition())).replace("{count}", String(count))}` : state;
2150
+ };
2151
+ const resizeLabel = () => messages().resizeColumn.replaceAll("{column}", column.definition.header);
2152
+ const reorderLabel = () => messages().reorderColumn.replaceAll("{column}", column.definition.header);
2153
+ const reportedWidth = () => column.state().width ?? (typeof column.definition.width === "number" ? column.definition.width : column.definition.minWidth ?? 160);
2154
+ 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)}
2155
+ aria-sort={sortPosition() === 1 ? sorted()?.direction === "asc" ? "ascending" : sorted()?.direction === "desc" ? "descending" : undefined : undefined}>
2156
+ <div class="sheen-data-table-header-content">
2157
+ <Show when={column.definition.sort} fallback={<span class="sheen-data-table-header-label">{column.definition.header}</span>}>
2158
+ <button class="sheen-data-table-sort" type="button" disabled={pending()} aria-describedby={column.sortDescriptionId} onClick={event => requestSort(column.definition.id, event.shiftKey)}>
2159
+ <span class="sheen-data-table-sort-label">{column.definition.header}</span>
2160
+ <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>
2161
+ </button>
2162
+ <span id={column.sortDescriptionId} class="sheen-data-table-state-label">{sortDescription()}</span>
2163
+ </Show>
2164
+ <button class="sheen-data-table-reorder" type="button" aria-label={reorderLabel()} onKeyDown={event => reorderWithKeyboard(event, column)}
2165
+ onPointerDown={event => startColumnDrag(event, column)} onPointerMove={moveColumnDrag} onPointerUp={finishColumnDrag} onPointerCancel={clearColumnDrag}
2166
+ onLostPointerCapture={() => { if (reorderSession?.source === column) clearColumnDrag(); }} aria-keyshortcuts="ArrowLeft ArrowRight"><span class="sheen-data-table-reorder-grip" aria-hidden="true" /></button>
2167
+ </div>
2168
+ <button class="sheen-data-table-resizer" type="button" role="separator" aria-label={resizeLabel()} aria-controls={tableId} aria-orientation="vertical"
2169
+ aria-valuemin={column.definition.minWidth ?? 80} aria-valuemax={column.definition.maxWidth ?? 4096} aria-valuenow={reportedWidth()} aria-valuetext={messages().columnWidthPixels.replace("{width}", String(reportedWidth()))}
2170
+ onPointerDown={event => startResize(event, column)} onPointerMove={moveResize} onPointerUp={finishResize} onPointerCancel={cancelResize}
2171
+ onLostPointerCapture={() => { if (resizeSession?.column === column) cancelResize(); }} onKeyDown={event => resizeWithKeyboard(event, column)} onDblClick={() => autoFitColumn(column)} />
2172
+ </th>;
2173
+ }}</For>
2174
+ </tr></thead>
2175
+ <Show when={rowCount() > 0} fallback={<tbody data-state={bodyState()}><tr class="sheen-data-table-empty" style={{ "grid-template-columns": template() }}><td colSpan={stateColumnCount()} aria-colindex="1" aria-colspan={logicalColumnCount()}>
2176
+ <Show when={bodyState() === "cold"}>
2177
+ <div class="sheen-data-table-cold" data-visible={coldVisible() ? "" : undefined} role={coldVisible() ? "status" : undefined}>
2178
+ <span class="sheen-data-table-state-label">{messages().loading}</span>
2179
+ <For each={coldRows}>{() => <div class="sheen-data-table-skeleton-row" style={{ "grid-template-columns": template() }}>
2180
+ <For each={Array.from({ length: stateColumnCount() })}>{() => <Skeleton />}</For>
2181
+ </div>}</For>
2182
+ </div>
2183
+ </Show>
2184
+ <Show when={bodyState() === "error"}><div class="sheen-data-table-state" role="alert"><strong>{messages().serverError}</strong><span>{errorMessage(error())}</span><Button onClick={retry}>{messages().retry}</Button></div></Show>
2185
+ <Show when={bodyState() === "no-results"}><EmptyState kind="no-results"><Button onClick={clearQuery}>{clearQueryLabel()}</Button></EmptyState></Show>
2186
+ <Show when={bodyState() === "empty"}><EmptyState kind="empty" /></Show>
2187
+ </td></tr></tbody>}>
2188
+ <tbody style={{ height: `${virtualizer.getTotalSize()}px` }}>
2189
+ <For each={renderedRows()}>{current => {
2190
+ const row = () => current.row();
2191
+ const dataRow = () => displayDataRow(row());
2192
+ const groupRow = () => displayGroupRow(row());
2193
+ const labelColumn = () => {
2194
+ const visible = visibleDefinitions();
2195
+ return visible.some(column => column.definition.id === props.grouping?.by) ? props.grouping?.by : visible[0]?.definition.id;
2196
+ };
2197
+ function RowCells(): JSX.Element {
2198
+ return <>
2199
+ <Show when={selection}>
2200
+ <Show when={dataRow()} fallback={<td role={treePresentation ? "gridcell" : undefined} class="sheen-data-table-selection-cell" aria-colindex="1" aria-hidden="true" />}>
2201
+ {value => <RowSelectionCell row={value().row} />}
2202
+ </Show>
2203
+ </Show>
2204
+ <For each={visibleDefinitions()}>{column => {
2205
+ const edit = createMemo(() => {
2206
+ const value = dataRow();
2207
+ return value ? cellEditRecord(value.row, column) : undefined;
2208
+ });
2209
+ const state = () => editSnapshot(edit());
2210
+ const invalid = () => {
2211
+ const currentState = state();
2212
+ return Boolean(currentState && (currentState.invalid !== null || currentState.error !== null));
2213
+ };
2214
+ 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}
2215
+ data-editable={edit() ? "" : undefined} data-invalid={invalid() ? "" : undefined}
2216
+ data-stale={state()?.stale ? "" : undefined} data-pending={state()?.pending ? "" : undefined} data-conflict={state()?.conflict ? "" : undefined}>
2217
+ <Show when={dataRow()} fallback={<Show when={groupRow()}>{value => <GroupCellContent row={value()} column={column} labelColumn={column.definition.id === labelColumn()} />}</Show>}>
2218
+ {value => <DataCellContent row={value()} column={column} first={column === visibleDefinitions()[0]} edit={edit()} />}
2219
+ </Show>
2220
+ </td>;
2221
+ }}</For>
2222
+ </>;
2223
+ }
2224
+ if (props.actions === undefined) return <tr data-row-key={current.key} data-row-id={dataRow()?.row.id} data-group-id={groupRow()?.group.id}
2225
+ data-index={current.item().index} data-selected={dataRow() && rowSelected(dataRow()?.row.id ?? "") ? "" : undefined}
2226
+ data-loading={dataRow()?.pending ? "" : undefined} data-load-error={dataRow() && dataRow()?.error !== null ? "" : undefined}
2227
+ tabIndex={focusableRowKey() === current.key ? 0 : props.onRowActivate || selection || treePresentation ? -1 : undefined}
2228
+ aria-rowindex={logicalRowIndex(current.item().index)}
2229
+ aria-level={treePresentation ? dataRow()?.depth ?? 1 : undefined}
2230
+ aria-posinset={treePresentation ? row().position : undefined} aria-setsize={treePresentation ? row().setSize : undefined}
2231
+ aria-expanded={groupRow()?.expanded ?? (dataRow()?.canExpand ? dataRow()?.expanded : undefined)}
2232
+ aria-selected={selection && dataRow() ? rowSelected(dataRow()?.row.id ?? "") : undefined}
2233
+ aria-busy={dataRow()?.pending ? true : undefined}
2234
+ onFocus={() => setActiveRowKey(current.key)} onKeyDown={event => handleRowKeyDown(event, row())} onClick={event => handleRowClick(event, row())}
2235
+ ref={element => bindVirtualRow(element, current.item().index)}
2236
+ style={{ "grid-template-columns": template(), transform: `translateY(${current.item().start}px)`, "block-size": props.variableRowHeight ? undefined : rowHeight, "min-block-size": rowHeight }}>
2237
+ <RowCells />
2238
+ </tr>;
2239
+ const contextRow = dataRow();
2240
+ return <ContextMenu as="tr" items={contextRow ? rowActionItems(contextRow.row) : []} disabled={!contextRow || actions().length === 0 || pending()}
2241
+ onContextMenu={() => { const value = dataRow(); if (value) prepareContextSelection(value.row); }}
2242
+ data-row-key={current.key} data-row-id={dataRow()?.row.id} data-group-id={groupRow()?.group.id}
2243
+ data-index={current.item().index} data-selected={dataRow() && rowSelected(dataRow()?.row.id ?? "") ? "" : undefined}
2244
+ data-loading={dataRow()?.pending ? "" : undefined} data-load-error={dataRow() && dataRow()?.error !== null ? "" : undefined}
2245
+ tabIndex={focusableRowKey() === current.key ? 0 : props.onRowActivate || selection || treePresentation || actions().length > 0 ? -1 : undefined}
2246
+ aria-rowindex={logicalRowIndex(current.item().index)}
2247
+ aria-level={treePresentation ? dataRow()?.depth ?? 1 : undefined}
2248
+ aria-posinset={treePresentation ? row().position : undefined} aria-setsize={treePresentation ? row().setSize : undefined}
2249
+ aria-expanded={groupRow()?.expanded ?? (dataRow()?.canExpand ? dataRow()?.expanded : undefined)}
2250
+ aria-selected={selection && dataRow() ? rowSelected(dataRow()?.row.id ?? "") : undefined}
2251
+ aria-busy={dataRow()?.pending ? true : undefined}
2252
+ onFocus={() => setActiveRowKey(current.key)} onKeyDown={event => handleRowKeyDown(event, row())} onClick={event => handleRowClick(event, row())}
2253
+ ref={element => {
2254
+ if (!(element instanceof HTMLTableRowElement)) throw new Error("DataTable context rows must render as table rows");
2255
+ bindVirtualRow(element, current.item().index);
2256
+ }}
2257
+ style={{ "grid-template-columns": template(), transform: `translateY(${current.item().start}px)`, "block-size": props.variableRowHeight ? undefined : rowHeight, "min-block-size": rowHeight }}>
2258
+ <RowCells />
2259
+ </ContextMenu>;
2260
+ }}</For>
2261
+ </tbody>
2262
+ </Show>
2263
+ <Show when={hasFooter()}><tfoot><tr aria-rowindex={footerRowIndex()} style={{ "grid-template-columns": template() }}>
2264
+ <Show when={selection}><td role={treePresentation ? "gridcell" : undefined} class="sheen-data-table-selection-cell" aria-colindex="1" aria-hidden="true" /></Show>
2265
+ <For each={visibleDefinitions()}>{column => <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}>
2266
+ {typeof column.definition.footer === "function" ? column.definition.footer(footerRows()) : column.definition.footer ?? ""}
2267
+ </td>}</For>
2268
+ </tr></tfoot></Show>
2269
+ </table>
2270
+ </div>
2271
+ <Show when={mobileLayout}><div ref={element => { mobileViewport = element; }} class="sheen-data-table-mobile" tabindex="-1">
2272
+ <Show when={mobileRows().length > 0} fallback={<div class="sheen-data-table-mobile-state" data-state={bodyState()}>
2273
+ <Show when={bodyState() === "cold"}><div class="sheen-data-table-mobile-cold" data-visible={coldVisible() ? "" : undefined} role={coldVisible() ? "status" : undefined}>
2274
+ <span class="sheen-data-table-state-label">{messages().loading}</span>
2275
+ <For each={coldRows.slice(0, 3)}>{() => <div class="sheen-data-table-mobile-skeleton"><Skeleton /><Skeleton /><Skeleton /></div>}</For>
2276
+ </div></Show>
2277
+ <Show when={bodyState() === "error"}><div class="sheen-data-table-state" role="alert"><strong>{messages().serverError}</strong><span>{errorMessage(error())}</span><Button onClick={retry}>{messages().retry}</Button></div></Show>
2278
+ <Show when={bodyState() === "no-results"}><EmptyState kind="no-results"><Button onClick={clearQuery}>{clearQueryLabel()}</Button></EmptyState></Show>
2279
+ <Show when={bodyState() === "empty"}><EmptyState kind="empty" /></Show>
2280
+ </div>}>
2281
+ <Show when={Boolean(selection || mobileSortItems().length)}><div class="sheen-data-table-mobile-controls">
2282
+ <Show when={selection}><Checkbox data-sheen-selection-control="" class="sheen-data-table-selection-control" label={messages().selectPage}
2283
+ checked={mobileDataRows().length > 0 && mobileSelectedCount() === mobileDataRows().length}
2284
+ indeterminate={mobileSelectedCount() > 0 && mobileSelectedCount() < mobileDataRows().length}
2285
+ disabled={pending() || mobileDataRows().length === 0} onCheckedChange={selectMobileRows} /></Show>
2286
+ <Show when={mobileSortItems().length > 0}><DropdownMenu trigger={messages().sort} items={mobileSortItems()} disabled={pending()} /></Show>
2287
+ </div></Show>
2288
+ <div class="sheen-data-table-mobile-list" role="list" aria-label={messages().cardView.replaceAll("{caption}", props.caption)}>
2289
+ <Index each={mobileRows()}>{row => {
2290
+ const current = row;
2291
+ const data = () => displayDataRow(current());
2292
+ const interactive = Boolean(props.onRowActivate || selection || treePresentation || actions().length > 0);
2293
+ const tabIndex = () => interactive ? mobileFocusableKey() === current().key ? 0 : -1 : undefined;
2294
+ return <div class="sheen-data-table-mobile-card" role="listitem" data-mobile-row-key={current().key} data-mobile-row-id={data()?.row.id} data-mobile-group-id={displayGroupRow(current())?.group.id}
2295
+ data-selected={data() && rowSelected(data()?.row.id ?? "") ? "" : undefined} data-loading={data()?.pending ? "" : undefined} data-load-error={data() && data()?.error !== null ? "" : undefined}
2296
+ tabIndex={tabIndex()} aria-busy={data()?.pending ? true : undefined}
2297
+ onFocus={() => setActiveRowKey(current().key)} onKeyDown={event => handleMobileRowKeyDown(event, current())} onClick={event => handleRowClick(event, current())}>
2298
+ <MobileCardBody row={current()} />
2299
+ </div>;
2300
+ }}</Index>
2301
+ </div>
2302
+ <Show when={hasFooter()}><dl class="sheen-data-table-mobile-footer">
2303
+ <For each={visibleDefinitions().filter(column => column.definition.footer !== null)}>{column => <div class="sheen-data-table-mobile-field">
2304
+ <dt>{column.definition.header}</dt><dd>{typeof column.definition.footer === "function" ? column.definition.footer(footerRows()) : column.definition.footer}</dd>
2305
+ </div>}</For>
2306
+ </dl></Show>
2307
+ <Show when={mobileRange()}>{current => <Show when={current().pageCount > 1}><Pagination class="sheen-data-table-mobile-pagination" label={messages().cardView.replaceAll("{caption}", props.caption)} pageIndex={current().pageIndex} pageCount={current().pageCount} pending={busy()} disabled={previous()} onPageChange={requestMobilePage} /></Show>}</Show>
2308
+ </Show>
2309
+ </div></Show>
2310
+ <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}>
2311
+ <strong>{messages().selectedCount.replaceAll("{count}", groupNumberFormatter().format(selectionCount()))}</strong>
2312
+ <For each={actions()}>{action => {
2313
+ const context = () => actionContext();
2314
+ return <Button size="sm" tone={action.tone ?? "neutral"} disabled={actionDisabled(action, context())} onClick={() => action.onSelect(actionContext())}>{action.label}</Button>;
2315
+ }}</For>
2316
+ <Button size="sm" variant="outline" onClick={clearSelection}>{messages().clearSelection}</Button>
2317
+ </div></Show>
2318
+ </div>
2319
+ <Show when={range()}>{page => <Pagination class="sheen-data-table-pagination" pageIndex={page().pageIndex} pageCount={page().pageCount} pending={busy()} disabled={previous()} onPageChange={requestPage} />}</Show>
2320
+ <Show when={editToaster}>{controller => <Toaster controller={controller()} />}</Show>
2321
+ </section>;
2322
+ }