@gemologic/sheen-table 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/DataTable.d.ts +7 -0
  2. package/dist/DataTable.js +1154 -1624
  3. package/dist/DataTableToolbar.js +1 -2
  4. package/dist/FilterBar.d.ts +3 -0
  5. package/dist/FilterBar.js +127 -108
  6. package/dist/QueryBuilder.js +72 -68
  7. package/dist/cell-edit.js +1 -2
  8. package/dist/client-state.js +20 -21
  9. package/dist/client-view.js +12 -13
  10. package/dist/column-layout.js +1 -2
  11. package/dist/columns.d.ts +5 -1
  12. package/dist/columns.js +7 -5
  13. package/dist/constrained-columns.js +1 -2
  14. package/dist/data-table-features.d.ts +129 -0
  15. package/dist/data-table-features.js +550 -0
  16. package/dist/export.js +1 -2
  17. package/dist/facets.js +5 -7
  18. package/dist/filter-bar-state.js +14 -18
  19. package/dist/filter-client.js +1 -2
  20. package/dist/filter.js +1 -2
  21. package/dist/grouping.js +1 -2
  22. package/dist/index.js +3 -3
  23. package/dist/messages.d.ts +1 -1
  24. package/dist/messages.js +2 -3
  25. package/dist/pagination.js +1 -2
  26. package/dist/query-builder-state.js +1 -2
  27. package/dist/requests.js +1 -2
  28. package/dist/row-hierarchy.js +1 -2
  29. package/dist/row-identity.js +1 -2
  30. package/dist/saved-views.js +1 -2
  31. package/dist/search-controller.js +1 -2
  32. package/dist/search.js +1 -2
  33. package/dist/selection-client.js +1 -2
  34. package/dist/selection.d.ts +3 -0
  35. package/dist/selection.js +9 -2
  36. package/dist/server-export.js +1 -2
  37. package/dist/sorting.js +1 -2
  38. package/dist/table-state-changes.js +1 -2
  39. package/dist/table-state.js +1 -2
  40. package/dist/text-normalization.js +1 -2
  41. package/dist/url-state.js +1 -2
  42. package/package.json +5 -5
  43. package/src/DataTable.tsx +285 -712
  44. package/src/FilterBar.tsx +17 -3
  45. package/src/QueryBuilder.tsx +5 -5
  46. package/src/columns.ts +9 -3
  47. package/src/data-table-features.tsx +579 -0
  48. package/src/messages.ts +1 -1
  49. package/src/selection.ts +8 -0
  50. package/src/styles.css +17 -11
@@ -0,0 +1,579 @@
1
+ import { Toaster, createToaster } from "@gemologic/sheen";
2
+ import { For, Show, createComputed, createEffect, createMemo, createSignal, createUniqueId, on, onCleanup, onMount, untrack } from "solid-js";
3
+ import type { Accessor, JSX } from "solid-js";
4
+ import type { ColumnEditor, ColumnValue, ResolvedColumn } from "./columns.ts";
5
+ import { createCellEdit } from "./cell-edit.ts";
6
+ import type { CellCommitOutcome, CellEditSnapshot } from "./cell-edit.ts";
7
+ import type { DataTableCellCommitRequest, DataTableProps, DataTableResult } from "./DataTable.tsx";
8
+ import type { FilterColumn, FilterNode } from "./filter.ts";
9
+ import { groupClientRows, normalizeServerGroups } from "./grouping.ts";
10
+ import type { ClientRowGroup } from "./grouping.ts";
11
+ import type { TableMessages } from "./messages.ts";
12
+ import { createRowHierarchy } from "./row-hierarchy.ts";
13
+ import type { HierarchyRow } from "./row-hierarchy.ts";
14
+ import { createRowIdentity } from "./row-identity.ts";
15
+
16
+ /** One application row with a stable ID. The accessor follows the current source row for that ID. */
17
+ export interface StableRow<Row extends object> {
18
+ readonly id: string;
19
+ readonly value: Accessor<Row>;
20
+ }
21
+
22
+ export interface StableRows<Row extends object> {
23
+ readonly resolve: (row: Row, index: number) => StableRow<Row>;
24
+ }
25
+
26
+ export interface DisplayDataRow<Row extends object> {
27
+ readonly kind: "data";
28
+ readonly key: string;
29
+ readonly row: StableRow<Row>;
30
+ readonly parentId: string | null;
31
+ readonly depth: number;
32
+ readonly position: number;
33
+ readonly setSize: number;
34
+ readonly canExpand: boolean;
35
+ readonly expanded: boolean;
36
+ readonly unloaded: boolean;
37
+ readonly pending: boolean;
38
+ readonly error: unknown;
39
+ }
40
+
41
+ export interface DisplayGroupRow<Row extends object> {
42
+ readonly kind: "group";
43
+ readonly key: string;
44
+ readonly group: ClientRowGroup<Row>;
45
+ readonly label: string;
46
+ readonly position: number;
47
+ readonly setSize: number;
48
+ readonly expanded: boolean;
49
+ }
50
+
51
+ export type DisplayRow<Row extends object> = DisplayDataRow<Row> | DisplayGroupRow<Row>;
52
+
53
+ /** What a feature may read from, and ask of, the table that composes it. */
54
+ export interface DataTableFeatureContext<Row extends object> {
55
+ readonly props: DataTableProps<Row>;
56
+ readonly definitions: readonly ResolvedColumn<Row>[];
57
+ readonly filterColumns: readonly FilterColumn[];
58
+ readonly messages: Accessor<TableMessages>;
59
+ readonly locale: Accessor<string>;
60
+ /** A query is unsettled. Structural changes wait for accepted state. */
61
+ readonly pending: Accessor<boolean>;
62
+ /** Accepted rows, total, facets, and server groups. */
63
+ readonly result: Accessor<DataTableResult<Row>>;
64
+ readonly accepted: Accessor<boolean>;
65
+ readonly acceptedFilter: Accessor<FilterNode>;
66
+ readonly requestFilter: (filter: FilterNode) => void;
67
+ /** Stable rows for the table's own source (client data or the accepted server page). */
68
+ readonly stableRows: StableRows<Row>;
69
+ readonly createStableRows: (source: Accessor<readonly Row[]>) => StableRows<Row>;
70
+ readonly rowAt: (index: number) => DisplayRow<Row> | undefined;
71
+ readonly rowIndex: (key: string, hint?: number) => number;
72
+ readonly focusRow: (index: number) => void;
73
+ }
74
+
75
+ /** Replaces the flat row model with a structured treegrid presentation. At most one may be active. */
76
+ export interface DataTablePresentation<Row extends object> {
77
+ readonly rows: Accessor<readonly DisplayRow<Row>[]>;
78
+ readonly allowSelectAll: boolean;
79
+ /** Column that labels group rows when it is visible. */
80
+ readonly labelColumn?: string;
81
+ /** Returns true when the feature handled the key. Cards omit child/parent focus movement. */
82
+ readonly keyDown: (event: KeyboardEvent, row: DisplayRow<Row>, index: number, layout: "table" | "cards") => boolean;
83
+ /** Wraps the first visible data cell with tree indentation and expansion controls. */
84
+ readonly TreeCell: (props: { readonly row: DisplayDataRow<Row>; readonly children: JSX.Element }) => JSX.Element;
85
+ readonly GroupCell?: (props: { readonly row: DisplayGroupRow<Row>; readonly column: ResolvedColumn<Row>; readonly label: boolean }) => JSX.Element;
86
+ }
87
+
88
+ export interface DataTableCellAttributes {
89
+ readonly "data-editable"?: "";
90
+ readonly "data-invalid"?: "";
91
+ readonly "data-stale"?: "";
92
+ readonly "data-pending"?: "";
93
+ readonly "data-conflict"?: "";
94
+ }
95
+
96
+ /** Per-cell extension bound inside the owning cell. */
97
+ export interface DataTableCellBinding<Row extends object> {
98
+ readonly active: Accessor<boolean>;
99
+ readonly attributes: Accessor<DataTableCellAttributes>;
100
+ readonly render: (row: Accessor<DisplayDataRow<Row>>) => JSX.Element;
101
+ }
102
+
103
+ export interface DataTableFeatureInstance<Row extends object> {
104
+ readonly presentation?: DataTablePresentation<Row>;
105
+ /** Toolbar query control rendered beside search. */
106
+ readonly query?: { readonly visible: Accessor<boolean>; readonly render: () => JSX.Element };
107
+ /** Returns undefined for columns the feature does not own. */
108
+ readonly cell?: (row: Accessor<DisplayDataRow<Row> | undefined>, column: ResolvedColumn<Row>) => DataTableCellBinding<Row> | undefined;
109
+ /** Rendered once at the end of the table section. */
110
+ readonly overlay?: () => JSX.Element;
111
+ }
112
+
113
+ /**
114
+ * Internal composition contract. A feature validates the props it owns and returns undefined when inactive.
115
+ * Features are row-agnostic so a later public `features` list can type-check against any DataTable.
116
+ */
117
+ export type DataTableFeature = <Row extends object>(context: DataTableFeatureContext<Row>) => DataTableFeatureInstance<Row> | undefined;
118
+
119
+ export function defaultCell(value: ColumnValue): JSX.Element {
120
+ if (value === null) return "";
121
+ if (typeof value === "boolean") return value ? "Yes" : "No";
122
+ return String(value);
123
+ }
124
+
125
+ /**
126
+ * Holds a framework-neutral store's immutable snapshot in a signal. Stores publish by replacing their
127
+ * snapshot object, so equal references do not notify readers.
128
+ */
129
+ export function createSnapshotSignal<Snapshot>(read: () => Snapshot): { readonly snapshot: Accessor<Snapshot>; readonly sync: () => void; readonly track: <Value>(completion: Promise<Value>) => Promise<Value> } {
130
+ const [snapshot, setSnapshot] = createSignal(read());
131
+ const sync = (): void => { setSnapshot(() => read()); };
132
+ return {
133
+ snapshot,
134
+ sync,
135
+ track: completion => {
136
+ sync();
137
+ return completion.finally(sync);
138
+ },
139
+ };
140
+ }
141
+
142
+ /**
143
+ * Resolves stable row records lazily by ID. Each record reads the validated source index, so a changed row
144
+ * object reaches only the readers of that record without writing reactive state while deriving rows.
145
+ */
146
+ export function createStableRows<Row extends object>(getRowId: (row: Row) => string, source: Accessor<readonly Row[]>): StableRows<Row> {
147
+ const identity = createRowIdentity(getRowId);
148
+ const records = new Map<string, StableRow<Row>>();
149
+ const index = createMemo(() => {
150
+ const rows = source();
151
+ const ids = identity.resolveIds(rows);
152
+ const byId = new Map<string, Row>();
153
+ for (let position = 0; position < rows.length; position++) byId.set(ids[position]!, rows[position]!);
154
+ for (const id of records.keys()) if (!byId.has(id)) records.delete(id);
155
+ return byId;
156
+ });
157
+ function create(id: string, row: Row): StableRow<Row> {
158
+ let last = row;
159
+ const record: StableRow<Row> = Object.freeze({
160
+ id,
161
+ value: (): Row => {
162
+ const current = index().get(id);
163
+ if (current !== undefined) last = current;
164
+ return last;
165
+ },
166
+ });
167
+ records.set(id, record);
168
+ return record;
169
+ }
170
+ return Object.freeze({
171
+ resolve(row: Row, position: number): StableRow<Row> {
172
+ const id = getRowId(row);
173
+ if (!index().has(id)) throw new Error(`Result row at index ${position} is not part of the supplied data`);
174
+ return records.get(id) ?? create(id, row);
175
+ },
176
+ });
177
+ }
178
+
179
+ function TreeCell<Row extends object>(props: {
180
+ readonly row: DisplayDataRow<Row>;
181
+ readonly children: JSX.Element;
182
+ readonly messages: TableMessages;
183
+ readonly pending: boolean;
184
+ readonly onToggle: (row: DisplayDataRow<Row>) => void;
185
+ readonly onRetry: (row: DisplayDataRow<Row>) => void;
186
+ }): JSX.Element {
187
+ return <div class="sheen-data-table-tree-cell" style={{ "--sheen-table-depth": Math.max(0, props.row.depth - 1) }}>
188
+ <Show when={props.row.canExpand} fallback={<span class="sheen-data-table-expander-space" aria-hidden="true" />}>
189
+ <button type="button" class="sheen-data-table-expander" aria-label={`${props.row.expanded ? props.messages.collapse : props.messages.expand} ${props.row.row.id}`} aria-expanded={props.row.expanded} disabled={props.pending}
190
+ onClick={() => props.onToggle(props.row)}>{props.row.expanded ? "▾" : "▸"}</button>
191
+ </Show>
192
+ <span class="sheen-data-table-tree-value">{props.children}</span>
193
+ <Show when={props.row.pending}><span class="sheen-data-table-row-status" role="status">{props.messages.loadingChildren}</span></Show>
194
+ <Show when={props.row.error !== null}><span class="sheen-data-table-row-status" role="alert">{props.messages.serverError} <button type="button" onClick={() => props.onRetry(props.row)}>{props.messages.retry}</button></span></Show>
195
+ </div>;
196
+ }
197
+
198
+ function plainKey(event: KeyboardEvent): boolean {
199
+ return !event.ctrlKey && !event.metaKey && !event.shiftKey;
200
+ }
201
+
202
+ /** First-seen groups over complete client data or delegated server groups for the accepted page. */
203
+ export function groupingFeature<Row extends object>(context: DataTableFeatureContext<Row>): DataTableFeatureInstance<Row> | undefined {
204
+ const props = context.props;
205
+ const options = props.grouping;
206
+ if (!options) return undefined;
207
+ if (props.mode !== "server" && props.pagination !== false) throw new Error("Client grouping requires complete continuous data with pagination=false");
208
+ if (typeof options.by !== "string" || !options.by.trim()) throw new Error("DataTable grouping requires a column ID");
209
+ if (options.getLabel !== undefined && typeof options.getLabel !== "function") throw new Error("DataTable grouping getLabel must be a function");
210
+ const column = context.definitions.find(definition => definition.id === options.by);
211
+ const getValue = column?.accessor;
212
+ if (!column || !getValue) throw new Error(`Grouping column ${options.by} must be an accessor column`);
213
+ const aggregateColumns = context.definitions.flatMap(definition => definition.aggregate && definition.accessor ? [{ id: definition.id, aggregate: definition.aggregate, getValue: definition.accessor }] : []);
214
+ const [overrides, setOverrides] = createSignal<ReadonlyMap<string, boolean>>(new Map());
215
+ // A group's default is fixed when it is first presented; later option changes affect only new groups.
216
+ const defaults = new Map<string, boolean>();
217
+ const numberFormatter = createMemo(() => new Intl.NumberFormat(context.locale()));
218
+
219
+ function expanded(id: string): boolean {
220
+ const override = overrides().get(id);
221
+ if (override !== undefined) return override;
222
+ const known = defaults.get(id);
223
+ if (known !== undefined) return known;
224
+ const initial = props.grouping?.collapsible === false || props.grouping?.defaultExpanded !== false;
225
+ defaults.set(id, initial);
226
+ return initial;
227
+ }
228
+ function setExpanded(id: string, value: boolean): void {
229
+ if (context.pending() || props.grouping?.collapsible === false || expanded(id) === value) return;
230
+ setOverrides(previous => new Map(previous).set(id, value));
231
+ }
232
+ function label(group: ClientRowGroup<Row>): string {
233
+ const supplied = props.grouping?.getLabel?.(group.value);
234
+ const value = supplied ?? (group.value === null ? context.messages().groupMissing : typeof group.value === "number" ? numberFormatter().format(group.value) : String(group.value));
235
+ if (typeof value !== "string" || !value.trim()) throw new Error(`Group ${group.id} requires a nonempty label`);
236
+ return value;
237
+ }
238
+
239
+ const rows = createMemo<readonly DisplayRow<Row>[]>(() => {
240
+ if (props.mode === "server" && !context.accepted()) return Object.freeze([]);
241
+ const current = context.result();
242
+ const groups = props.mode === "server"
243
+ ? normalizeServerGroups(current.rows, current.groups, { column: column.id, aggregateColumns: aggregateColumns.map(aggregate => aggregate.id), getRowId: props.getRowId })
244
+ : groupClientRows(current.rows, { column: column.id, getValue, aggregates: aggregateColumns });
245
+ const display: DisplayRow<Row>[] = [];
246
+ let sourceIndex = 0;
247
+ for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
248
+ const group = groups[groupIndex]!;
249
+ const open = expanded(group.id);
250
+ display.push(Object.freeze({ kind: "group", key: group.id, group, label: label(group), position: groupIndex + 1, setSize: groups.length, expanded: open }));
251
+ for (let rowIndex = 0; rowIndex < group.rows.length; rowIndex++, sourceIndex++) {
252
+ if (!open) continue;
253
+ const row = context.stableRows.resolve(group.rows[rowIndex]!, sourceIndex);
254
+ display.push(Object.freeze({ kind: "data", key: `row:${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 }));
255
+ }
256
+ }
257
+ return Object.freeze(display);
258
+ });
259
+
260
+ const ignore = (): void => undefined;
261
+ return {
262
+ presentation: {
263
+ rows,
264
+ allowSelectAll: true,
265
+ labelColumn: column.id,
266
+ keyDown(event, row) {
267
+ if (row.kind !== "group" || !plainKey(event)) return false;
268
+ if (event.key === " " || event.key === "Enter") setExpanded(row.group.id, !row.expanded);
269
+ else if (event.key === "ArrowRight" || event.key === "ArrowLeft") setExpanded(row.group.id, event.key === "ArrowRight");
270
+ else return false;
271
+ event.preventDefault();
272
+ return true;
273
+ },
274
+ TreeCell: cellProps => <TreeCell row={cellProps.row} messages={context.messages()} pending={context.pending()} onToggle={ignore} onRetry={ignore}>{cellProps.children}</TreeCell>,
275
+ GroupCell: cellProps => {
276
+ if (cellProps.label) return <div class="sheen-data-table-tree-cell" style={{ "--sheen-table-depth": 0 }}>
277
+ <Show when={props.grouping?.collapsible !== false} fallback={<span class="sheen-data-table-expander-space" aria-hidden="true" />}>
278
+ <button type="button" class="sheen-data-table-expander" disabled={context.pending()} aria-label={`${cellProps.row.expanded ? context.messages().collapse : context.messages().expand} ${cellProps.row.label}`}
279
+ aria-expanded={cellProps.row.expanded} onClick={() => setExpanded(cellProps.row.group.id, !cellProps.row.expanded)}>{cellProps.row.expanded ? "▾" : "▸"}</button>
280
+ </Show>
281
+ <span class="sheen-data-table-group-label">{cellProps.row.label} <span class="sheen-data-table-group-count">({numberFormatter().format(cellProps.row.group.count)})</span></span>
282
+ </div>;
283
+ return defaultCell(cellProps.row.group.aggregates.find(value => value.column === cellProps.column.id)?.value ?? null);
284
+ },
285
+ },
286
+ };
287
+ }
288
+
289
+ /** Expandable parent rows with synchronous children or independently loaded subtrees. */
290
+ export function hierarchyFeature<Row extends object>(context: DataTableFeatureContext<Row>): DataTableFeatureInstance<Row> | undefined {
291
+ const props = context.props;
292
+ const options = props.hierarchy;
293
+ if (!options) return undefined;
294
+ if (!options.getChildren && !options.onLoadChildren) throw new Error("DataTable hierarchy requires getChildren or onLoadChildren");
295
+ if (options.onLoadChildren && !options.hasChildren) throw new Error("Async DataTable hierarchy requires hasChildren");
296
+ if (typeof options.resetKey === "number" && !Number.isFinite(options.resetKey)) throw new Error("DataTable hierarchy resetKey must be a finite number or string");
297
+ const store = createRowHierarchy<Row>({
298
+ getRowId: props.getRowId,
299
+ ...(options.getChildren ? { getChildren: options.getChildren } : {}),
300
+ ...(options.hasChildren ? { canLoadChildren: options.hasChildren } : {}),
301
+ ...(options.onLoadChildren ? { loadChildren: options.onLoadChildren } : {}),
302
+ ...(options.defaultExpanded !== undefined ? { defaultExpanded: options.defaultExpanded } : {}),
303
+ });
304
+ onCleanup(() => store.dispose());
305
+ const { snapshot, sync, track } = createSnapshotSignal<readonly HierarchyRow<Row>[]>(store.getSnapshot);
306
+ let resetKey = options.resetKey;
307
+ // Accepted roots and the authorization boundary drive the store before any row derivation reads it.
308
+ createComputed(() => {
309
+ const roots = context.result().rows;
310
+ const nextResetKey = props.hierarchy?.resetKey;
311
+ untrack(() => {
312
+ if (!Object.is(nextResetKey, resetKey)) store.reset();
313
+ resetKey = nextResetKey;
314
+ store.updateRoots(roots);
315
+ sync();
316
+ });
317
+ });
318
+ const stableRows = context.createStableRows(() => snapshot().map(item => item.row));
319
+ const rows = createMemo<readonly DisplayRow<Row>[]>(() => Object.freeze(snapshot().map((item, index): DisplayDataRow<Row> => {
320
+ const row = stableRows.resolve(item.row, index);
321
+ 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 });
322
+ })));
323
+
324
+ function changeExpansion(row: DisplayDataRow<Row>, expanded: boolean): void {
325
+ if (context.pending()) return;
326
+ void track(store.setExpanded(row.row.id, expanded));
327
+ }
328
+ function retry(row: DisplayDataRow<Row>): void {
329
+ if (context.pending()) return;
330
+ void track(store.retry(row.row.id));
331
+ }
332
+ const [mounted, setMounted] = createSignal(false);
333
+ onMount(() => { setMounted(true); });
334
+ createEffect(() => {
335
+ if (!mounted()) return;
336
+ for (const row of rows()) if (row.kind === "data" && row.expanded && row.unloaded && !row.pending && row.error === null) changeExpansion(row, true);
337
+ });
338
+
339
+ return {
340
+ presentation: {
341
+ rows,
342
+ allowSelectAll: false,
343
+ keyDown(event, row, index, layout) {
344
+ if (row.kind !== "data" || !plainKey(event)) return false;
345
+ if (layout === "cards") {
346
+ if (!row.canExpand || (event.key !== "ArrowRight" && event.key !== "ArrowLeft")) return false;
347
+ event.preventDefault();
348
+ changeExpansion(row, event.key === "ArrowRight");
349
+ return true;
350
+ }
351
+ if (row.canExpand && event.key === "ArrowRight") {
352
+ event.preventDefault();
353
+ if (!row.expanded) changeExpansion(row, true);
354
+ else {
355
+ const current = context.rowIndex(row.key, index);
356
+ const child = context.rowAt(current + 1);
357
+ if (child?.kind === "data" && child.parentId === row.row.id) context.focusRow(current + 1);
358
+ }
359
+ return true;
360
+ }
361
+ if (event.key !== "ArrowLeft") return false;
362
+ event.preventDefault();
363
+ if (row.expanded) changeExpansion(row, false);
364
+ else if (row.parentId) {
365
+ const parent = rows().findIndex(candidate => candidate.kind === "data" && candidate.row.id === row.parentId);
366
+ if (parent >= 0) context.focusRow(parent);
367
+ }
368
+ return true;
369
+ },
370
+ TreeCell: cellProps => <TreeCell row={cellProps.row} messages={context.messages()} pending={context.pending()} onToggle={row => changeExpansion(row, !row.expanded)} onRetry={retry}>{cellProps.children}</TreeCell>,
371
+ },
372
+ };
373
+ }
374
+
375
+ function editorAccepts<Row extends object>(editor: ColumnEditor<Row>, value: ColumnValue): boolean {
376
+ if (value === null) return editor.nullable === true;
377
+ if (editor.type === "text") return typeof value === "string";
378
+ if (editor.type === "number") return typeof value === "number";
379
+ if (editor.type === "boolean") return typeof value === "boolean";
380
+ if (editor.type === "select") return typeof value === "string" && editor.options.includes(value);
381
+ return false;
382
+ }
383
+
384
+ interface CellEditRecord {
385
+ readonly controller: ReturnType<typeof createCellEdit<ColumnValue, string>>;
386
+ readonly snapshot: Accessor<CellEditSnapshot<ColumnValue, string>>;
387
+ readonly sync: () => void;
388
+ }
389
+
390
+ /** Inline editing for columns that declare an editor. Drafts survive virtualization until the reset boundary changes. */
391
+ export function cellEditingFeature<Row extends object>(context: DataTableFeatureContext<Row>): DataTableFeatureInstance<Row> | undefined {
392
+ const props = context.props;
393
+ const editable = context.definitions.filter(column => column.editor !== null);
394
+ if (editable.length > 0 && !props.onCellCommit) throw new Error("DataTable editable columns require onCellCommit");
395
+ if (editable.length === 0 && props.onCellCommit) throw new Error("DataTable onCellCommit requires at least one editable column");
396
+ for (const column of editable) {
397
+ if (!column.accessor || !column.editor) throw new Error(`Editable column ${column.id} requires an accessor and editor`);
398
+ }
399
+ const commit = props.onCellCommit;
400
+ if (!commit) return undefined;
401
+ const toaster = createToaster();
402
+ // Each reset boundary owns its records; replacing the scope disposes drafts and aborts in-flight commits.
403
+ const scope = createMemo(() => {
404
+ const resetKey = props.editResetKey;
405
+ if (typeof resetKey === "number" && !Number.isFinite(resetKey)) throw new Error("DataTable editResetKey must be a finite number or string");
406
+ const records = new Map<string, CellEditRecord>();
407
+ onCleanup(() => { for (const record of records.values()) record.controller.dispose(); });
408
+ return records;
409
+ });
410
+ createEffect(on(() => props.editResetKey, () => toaster.clear(), { defer: true }));
411
+
412
+ function recordFor(records: Map<string, CellEditRecord>, row: StableRow<Row>, column: ResolvedColumn<Row>): CellEditRecord | undefined {
413
+ const editor = column.editor;
414
+ const accessor = column.accessor;
415
+ if (!editor || !accessor || !commit) return undefined;
416
+ const key = `${row.id}\u0000${column.id}`;
417
+ const existing = records.get(key);
418
+ if (existing) return existing;
419
+ const initial = accessor(untrack(row.value));
420
+ if (!editorAccepts(editor, initial)) throw new Error(`Initial value for editable cell ${row.id}/${column.id} does not match its editor`);
421
+ const controller = createCellEdit<ColumnValue, string>(initial, async (request, signal) => {
422
+ const applicationRequest: DataTableCellCommitRequest<Row> = Object.freeze({ ...request, rowId: row.id, row: untrack(row.value), column: column.id });
423
+ const result = await commit(applicationRequest, signal);
424
+ const value = result.kind === "accepted" ? result.value : result.current;
425
+ if (!editorAccepts(editor, value)) throw new Error(`Committed value for ${row.id}/${column.id} does not match its editor`);
426
+ return result;
427
+ }, { validate: value => {
428
+ if (!editorAccepts(editor, value)) return value === null ? context.messages().cellValueRequired : context.messages().cellValueInvalid;
429
+ return editor.validate?.(value, untrack(row.value)) ?? null;
430
+ } });
431
+ const { snapshot, sync } = createSnapshotSignal(controller.getSnapshot);
432
+ const record = Object.freeze({ controller, snapshot, sync });
433
+ records.set(key, record);
434
+ return record;
435
+ }
436
+
437
+ function EditableCellValue(cellProps: { readonly row: DisplayDataRow<Row>; readonly column: ResolvedColumn<Row>; readonly record: CellEditRecord }): JSX.Element {
438
+ const editor = cellProps.column.editor;
439
+ const accessor = cellProps.column.accessor;
440
+ if (!editor || !accessor) throw new Error(`Editable cell ${cellProps.row.row.id}/${cellProps.column.id} is missing its editor`);
441
+ const activeEditor = editor;
442
+ const id = createUniqueId();
443
+ let editorElement: HTMLInputElement | HTMLSelectElement | undefined;
444
+ let restingElement: HTMLSpanElement | undefined;
445
+ let restoringRestingFocus = false;
446
+ let incoming = accessor(untrack(cellProps.row.row.value));
447
+ const snapshot = (): CellEditSnapshot<ColumnValue, string> => cellProps.record.snapshot();
448
+ const draft = (): ColumnValue => snapshot().draft?.value ?? snapshot().committed;
449
+ const label = () => context.messages().editCell.replaceAll("{column}", cellProps.column.header).replaceAll("{id}", cellProps.row.row.id);
450
+ const message = () => {
451
+ const current = snapshot();
452
+ if (current.invalid) return current.invalid;
453
+ if (current.conflict) return context.messages().cellConflict.replaceAll("{value}", current.conflict.current === null ? context.messages().noValue : String(current.conflict.current));
454
+ return current.error ? context.messages().cellUpdateFailedDescription : null;
455
+ };
456
+ const content = () => cellProps.column.cell?.(snapshot().committed, cellProps.row.row.value()) ?? defaultCell(snapshot().committed);
457
+
458
+ createEffect(() => {
459
+ const next = accessor(cellProps.row.row.value());
460
+ if (Object.is(next, incoming)) return;
461
+ incoming = next;
462
+ cellProps.record.controller.acceptRefetch(next);
463
+ cellProps.record.sync();
464
+ });
465
+
466
+ function focusEditor(): void { queueMicrotask(() => editorElement?.focus({ preventScroll: true })); }
467
+ function focusResting(): void {
468
+ queueMicrotask(() => {
469
+ restoringRestingFocus = true;
470
+ try { restingElement?.focus({ preventScroll: true }); }
471
+ finally { restoringRestingFocus = false; }
472
+ });
473
+ }
474
+ function begin(): void {
475
+ if (restoringRestingFocus || context.pending()) return;
476
+ if (cellProps.record.controller.begin()) {
477
+ cellProps.record.sync();
478
+ focusEditor();
479
+ }
480
+ }
481
+ function update(value: ColumnValue): void {
482
+ cellProps.record.controller.setDraft(value);
483
+ cellProps.record.sync();
484
+ }
485
+ async function finish(completion: Promise<CellCommitOutcome>, restore: boolean, notify = true): Promise<CellCommitOutcome> {
486
+ cellProps.record.sync();
487
+ const outcome = await completion;
488
+ cellProps.record.sync();
489
+ const current = snapshot();
490
+ if (outcome === "accepted" && !current.editing && restore) focusResting();
491
+ if ((outcome === "invalid" || outcome === "conflict") && restore) focusEditor();
492
+ if (outcome === "failed" && notify) toaster.show({
493
+ title: context.messages().cellUpdateFailed,
494
+ description: context.messages().cellUpdateFailedDescription,
495
+ tone: "danger",
496
+ priority: "assertive",
497
+ duration: null,
498
+ action: {
499
+ label: context.messages().retry,
500
+ retryLabel: context.messages().retry,
501
+ errorMessage: context.messages().retryFailed,
502
+ run: async () => {
503
+ const retried = await finish(cellProps.record.controller.retry(), false, false);
504
+ if (retried !== "accepted") throw new Error(`Cell retry was not accepted: ${retried}`);
505
+ focusResting();
506
+ },
507
+ },
508
+ });
509
+ return outcome;
510
+ }
511
+ function commitDraft(restore: boolean): void { void finish(cellProps.record.controller.commit(), restore); }
512
+ function blur(): void {
513
+ const current = snapshot();
514
+ const unchangedFailure = (current.error !== null || current.conflict !== null) && current.attempt !== null && current.draft !== null && Object.is(current.attempt.value, current.draft.value);
515
+ if (!unchangedFailure) commitDraft(false);
516
+ }
517
+ function keyDown(event: KeyboardEvent): void {
518
+ if (event.key === "Enter") {
519
+ event.preventDefault();
520
+ commitDraft(true);
521
+ } else if (event.key === "Escape") {
522
+ event.preventDefault();
523
+ cellProps.record.controller.discard();
524
+ cellProps.record.sync();
525
+ focusResting();
526
+ }
527
+ }
528
+ function EditorControl(): JSX.Element {
529
+ const invalid = () => snapshot().invalid !== null || snapshot().error !== null || undefined;
530
+ const describedBy = () => message() ? `${id}-message` : undefined;
531
+ 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"
532
+ aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown} onChange={event => update(event.currentTarget.checked)} />;
533
+ if (activeEditor.type === "select") return <select ref={element => { editorElement = element; element.value = draft() === null ? "" : String(draft()); }} class="sheen-data-table-editor"
534
+ 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)}>
535
+ <Show when={activeEditor.nullable}><option value="">{context.messages().noValue}</option></Show>
536
+ <For each={activeEditor.options}>{option => <option value={option}>{option}</option>}</For>
537
+ </select>;
538
+ 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"
539
+ aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown}
540
+ onInput={event => update(event.currentTarget.value === "" ? null : event.currentTarget.valueAsNumber)} />;
541
+ return <input ref={element => { editorElement = element; element.value = draft() === null ? "" : String(draft()); }} class="sheen-data-table-editor" type="text"
542
+ aria-label={label()} aria-describedby={describedBy()} aria-invalid={invalid()} aria-busy={snapshot().pending || undefined} onBlur={blur} onKeyDown={keyDown}
543
+ onInput={event => update(event.currentTarget.value === "" && activeEditor.nullable ? null : event.currentTarget.value)} />;
544
+ }
545
+ return <span class="sheen-data-table-edit-value">
546
+ <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}
547
+ onKeyDown={event => { if (event.key === "Enter") { event.preventDefault(); begin(); } }}>{content()}</span>}>
548
+ <EditorControl />
549
+ </Show>
550
+ <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>
551
+ </span>;
552
+ }
553
+
554
+ return {
555
+ cell(row, column) {
556
+ if (!column.editor) return undefined;
557
+ const record = createMemo(() => {
558
+ const value = row();
559
+ return value ? recordFor(scope(), value.row, column) : undefined;
560
+ });
561
+ return {
562
+ active: () => record() !== undefined,
563
+ attributes: () => {
564
+ const current = record()?.snapshot();
565
+ if (!current) return {};
566
+ return {
567
+ "data-editable": "",
568
+ ...(current.invalid !== null || current.error !== null ? { "data-invalid": "" } : {}),
569
+ ...(current.stale ? { "data-stale": "" } : {}),
570
+ ...(current.pending ? { "data-pending": "" } : {}),
571
+ ...(current.conflict ? { "data-conflict": "" } : {}),
572
+ };
573
+ },
574
+ render: value => <Show when={record()} keyed>{current => <EditableCellValue row={value()} column={column} record={current} />}</Show>,
575
+ };
576
+ },
577
+ overlay: () => <Toaster controller={toaster} />,
578
+ };
579
+ }
package/src/messages.ts CHANGED
@@ -5,7 +5,7 @@ export const englishTableMessages = Object.freeze({
5
5
  cardView: "{caption}, card view", rowActions: "Actions for row {id}",
6
6
  sort: "Sort", sortColumn: "Sort by {column}", sortedAscending: "ascending", sortedDescending: "descending", notSorted: "not sorted", sortPriority: "priority {position} of {count}",
7
7
  export: "Export", exportCSV: "Export CSV", exportJSON: "Export JSON", preparingExport: "Preparing export", exportFailed: "Export failed", retryExport: "Retry export", downloadLastExport: "Download last export",
8
- filters: "Filters", filterAdd: "+ Filter", filterColumns: "Filter columns", filterSearchColumns: "Search filter columns", filterEdit: "Edit filter", filterRemove: "Remove filter", filterApply: "Apply filter",
8
+ filters: "Filters", filterAdd: "Add filter", filterColumns: "Filter columns", filterSearchColumns: "Search filter columns", filterEdit: "Edit filter", filterRemove: "Remove filter", filterApply: "Apply filter",
9
9
  filterOperator: "Operator", filterValue: "Value", filterMinimum: "Minimum", filterMaximum: "Maximum", filterDate: "Date", filterStartDate: "Start date", filterEndDate: "End date", filterValues: "Values",
10
10
  filterCaseSensitive: "Case sensitive", filterNegated: "Exclude matches", filterInheritedNegation: "This condition is also inside an excluded group.", filterInvalid: "Enter a valid filter value.",
11
11
  filterEquals: "is", filterContains: "contains", filterStartsWith: "starts with", filterEndsWith: "ends with", filterLessThan: "is less than", filterAtMost: "is at most", filterGreaterThan: "is greater than", filterAtLeast: "is at least", filterBetween: "is between", filterIsEmpty: "is empty", filterIsAnyOf: "is any of",
package/src/selection.ts CHANGED
@@ -42,6 +42,14 @@ export function createTableSelection(initialFilter: FilterNode, columns: readonl
42
42
  },
43
43
  selectAllMatching() { explicit = new Set(); excluded = new Set(); inverted = true; },
44
44
  isSelected(id: string) { return inverted ? loaded.has(id) && !excluded.has(id) : explicit.has(id); },
45
+ isLoaded(id: string) { return loaded.has(id); },
46
+ /** Counts selected loaded rows from the smaller explicit/excluded set instead of walking every loaded row. */
47
+ loadedSelectedCount() {
48
+ const marked = inverted ? excluded : explicit;
49
+ let count = 0;
50
+ for (const id of marked) if (loaded.has(id)) count++;
51
+ return inverted ? loaded.size - count : count;
52
+ },
45
53
  getPayload(): BulkSelection {
46
54
  return inverted
47
55
  ? Object.freeze({ kind: "query", filter, excluded: Object.freeze([...excluded]) })