@dxos/react-ui-table 0.10.0 → 0.11.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 (110) hide show
  1. package/dist/lib/chunk-types.mjs +65 -0
  2. package/dist/lib/chunk-types.mjs.map +1 -0
  3. package/dist/lib/chunk-useTableModel.mjs +1595 -0
  4. package/dist/lib/chunk-useTableModel.mjs.map +1 -0
  5. package/dist/lib/index.mjs +1133 -0
  6. package/dist/lib/index.mjs.map +1 -0
  7. package/dist/lib/testing.mjs +88 -0
  8. package/dist/lib/testing.mjs.map +1 -0
  9. package/dist/lib/translations.mjs +30 -0
  10. package/dist/lib/translations.mjs.map +1 -0
  11. package/dist/lib/types.mjs +2 -0
  12. package/dist/types/src/components/Table/DynamicTable.d.ts +4 -1
  13. package/dist/types/src/components/Table/DynamicTable.d.ts.map +1 -1
  14. package/dist/types/src/components/Table/DynamicTable.stories.d.ts +3 -1
  15. package/dist/types/src/components/Table/DynamicTable.stories.d.ts.map +1 -1
  16. package/dist/types/src/components/Table/Relations.stories.d.ts +1 -0
  17. package/dist/types/src/components/Table/Relations.stories.d.ts.map +1 -1
  18. package/dist/types/src/components/Table/Table.d.ts +3 -9
  19. package/dist/types/src/components/Table/Table.d.ts.map +1 -1
  20. package/dist/types/src/components/Table/Table.stories.d.ts +2 -0
  21. package/dist/types/src/components/Table/Table.stories.d.ts.map +1 -1
  22. package/dist/types/src/components/Table/TableContent.d.ts +1 -1
  23. package/dist/types/src/components/Table/TableContent.d.ts.map +1 -1
  24. package/dist/types/src/components/Table/TableContext.d.ts +10 -0
  25. package/dist/types/src/components/Table/TableContext.d.ts.map +1 -0
  26. package/dist/types/src/components/Table/TableToolbar.d.ts +1 -1
  27. package/dist/types/src/components/Table/TableToolbar.d.ts.map +1 -1
  28. package/dist/types/src/components/Table/index.d.ts +1 -0
  29. package/dist/types/src/components/Table/index.d.ts.map +1 -1
  30. package/dist/types/src/components/TableCellEditor/TableCellEditor.d.ts.map +1 -1
  31. package/dist/types/src/components/TableCellEditor/TableCellEditor.stories.d.ts.map +1 -1
  32. package/dist/types/src/components/testing.d.ts +1 -1
  33. package/dist/types/src/components/testing.d.ts.map +1 -1
  34. package/dist/types/src/hooks/useProjectionModel.d.ts +1 -1
  35. package/dist/types/src/hooks/useProjectionModel.d.ts.map +1 -1
  36. package/dist/types/src/hooks/useTableModel.d.ts +8 -1
  37. package/dist/types/src/hooks/useTableModel.d.ts.map +1 -1
  38. package/dist/types/src/model/modal-controller.d.ts +1 -1
  39. package/dist/types/src/model/modal-controller.d.ts.map +1 -1
  40. package/dist/types/src/model/selection-model.d.ts +1 -1
  41. package/dist/types/src/model/selection-model.d.ts.map +1 -1
  42. package/dist/types/src/model/table-model.d.ts +42 -7
  43. package/dist/types/src/model/table-model.d.ts.map +1 -1
  44. package/dist/types/src/model/table-presentation.d.ts +20 -5
  45. package/dist/types/src/model/table-presentation.d.ts.map +1 -1
  46. package/dist/types/src/model/table-view-state.d.ts +5 -1
  47. package/dist/types/src/model/table-view-state.d.ts.map +1 -1
  48. package/dist/types/src/types/index.d.ts.map +1 -1
  49. package/dist/types/src/util/dynamic-table.d.ts +1 -1
  50. package/dist/types/src/util/dynamic-table.d.ts.map +1 -1
  51. package/dist/types/src/util/table-controls.d.ts +5 -3
  52. package/dist/types/src/util/table-controls.d.ts.map +1 -1
  53. package/dist/types/tsconfig.tsbuildinfo +1 -1
  54. package/package.json +48 -50
  55. package/src/components/Table/DynamicTable.stories.tsx +59 -1
  56. package/src/components/Table/DynamicTable.tsx +16 -8
  57. package/src/components/Table/Relations.stories.tsx +2 -2
  58. package/src/components/Table/Table.stories.tsx +76 -2
  59. package/src/components/Table/Table.tsx +3 -15
  60. package/src/components/Table/TableContent.tsx +6 -5
  61. package/src/components/Table/TableContext.ts +21 -0
  62. package/src/components/Table/index.ts +2 -0
  63. package/src/components/TableCellEditor/TableCellEditor.stories.tsx +2 -3
  64. package/src/components/TableCellEditor/TableCellEditor.tsx +27 -22
  65. package/src/components/testing.ts +1 -1
  66. package/src/hooks/useProjectionModel.ts +1 -1
  67. package/src/hooks/useTableModel.ts +18 -6
  68. package/src/model/modal-controller.ts +1 -1
  69. package/src/model/selection-model.ts +1 -1
  70. package/src/model/table-model.test.ts +3 -3
  71. package/src/model/table-model.ts +148 -31
  72. package/src/model/table-presentation.test.ts +59 -1
  73. package/src/model/table-presentation.ts +171 -81
  74. package/src/model/table-view-state.ts +2 -2
  75. package/src/testing/useTestTableModel.ts +1 -1
  76. package/src/types/index.ts +4 -0
  77. package/src/util/dynamic-table.test.ts +1 -1
  78. package/src/util/dynamic-table.ts +1 -1
  79. package/src/util/table-buttons.ts +1 -1
  80. package/src/util/table-controls.ts +18 -10
  81. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  82. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  83. package/dist/lib/browser/chunk-K4J2CKTZ.mjs +0 -1751
  84. package/dist/lib/browser/chunk-K4J2CKTZ.mjs.map +0 -7
  85. package/dist/lib/browser/chunk-VV3P3ADH.mjs +0 -67
  86. package/dist/lib/browser/chunk-VV3P3ADH.mjs.map +0 -7
  87. package/dist/lib/browser/index.mjs +0 -1416
  88. package/dist/lib/browser/index.mjs.map +0 -7
  89. package/dist/lib/browser/meta.json +0 -1
  90. package/dist/lib/browser/testing/index.mjs +0 -115
  91. package/dist/lib/browser/testing/index.mjs.map +0 -7
  92. package/dist/lib/browser/translations.mjs +0 -39
  93. package/dist/lib/browser/translations.mjs.map +0 -7
  94. package/dist/lib/browser/types/index.mjs +0 -8
  95. package/dist/lib/browser/types/index.mjs.map +0 -7
  96. package/dist/lib/node-esm/chunk-E6V274ZW.mjs +0 -1753
  97. package/dist/lib/node-esm/chunk-E6V274ZW.mjs.map +0 -7
  98. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  99. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  100. package/dist/lib/node-esm/chunk-RPEWNOZZ.mjs +0 -68
  101. package/dist/lib/node-esm/chunk-RPEWNOZZ.mjs.map +0 -7
  102. package/dist/lib/node-esm/index.mjs +0 -1417
  103. package/dist/lib/node-esm/index.mjs.map +0 -7
  104. package/dist/lib/node-esm/meta.json +0 -1
  105. package/dist/lib/node-esm/testing/index.mjs +0 -116
  106. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  107. package/dist/lib/node-esm/translations.mjs +0 -40
  108. package/dist/lib/node-esm/translations.mjs.map +0 -7
  109. package/dist/lib/node-esm/types/index.mjs +0 -9
  110. package/dist/lib/node-esm/types/index.mjs.map +0 -7
@@ -1,1753 +0,0 @@
1
- import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
-
3
- // src/util/query-ast.ts
4
- var extractOrder = (queryAst) => {
5
- if (queryAst.type === "order") {
6
- return queryAst.order;
7
- }
8
- if (queryAst.type === "options") {
9
- return extractOrder(queryAst.query);
10
- }
11
- if (queryAst.type === "from") {
12
- return extractOrder(queryAst.query);
13
- }
14
- return void 0;
15
- };
16
-
17
- // src/util/sort.ts
18
- import { Format } from "@dxos/echo";
19
- var getSortValue = (value, format) => {
20
- if (value === void 0 || value === null) {
21
- return null;
22
- }
23
- const isDateFormat = format === Format.TypeFormat.DateTime || format === Format.TypeFormat.Date;
24
- if (isDateFormat) {
25
- const date = new Date(value);
26
- if (!isNaN(date.getTime())) {
27
- return date.getTime();
28
- }
29
- return String(value);
30
- }
31
- if (format === Format.TypeFormat.Number || format === Format.TypeFormat.Integer || format === Format.TypeFormat.Currency || format === Format.TypeFormat.Percent || format === Format.TypeFormat.Duration) {
32
- const num = typeof value === "number" ? value : Number(value);
33
- if (!isNaN(num)) {
34
- return num;
35
- }
36
- return String(value);
37
- }
38
- if (typeof value === "string") {
39
- return value;
40
- }
41
- if (typeof value === "number") {
42
- return value;
43
- }
44
- return String(value);
45
- };
46
- var compareValues = (aValue, bValue, format, direction) => {
47
- if (aValue === void 0 || aValue === null) {
48
- return bValue === void 0 || bValue === null ? 0 : 1;
49
- }
50
- if (bValue === void 0 || bValue === null) {
51
- return -1;
52
- }
53
- const aSortValue = getSortValue(aValue, format);
54
- const bSortValue = getSortValue(bValue, format);
55
- let comparison = 0;
56
- if (typeof aSortValue === "number" && typeof bSortValue === "number") {
57
- comparison = aSortValue - bSortValue;
58
- } else if (typeof aSortValue === "string" && typeof bSortValue === "string") {
59
- comparison = aSortValue.localeCompare(bSortValue);
60
- } else {
61
- comparison = String(aSortValue).localeCompare(String(bSortValue));
62
- }
63
- return direction === "desc" ? -comparison : comparison;
64
- };
65
-
66
- // src/util/table-buttons.ts
67
- var BUTTON_IDENTIFIERS = {
68
- columnSettings: "data-table-column-settings-button",
69
- newColumn: "data-table-new-column-button",
70
- referencedCell: "data-table-ref-cell-button",
71
- rowMenu: "data-table-row-menu-button",
72
- saveDraftRow: "data-table-save-draft-row-button",
73
- sort: "data-table-sort-button"
74
- };
75
- var createButton = ({ attr, data, disabled = false, icon, testId, type: _type = "primary" }) => {
76
- const dataAttrs = Object.entries(data).map(([k, v]) => `${k}="${v}"`).join(" ");
77
- return `<button ${attr} data-testid="${testId}" class="dx-button w-6 aspect-square px-0.5 min-h-0" ${dataAttrs} ${disabled ? "disabled" : ""} data-dx-grid-action="accessory"><svg data-size="4"><use href="/icons.svg#${icon}"/></svg></button>`;
78
- };
79
- var addColumnButton = {
80
- attr: BUTTON_IDENTIFIERS.newColumn,
81
- icon: "ph--plus--regular",
82
- render: ({ disabled }) => {
83
- return createButton({
84
- attr: BUTTON_IDENTIFIERS.newColumn,
85
- icon: addColumnButton.icon,
86
- disabled,
87
- data: {},
88
- testId: "table-new-column-button"
89
- });
90
- },
91
- getData: (_el) => ({
92
- type: "newColumn"
93
- })
94
- };
95
- var columnSettingsButton = {
96
- attr: BUTTON_IDENTIFIERS.columnSettings,
97
- icon: "ph--caret-down--regular",
98
- render: ({ fieldId }) => {
99
- return createButton({
100
- attr: BUTTON_IDENTIFIERS.columnSettings,
101
- icon: columnSettingsButton.icon,
102
- data: {
103
- "data-field-id": fieldId,
104
- "data-variant": "ghost"
105
- },
106
- testId: "table-column-settings-button"
107
- });
108
- },
109
- getData: (el) => ({
110
- type: "columnSettings",
111
- fieldId: el.getAttribute("data-field-id")
112
- })
113
- };
114
- var rowMenuButton = {
115
- attr: BUTTON_IDENTIFIERS.rowMenu,
116
- icon: "ph--dots-three--regular",
117
- render: ({ rowIndex }) => {
118
- return createButton({
119
- attr: BUTTON_IDENTIFIERS.rowMenu,
120
- icon: rowMenuButton.icon,
121
- data: {
122
- "data-row-index": rowIndex.toString()
123
- },
124
- testId: "table-row-menu-button"
125
- });
126
- },
127
- getData: (el) => ({
128
- type: "rowMenu",
129
- rowIndex: Number(el.getAttribute("data-row-index"))
130
- })
131
- };
132
- var sortButton = {
133
- attr: BUTTON_IDENTIFIERS.sort,
134
- icon: "ph--sort-ascending--regular",
135
- render: ({ fieldId, direction }) => {
136
- return createButton({
137
- attr: BUTTON_IDENTIFIERS.sort,
138
- icon: direction === "desc" ? "ph--sort-descending--regular" : "ph--sort-ascending--regular",
139
- data: {
140
- "data-field-id": fieldId,
141
- "data-direction": direction ?? ""
142
- },
143
- testId: "table-sort-button",
144
- // TODO(ZaymonFC): All buttons should be rendered into an absolutely positioned flex container.
145
- // This is a bit hacky.
146
- type: "secondary"
147
- });
148
- },
149
- getData: (el) => ({
150
- type: "sort",
151
- fieldId: el.getAttribute("data-field-id"),
152
- direction: el.getAttribute("data-direction")
153
- })
154
- };
155
- var saveDraftRowButton = {
156
- attr: BUTTON_IDENTIFIERS.saveDraftRow,
157
- icon: "ph--floppy-disk--regular",
158
- render: ({ rowIndex, disabled }) => {
159
- return createButton({
160
- attr: BUTTON_IDENTIFIERS.saveDraftRow,
161
- icon: saveDraftRowButton.icon,
162
- disabled,
163
- data: {
164
- "data-row-index": rowIndex.toString(),
165
- "data-variant": "primary"
166
- },
167
- testId: "table-save-draft-row-button"
168
- });
169
- },
170
- getData: (el) => ({
171
- type: "saveDraftRow",
172
- rowIndex: Number(el.getAttribute("data-row-index"))
173
- })
174
- };
175
- var tableButtons = {
176
- addColumn: addColumnButton,
177
- columnSettings: columnSettingsButton,
178
- rowMenu: rowMenuButton,
179
- saveDraftRow: saveDraftRowButton,
180
- sort: sortButton
181
- };
182
-
183
- // src/util/table-controls.ts
184
- import { accessoryHandlesPointerdownAttrs } from "@dxos/lit-grid";
185
- var CONTROL_IDENTIFIERS = {
186
- checkbox: "data-table-checkbox",
187
- switch: "data-table-switch"
188
- };
189
- var BASE_CLASSES = {
190
- checkbox: "absolute inset-y-[.375rem] end-[.375rem] dx-checkbox",
191
- switch: "absolute inset-y-[.25rem] end-[.25rem] dx-checkbox--switch"
192
- };
193
- var renderAttributes = (data) => {
194
- return Object.entries(data).map(([k, v]) => `${k}="${v}"`).join(" ");
195
- };
196
- var renderInput = (baseClass, attrs, checked = false, disabled = false, preventToggle = false, testId) => {
197
- return `<input type="checkbox" class="${baseClass}" ${renderAttributes(attrs)} ${checked ? "checked" : ""} ${preventToggle ? 'onclick="return false"' : ""} ${disabled ? "disabled" : ""} data-testid="${testId}" data-dx-grid-action="accessory"/>`;
198
- };
199
- var CheckboxStory = ({ rowIndex, header = false, checked = false, disabled = false }) => {
200
- const attrs = {
201
- [CONTROL_IDENTIFIERS.checkbox]: "",
202
- "data-row-index": rowIndex.toString(),
203
- ...header && {
204
- "data-header": ""
205
- }
206
- };
207
- return renderInput(BASE_CLASSES.checkbox, attrs, checked, disabled, true, "table-selection");
208
- };
209
- var SwitchStory = ({ colIndex, rowIndex, checked = false, disabled = false }) => {
210
- const attrs = {
211
- [CONTROL_IDENTIFIERS.switch]: "",
212
- "data-row-index": rowIndex.toString(),
213
- "data-col-index": colIndex.toString(),
214
- ...accessoryHandlesPointerdownAttrs
215
- };
216
- return renderInput(BASE_CLASSES.switch, attrs, checked, disabled, true, "table-switch");
217
- };
218
- var tableControls = {
219
- checkbox: {
220
- attr: CONTROL_IDENTIFIERS.checkbox,
221
- render: CheckboxStory,
222
- getData: (el) => ({
223
- type: "checkbox",
224
- rowIndex: Number(el.getAttribute("data-row-index")),
225
- header: el.hasAttribute("data-header")
226
- })
227
- },
228
- switch: {
229
- attr: CONTROL_IDENTIFIERS.switch,
230
- render: SwitchStory,
231
- getData: (el) => ({
232
- type: "switch",
233
- rowIndex: Number(el.getAttribute("data-row-index")),
234
- colIndex: Number(el.getAttribute("data-col-index"))
235
- })
236
- }
237
- };
238
-
239
- // src/model/table-view-state.ts
240
- import * as Schema from "effect/Schema";
241
- import { QueryAST } from "@dxos/echo";
242
- import { defineViewState } from "@dxos/react-ui-attention";
243
- var FieldSortSchema = Schema.Struct({
244
- fieldId: Schema.String,
245
- direction: QueryAST.OrderDirection
246
- });
247
- var tableSortAspect = defineViewState({
248
- key: "table-sort",
249
- backend: "local",
250
- schema: Schema.UndefinedOr(FieldSortSchema),
251
- defaultValue: () => void 0
252
- });
253
-
254
- // src/model/table-model.ts
255
- import { Atom as Atom2 } from "@effect-atom/atom-react";
256
- import { Resource as Resource2 } from "@dxos/context";
257
- import { Format as Format2, Obj, Order, Query, Ref, Type } from "@dxos/echo";
258
- import { toEffectSchema } from "@dxos/echo/JsonSchema";
259
- import { getSnapshot } from "@dxos/echo/Obj";
260
- import { SchemaEx } from "@dxos/effect";
261
- import { invariant } from "@dxos/invariant";
262
- import { EntityId } from "@dxos/keys";
263
- import { formatForEditing, parseValue } from "@dxos/react-ui-form";
264
- import { validateSchema } from "@dxos/schema";
265
-
266
- // src/util/tag.ts
267
- var TAG_PATTERN_REGEX = /\[([^\]]+)\]\(([^)]+)\)/g;
268
- var extractTagIds = (value) => {
269
- if (typeof value !== "string") {
270
- return void 0;
271
- }
272
- const ids = [];
273
- let match;
274
- while ((match = TAG_PATTERN_REGEX.exec(value)) !== null) {
275
- if (match[2]) {
276
- ids.push(match[2]);
277
- }
278
- }
279
- return ids.length > 0 ? ids : void 0;
280
- };
281
-
282
- // src/model/selection-model.ts
283
- import { Atom } from "@effect-atom/atom-react";
284
- import { Resource } from "@dxos/context";
285
- var SelectionModel = class extends Resource {
286
- _registry;
287
- _rows;
288
- _selection;
289
- _validSelectedIds;
290
- _hasSelection;
291
- _allSelected;
292
- _selectionMode;
293
- _onSelectionChanged;
294
- constructor(registry, rows, selectionMode, initialSelection, onSelectionChanged) {
295
- super();
296
- this._registry = registry;
297
- this._rows = rows;
298
- this._selectionMode = selectionMode;
299
- this._onSelectionChanged = onSelectionChanged;
300
- this._selection = Atom.make(new Set(initialSelection));
301
- this._validSelectedIds = Atom.make((get) => {
302
- const rows2 = get(this._rows);
303
- if (!rows2) {
304
- return /* @__PURE__ */ new Set();
305
- }
306
- const validIds = new Set(rows2.map((row) => row.id));
307
- const selection = get(this._selection);
308
- return new Set([
309
- ...selection
310
- ].filter((id) => validIds.has(id)));
311
- });
312
- this._hasSelection = Atom.make((get) => get(this._validSelectedIds).size > 0);
313
- this._allSelected = Atom.make((get) => {
314
- const rows2 = get(this._rows);
315
- if (rows2.length === 0) {
316
- return false;
317
- }
318
- const selection = get(this._selection);
319
- return rows2.every((row) => selection.has(row.id));
320
- });
321
- }
322
- async _open() {
323
- const selectionUnsubscribe = this._registry.subscribe(this._selection, () => {
324
- this._onSelectionChanged?.();
325
- });
326
- this._ctx.onDispose(selectionUnsubscribe);
327
- }
328
- //
329
- // Getters
330
- //
331
- /** Get the selection atom for reactive access. */
332
- get selectionAtom() {
333
- return this._selection;
334
- }
335
- /** Get the current selection value. */
336
- get selection() {
337
- return this._registry.get(this._selection);
338
- }
339
- /** Get the hasSelection atom for reactive access. */
340
- get hasSelectionAtom() {
341
- return this._hasSelection;
342
- }
343
- /** Check if there is any selection. */
344
- get hasSelection() {
345
- return this._registry.get(this._hasSelection);
346
- }
347
- /** Get the allRowsSelected atom for reactive access. */
348
- get allRowsSelectedAtom() {
349
- return this._allSelected;
350
- }
351
- /** Check if all rows are selected. */
352
- get allRowsSelected() {
353
- return this._registry.get(this._allSelected);
354
- }
355
- get selectionMode() {
356
- return this._selectionMode;
357
- }
358
- getSelectedRows = () => {
359
- const selectedIds = this._registry.get(this._validSelectedIds);
360
- return this._registry.get(this._rows).filter((row) => selectedIds.has(row.id));
361
- };
362
- isRowIndexSelected = (rowIndex) => {
363
- const row = this._registry.get(this._rows)[rowIndex];
364
- return this._registry.get(this._selection).has(row.id);
365
- };
366
- isObjectSelected = (object) => {
367
- return this._registry.get(this._selection).has(object.id);
368
- };
369
- //
370
- // Manipulation
371
- //
372
- toggleSelectionForRowIndex = (rowIndex) => {
373
- const row = this._registry.get(this._rows)[rowIndex];
374
- const currentSelection = this._registry.get(this._selection);
375
- const newSelection = new Set(currentSelection);
376
- if (newSelection.has(row.id)) {
377
- newSelection.delete(row.id);
378
- } else {
379
- if (this._selectionMode === "single") {
380
- newSelection.clear();
381
- }
382
- newSelection.add(row.id);
383
- }
384
- this._registry.set(this._selection, newSelection);
385
- };
386
- setSelection = (mode) => {
387
- switch (mode) {
388
- case "all": {
389
- this._registry.set(this._selection, new Set(this._registry.get(this._rows).map((row) => row.id)));
390
- break;
391
- }
392
- case "none": {
393
- this._registry.set(this._selection, /* @__PURE__ */ new Set());
394
- break;
395
- }
396
- }
397
- };
398
- };
399
-
400
- // src/model/table-model.ts
401
- var __dxlog_file = "/__w/dxos/dxos/packages/ui/react-ui-table/src/model/table-model.ts";
402
- var createEchoChangeCallback = (table) => ({
403
- table: (mutate) => Obj.update(table, (table2) => mutate(table2)),
404
- row: (row, mutate) => {
405
- if (Obj.isObject(row)) {
406
- Obj.update(row, (row2) => mutate(row2));
407
- } else {
408
- mutate(row);
409
- }
410
- }
411
- });
412
- var createDirectChangeCallback = (table) => ({
413
- table: (mutate) => mutate(table),
414
- row: (row, mutate) => mutate(row)
415
- });
416
- var defaultFeatures = {
417
- selection: {
418
- enabled: true,
419
- mode: "multiple"
420
- },
421
- dataEditable: false,
422
- schemaEditable: false
423
- };
424
- var TableModel = class extends Resource2 {
425
- _registry;
426
- _object;
427
- _projection;
428
- _db;
429
- _change;
430
- _visibleRange;
431
- _onInsertRow;
432
- _onDeleteRows;
433
- _onColumnDelete;
434
- _onCellUpdate;
435
- _onRowOrderChange;
436
- _onRowAction;
437
- _rowActions;
438
- _features;
439
- _rows;
440
- _draftRows;
441
- // Optional per-context UI state manager; when present the column sort is view-state-backed.
442
- _viewState;
443
- // Per-user sort state - backed by the `tableSortAspect` view state (keyed by table URI) when a
444
- // ViewStateManager is provided, else an ephemeral atom. Changes are local until saved to the view.
445
- _inMemorySort;
446
- // Derived atom for persisted sort from view.query.ast.
447
- _persistedSort;
448
- // Derived atom for current sort (in-memory takes precedence over persisted).
449
- _sorting;
450
- // Derived atom for sorted rows (used by rows getter and SelectionModel).
451
- _sortedRows;
452
- // Derived atom for viewDirty state.
453
- _viewDirty;
454
- _pinnedRows;
455
- _selection;
456
- _columnMeta;
457
- // Counter atom that increments when cells are updated - allows UI to react to cell changes.
458
- _cellUpdateCounter;
459
- constructor({ registry, object, projection, db, viewState, change, features = {}, initialSelection = [], pinnedRows = {
460
- top: [],
461
- bottom: []
462
- }, rowActions = [], onCellUpdate, onColumnDelete, onDeleteRows, onInsertRow, onRowOrderChange, onRowAction }) {
463
- super();
464
- this._registry = registry;
465
- this._object = object;
466
- this._viewState = viewState;
467
- this._projection = projection;
468
- this._projection.normalizeView();
469
- this._db = db;
470
- this._change = change ?? createEchoChangeCallback(object);
471
- this._features = {
472
- ...defaultFeatures,
473
- ...features
474
- };
475
- invariant(!(this._features.dataEditable && this._features.selection.enabled && this._features.selection.mode === "single"), "Single selection is not compatible with editable tables.", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 99, S: this, A: ["!(this._features.dataEditable && this._features.selection.enabled && this._features.selection.mode === 'single')", "'Single selection is not compatible with editable tables.'"] });
476
- this._visibleRange = Atom2.make({
477
- start: {
478
- row: 0,
479
- col: 0
480
- },
481
- end: {
482
- row: 0,
483
- col: 0
484
- }
485
- });
486
- this._rows = Atom2.make([]);
487
- this._draftRows = Atom2.make([]);
488
- this._inMemorySort = this._viewState ? this._viewState.atom(tableSortAspect, this.id) : Atom2.make(void 0);
489
- this._cellUpdateCounter = Atom2.make(0);
490
- this._persistedSort = Atom2.make((get) => {
491
- const view = get(this._object.view.atom);
492
- if (!view) {
493
- return void 0;
494
- }
495
- const viewSnapshot = Obj.getSnapshot(view);
496
- const ast = viewSnapshot.query.ast;
497
- const orders = extractOrder(ast);
498
- if (orders && orders.length > 0) {
499
- const firstOrder = orders[0];
500
- if (firstOrder.kind === "property") {
501
- const field = this._projection.getFields().find((f) => f.path === firstOrder.property);
502
- if (field) {
503
- return {
504
- fieldId: field.id,
505
- direction: firstOrder.direction
506
- };
507
- }
508
- }
509
- }
510
- return void 0;
511
- });
512
- this._sorting = Atom2.make((get) => {
513
- const inMemorySort = get(this._inMemorySort);
514
- return inMemorySort ?? get(this._persistedSort);
515
- });
516
- this._sortedRows = Atom2.make((get) => {
517
- const rows = get(this._rows);
518
- const sort = get(this._sorting);
519
- if (!sort || rows.length === 0) {
520
- return rows;
521
- }
522
- const field = this._projection.getFields().find((f) => f.id === sort.fieldId);
523
- if (!field) {
524
- return rows;
525
- }
526
- const fieldProjection = this._projection.getFieldProjection(field.id);
527
- const sorted = [
528
- ...rows
529
- ].sort((a, b) => {
530
- const aValue = SchemaEx.getValue(a, field.path);
531
- const bValue = SchemaEx.getValue(b, field.path);
532
- return compareValues(aValue, bValue, fieldProjection.props.format, sort.direction);
533
- });
534
- return sorted;
535
- });
536
- this._selection = new SelectionModel(this._registry, this._sortedRows, this._features.selection.mode ?? "multiple", initialSelection, () => this._onRowOrderChange?.());
537
- this._viewDirty = Atom2.make((get) => {
538
- const inMemorySort = get(this._inMemorySort);
539
- if (!inMemorySort) {
540
- return false;
541
- }
542
- const persisted = get(this._persistedSort);
543
- if (!persisted) {
544
- return true;
545
- }
546
- return inMemorySort.fieldId !== persisted.fieldId || inMemorySort.direction !== persisted.direction;
547
- });
548
- this._pinnedRows = pinnedRows;
549
- this._rowActions = rowActions;
550
- this._onInsertRow = onInsertRow;
551
- this._onDeleteRows = onDeleteRows;
552
- this._onColumnDelete = onColumnDelete;
553
- this._onCellUpdate = onCellUpdate;
554
- this._onRowOrderChange = onRowOrderChange;
555
- this._onRowAction = onRowAction;
556
- }
557
- get id() {
558
- return Obj.getURI(this._object);
559
- }
560
- get view() {
561
- const view = this._object.view.target;
562
- invariant(view, "Table model not initialized", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 197, S: this, A: ["view", "'Table model not initialized'"] });
563
- return view;
564
- }
565
- get table() {
566
- return this._object;
567
- }
568
- get projection() {
569
- return this._projection;
570
- }
571
- get db() {
572
- return this._db;
573
- }
574
- /**
575
- * Atom for reactive access to rows with in-memory sorting applied.
576
- */
577
- get rows() {
578
- return this._sortedRows;
579
- }
580
- /**
581
- * Gets rows with in-memory sorting applied.
582
- * In-memory sort is local to this instance until saved.
583
- */
584
- getRows() {
585
- return this._registry.get(this._sortedRows);
586
- }
587
- /** Atom for reactive access to cell changes. */
588
- get cellUpdate() {
589
- return this._cellUpdateCounter;
590
- }
591
- /**
592
- * Change a row using the configured change callback.
593
- * Use this instead of directly mutating to ensure consistent mutation handling.
594
- */
595
- changeRow(row, mutate) {
596
- this._change.row(row, mutate);
597
- }
598
- get features() {
599
- return this._features;
600
- }
601
- /**
602
- * Gets the current sort state.
603
- * Priority: in-memory sort (local changes) > persisted sort (from query AST).
604
- */
605
- getSorting() {
606
- return this._registry.get(this._sorting);
607
- }
608
- /**
609
- * Gets the row data at the specified display index.
610
- */
611
- getRowAt(displayIndex) {
612
- const sortedRows = this._registry.get(this._sortedRows);
613
- if (displayIndex < 0 || displayIndex >= sortedRows.length) {
614
- return void 0;
615
- }
616
- return sortedRows[displayIndex];
617
- }
618
- get pinnedRows() {
619
- return this._pinnedRows;
620
- }
621
- get columnMeta() {
622
- invariant(this._columnMeta, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 251, S: this, A: ["this._columnMeta", ""] });
623
- return this._columnMeta;
624
- }
625
- get selection() {
626
- return this._selection;
627
- }
628
- get rowActions() {
629
- return this._rowActions;
630
- }
631
- //
632
- // Initialisation
633
- //
634
- async _open() {
635
- await this._object.view.load();
636
- this.initializeColumnMeta();
637
- this.initializeEffects();
638
- await this._selection.open(this._ctx);
639
- }
640
- initializeColumnMeta() {
641
- invariant(this._object.view.target, "View must be loaded before initializing column meta", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 270, S: this, A: ["this._object.view.target", "'View must be loaded before initializing column meta'"] });
642
- this._columnMeta = Atom2.make((get) => {
643
- const fields = get(this._projection.fields);
644
- const meta = Object.fromEntries(fields.map((field, index) => [
645
- index,
646
- {
647
- size: this.table.sizes[field.path] ?? 256,
648
- resizeable: true
649
- }
650
- ]));
651
- return {
652
- grid: meta,
653
- frozenColsStart: {
654
- 0: {
655
- size: 30,
656
- resizeable: false
657
- }
658
- },
659
- frozenColsEnd: {
660
- 0: {
661
- size: 32,
662
- resizeable: false
663
- }
664
- }
665
- };
666
- });
667
- }
668
- initializeEffects() {
669
- const rowsUnsubscribe = this._registry.subscribe(this._rows, () => {
670
- this._onRowOrderChange?.();
671
- });
672
- this._ctx.onDispose(rowsUnsubscribe);
673
- const rowSubscriptions = /* @__PURE__ */ new Map();
674
- const visibleRangeUnsubscribe = this._registry.subscribe(this._visibleRange, () => {
675
- for (const [id, unsub] of rowSubscriptions) {
676
- unsub();
677
- rowSubscriptions.delete(id);
678
- }
679
- const { start, end } = this._registry.get(this._visibleRange);
680
- const sortedRows = this._registry.get(this._sortedRows);
681
- for (let row = start.row; row <= end.row && row < sortedRows.length; row++) {
682
- const obj = sortedRows[row];
683
- if (Obj.isObject(obj) && !rowSubscriptions.has(obj.id)) {
684
- const unsub = Obj.subscribe(obj, () => {
685
- this._registry.set(this._cellUpdateCounter, this._registry.get(this._cellUpdateCounter) + 1);
686
- this._onCellUpdate?.({
687
- row,
688
- col: start.col,
689
- plane: "grid"
690
- });
691
- });
692
- rowSubscriptions.set(obj.id, unsub);
693
- }
694
- }
695
- });
696
- this._ctx.onDispose(() => {
697
- visibleRangeUnsubscribe();
698
- for (const unsub of rowSubscriptions.values()) {
699
- unsub();
700
- }
701
- });
702
- const draftRowsUnsubscribe = this._registry.subscribe(this._draftRows, () => {
703
- this._onRowOrderChange?.();
704
- });
705
- this._ctx.onDispose(draftRowsUnsubscribe);
706
- }
707
- //
708
- // Data
709
- //
710
- setRows = (obj) => {
711
- this._registry.set(this._rows, obj);
712
- };
713
- getRowCount = () => this._registry.get(this._sortedRows).length;
714
- getDraftRowCount() {
715
- return this._registry.get(this._draftRows).length;
716
- }
717
- /** Atom for reactive access to draft rows. */
718
- get draftRows() {
719
- return this._draftRows;
720
- }
721
- /** Gets the current draft rows. */
722
- getDraftRows() {
723
- return this._registry.get(this._draftRows);
724
- }
725
- /**
726
- * Checks if a specific field path has validation errors for a given draft row.
727
- * @param draftRowIndex - The index of the draft row to check
728
- * @param fieldPath - The path of the field to check for validation errors
729
- * @returns true if the field has validation errors, false otherwise
730
- */
731
- hasDraftRowValidationError(draftRowIndex, fieldPath) {
732
- if (draftRowIndex < 0 || draftRowIndex >= this._registry.get(this._draftRows).length) {
733
- return false;
734
- }
735
- const draftRow = this._registry.get(this._draftRows)[draftRowIndex];
736
- const validationErrors = draftRow.validationErrors || [];
737
- return validationErrors.some((error) => error.path === fieldPath);
738
- }
739
- getColumnCount = () => this._projection?.getFields().length ?? 0;
740
- insertRow = () => {
741
- const result = this._onInsertRow?.();
742
- if (result === "draft" && this._registry.get(this._draftRows).length === 0) {
743
- this.createDraftRow();
744
- }
745
- return result ?? "final";
746
- };
747
- createDraftRow() {
748
- if (!this._projection) {
749
- return;
750
- }
751
- const draftData = {
752
- id: EntityId.random()
753
- };
754
- const validationErrors = this.validateDraftRowData(draftData);
755
- const draftRow = {
756
- data: draftData,
757
- valid: validationErrors.length === 0,
758
- validationErrors
759
- };
760
- this._registry.set(this._draftRows, [
761
- ...this._registry.get(this._draftRows),
762
- draftRow
763
- ]);
764
- }
765
- validateDraftRow(draftRowIndex) {
766
- if (draftRowIndex < 0 || draftRowIndex >= this._registry.get(this._draftRows).length) {
767
- return;
768
- }
769
- const draftRow = this._registry.get(this._draftRows)[draftRowIndex];
770
- const validationErrors = this.validateDraftRowData(draftRow.data);
771
- const updatedDraftRow = {
772
- ...draftRow,
773
- valid: validationErrors.length === 0,
774
- validationErrors
775
- };
776
- const newDraftRows = [
777
- ...this._registry.get(this._draftRows)
778
- ];
779
- newDraftRows[draftRowIndex] = updatedDraftRow;
780
- this._registry.set(this._draftRows, newDraftRows);
781
- }
782
- validateDraftRowData(data) {
783
- const schema = toEffectSchema(this._projection.baseSchema);
784
- return validateSchema(schema, data) || [];
785
- }
786
- commitDraftRow = (draftRowIndex) => {
787
- if (draftRowIndex < 0 || draftRowIndex >= this._registry.get(this._draftRows).length) {
788
- return false;
789
- }
790
- const draftRow = this._registry.get(this._draftRows)[draftRowIndex];
791
- if (!draftRow.valid) {
792
- return false;
793
- }
794
- const insertRowResult = this._onInsertRow?.(draftRow.data);
795
- if (insertRowResult === "final") {
796
- const newDraftRows = this._registry.get(this._draftRows).filter((_, index) => index !== draftRowIndex);
797
- this._registry.set(this._draftRows, newDraftRows);
798
- }
799
- return insertRowResult === "final";
800
- };
801
- deleteRow = (rowIndex) => {
802
- const sortedRows = this._registry.get(this._sortedRows);
803
- const obj = sortedRows[rowIndex];
804
- const objectsToDelete = [];
805
- if (this.features.selection.enabled && this._selection.hasSelection) {
806
- const selectedRows = this._selection.getSelectedRows();
807
- objectsToDelete.push(...selectedRows);
808
- } else if (obj) {
809
- objectsToDelete.push(obj);
810
- }
811
- if (objectsToDelete.length > 0) {
812
- this._onDeleteRows?.(rowIndex, objectsToDelete);
813
- }
814
- };
815
- handleRowAction = (actionId, rowIndex) => {
816
- if (!this._onRowAction) {
817
- return;
818
- }
819
- const sortedRows = this._registry.get(this._sortedRows);
820
- const data = sortedRows[rowIndex];
821
- if (data) {
822
- this._onRowAction(actionId, data);
823
- }
824
- };
825
- getCellData = (cell) => {
826
- const { col, row, plane } = cell;
827
- const fields = this._projection?.getFields() ?? [];
828
- if (col < 0 || col >= fields.length) {
829
- return void 0;
830
- }
831
- const field = fields[col];
832
- let value;
833
- if (plane === "frozenRowsEnd") {
834
- if (row >= 0 && row < this._registry.get(this._draftRows).length) {
835
- value = SchemaEx.getValue(this._registry.get(this._draftRows)[row].data, field.path);
836
- } else {
837
- return void 0;
838
- }
839
- } else {
840
- const sortedRows = this._registry.get(this._sortedRows);
841
- value = SchemaEx.getValue(sortedRows[row], field.path);
842
- }
843
- if (value == null) {
844
- return "";
845
- }
846
- const { props } = this._projection.getFieldProjection(field.id);
847
- switch (props.format) {
848
- case Format2.TypeFormat.Ref: {
849
- if (!field.referencePath) {
850
- return "";
851
- }
852
- return SchemaEx.getValue(value.target, field.referencePath);
853
- }
854
- default: {
855
- return formatForEditing({
856
- type: props.type,
857
- format: props.format,
858
- value
859
- });
860
- }
861
- }
862
- };
863
- validateCellData = async ({ col, row, plane }, value) => {
864
- const fields = this._projection?.getFields() ?? [];
865
- if (col < 0 || col >= fields.length) {
866
- return {
867
- valid: false,
868
- error: "Invalid column index"
869
- };
870
- }
871
- const field = fields[col];
872
- const { props } = this._projection.getFieldProjection(field.id);
873
- const transformedValue = editorTextToCellValue(props, value);
874
- const isDraftRow = plane === "frozenRowsEnd";
875
- if (isDraftRow) {
876
- const isInvalidDraftRowIndex = row < 0 || row >= this._registry.get(this._draftRows).length;
877
- if (isInvalidDraftRowIndex) {
878
- return {
879
- valid: false,
880
- error: "Invalid draft row index"
881
- };
882
- }
883
- const draftRow = this._registry.get(this._draftRows)[row];
884
- const snapshot = {
885
- ...draftRow.data
886
- };
887
- SchemaEx.setValue(snapshot, field.path, transformedValue);
888
- const validationErrors = this.validateDraftRowData(snapshot);
889
- if (validationErrors.length > 0) {
890
- const error = validationErrors.find((err) => err.path === field.path);
891
- if (error) {
892
- return {
893
- valid: false,
894
- error: error.message
895
- };
896
- }
897
- }
898
- return {
899
- valid: true
900
- };
901
- } else {
902
- const currentRow = this._registry.get(this._rows)[row];
903
- invariant(currentRow, "Invalid row index", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 544, S: this, A: ["currentRow", "'Invalid row index'"] });
904
- const snapshot = {
905
- ...getSnapshot(currentRow)
906
- };
907
- SchemaEx.setValue(snapshot, field.path, transformedValue);
908
- const type = Obj.getType(currentRow);
909
- invariant(type, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 551, S: this, A: ["type", ""] });
910
- const schema = Type.getSchema(type);
911
- const validationResult = validateSchema(schema, snapshot);
912
- if (validationResult && validationResult.length > 0) {
913
- const error = validationResult.find((err) => err.path === field.path);
914
- if (error) {
915
- return {
916
- valid: false,
917
- error: error.message
918
- };
919
- }
920
- }
921
- return {
922
- valid: true
923
- };
924
- }
925
- };
926
- setCellData = (cell, value) => {
927
- const { col, row, plane } = cell;
928
- const fields = this._projection?.getFields() ?? [];
929
- if (col < 0 || col >= fields.length) {
930
- return;
931
- }
932
- const field = fields[col];
933
- const { props } = this._projection.getFieldProjection(field.id);
934
- const transformedValue = editorTextToCellValue(props, value);
935
- if (props.format === Format2.TypeFormat.Ref && !Obj.isObject(value)) {
936
- return;
937
- }
938
- if (plane === "frozenRowsEnd") {
939
- if (row >= 0 && row < this._registry.get(this._draftRows).length) {
940
- SchemaEx.setValue(this._registry.get(this._draftRows)[row].data, field.path, transformedValue);
941
- this.validateDraftRow(row);
942
- }
943
- } else {
944
- const sortedRows = this._registry.get(this._sortedRows);
945
- const rowData = sortedRows[row];
946
- this._change.row(rowData, (mutableRow) => {
947
- SchemaEx.setValue(mutableRow, field.path, transformedValue);
948
- });
949
- }
950
- };
951
- /**
952
- * Updates a cell's value using a transform function.
953
- * @param {DxGridPlanePosition} position - The position of the cell to update.
954
- * @param {(value: any) => any} update - A function that takes the current value and returns the updated value.
955
- */
956
- updateCellData({ col, row }, update) {
957
- const fields = this._projection?.getFields() ?? [];
958
- const field = fields[col];
959
- const sortedRows = this._registry.get(this._sortedRows);
960
- const rowData = sortedRows[row];
961
- const value = SchemaEx.getValue(rowData, field.path);
962
- const updatedValue = update(value);
963
- this._change.row(rowData, (mutableRow) => {
964
- SchemaEx.setValue(mutableRow, field.path, updatedValue);
965
- });
966
- }
967
- /**
968
- * Gets the domain-appropriate cell type for a given cell position.
969
- * This abstracts away the low-level grid plane concepts and provides domain-specific types.
970
- * @param cell - The cell position to classify
971
- * @returns The domain-appropriate cell type
972
- */
973
- getCellType(cell) {
974
- switch (cell.plane) {
975
- case "frozenRowsEnd":
976
- return "draft";
977
- case "frozenRowsStart":
978
- return "header";
979
- case "grid":
980
- default:
981
- return "standard";
982
- }
983
- }
984
- /**
985
- * Convenience method to check if a cell is a draft cell.
986
- * @param cell - The cell position to check
987
- * @returns true if the cell is a draft cell, false otherwise
988
- */
989
- isDraftCell(cell) {
990
- return this.getCellType(cell) === "draft";
991
- }
992
- //
993
- // Column Operations
994
- //
995
- deleteColumn(fieldId) {
996
- if (!this._projection) {
997
- return;
998
- }
999
- const field = this._projection?.getFields().find((field2) => field2.id === fieldId);
1000
- if (field && this._onColumnDelete) {
1001
- this._onColumnDelete(field.id);
1002
- }
1003
- }
1004
- //
1005
- // Resize
1006
- //
1007
- setColumnWidth(columnIndex, width) {
1008
- const fields = this._projection?.getFields() ?? [];
1009
- if (columnIndex < fields.length) {
1010
- const newWidth = Math.max(0, width);
1011
- const field = fields[columnIndex];
1012
- if (field) {
1013
- this._change.table((mutableTable) => {
1014
- mutableTable.sizes[field.path] = newWidth;
1015
- });
1016
- }
1017
- }
1018
- }
1019
- //
1020
- // Pinning
1021
- //
1022
- // TODO(burdon): Change to setPinned(on/off).
1023
- pinRow(rowIndex, side) {
1024
- this._pinnedRows[side].push(rowIndex);
1025
- }
1026
- unpinRow(rowIndex) {
1027
- this._pinnedRows.top = this._pinnedRows.top.filter((index) => index !== rowIndex);
1028
- this._pinnedRows.bottom = this._pinnedRows.bottom.filter((index) => index !== rowIndex);
1029
- }
1030
- //
1031
- // Sort operations
1032
- //
1033
- /**
1034
- * Sets the sort order for a field in-memory (local to this instance).
1035
- * Use saveView() to persist the sort to the view query.
1036
- */
1037
- setSort(fieldId, direction) {
1038
- const field = this._projection.getFields().find((f) => f.id === fieldId);
1039
- if (!field) {
1040
- return;
1041
- }
1042
- this._writeSort({
1043
- fieldId,
1044
- direction
1045
- });
1046
- }
1047
- /**
1048
- * Writes the per-user sort, routing through the ViewStateManager (so the `local` backend persists)
1049
- * when one is configured, otherwise updating the ephemeral atom directly.
1050
- */
1051
- _writeSort(value) {
1052
- if (this._viewState) {
1053
- this._viewState.set(tableSortAspect, this.id, value);
1054
- } else {
1055
- this._registry.set(this._inMemorySort, value);
1056
- }
1057
- }
1058
- /**
1059
- * Toggles the sort direction for a field in-memory.
1060
- */
1061
- toggleSort(fieldId) {
1062
- const currentSort = this.getSorting();
1063
- if (!currentSort || currentSort.fieldId !== fieldId) {
1064
- this.setSort(fieldId, "asc");
1065
- return;
1066
- }
1067
- const newDirection = currentSort.direction === "asc" ? "desc" : "asc";
1068
- this.setSort(fieldId, newDirection);
1069
- }
1070
- /**
1071
- * Clears the in-memory sort order.
1072
- */
1073
- clearSort() {
1074
- this._writeSort(void 0);
1075
- }
1076
- /**
1077
- * Saves the current in-memory sort to the view query AST.
1078
- * This persists the sort so it becomes the default for all viewers.
1079
- */
1080
- saveView() {
1081
- const view = this.view;
1082
- const inMemorySort = this._registry.get(this._inMemorySort);
1083
- const viewSnapshot = Obj.getSnapshot(view);
1084
- const currentQuery = Query.fromAst(viewSnapshot.query.ast);
1085
- const baseQuery = this._getBaseQuery(currentQuery);
1086
- if (inMemorySort) {
1087
- const field = this._projection.getFields().find((f) => f.id === inMemorySort.fieldId);
1088
- if (field) {
1089
- const newQuery = baseQuery.orderBy(Order.property(field.path, inMemorySort.direction));
1090
- Obj.update(view, (view2) => {
1091
- view2.query.ast = newQuery.ast;
1092
- });
1093
- }
1094
- } else {
1095
- Obj.update(view, (view2) => {
1096
- view2.query.ast = baseQuery.ast;
1097
- });
1098
- }
1099
- this._writeSort(void 0);
1100
- }
1101
- /**
1102
- * Extracts the base query without order clauses.
1103
- */
1104
- _getBaseQuery(query) {
1105
- const ast = query.ast;
1106
- if (ast.type === "order") {
1107
- return Query.fromAst(ast.query);
1108
- }
1109
- return query;
1110
- }
1111
- /**
1112
- * Checks if the view has unsaved changes (in-memory sort differs from persisted sort).
1113
- */
1114
- getViewDirty() {
1115
- return this._registry.get(this._viewDirty);
1116
- }
1117
- };
1118
- var editorTextToCellValue = (props, value) => {
1119
- switch (props.format) {
1120
- case Format2.TypeFormat.Ref: {
1121
- if (Obj.isObject(value)) {
1122
- return Ref.make(value);
1123
- } else {
1124
- return value;
1125
- }
1126
- }
1127
- case Format2.TypeFormat.SingleSelect: {
1128
- const ids = extractTagIds(value);
1129
- if (ids && ids.length > 0) {
1130
- return ids[0];
1131
- } else {
1132
- return value;
1133
- }
1134
- }
1135
- case Format2.TypeFormat.MultiSelect: {
1136
- const ids = extractTagIds(value);
1137
- return ids || value;
1138
- }
1139
- default: {
1140
- return parseValue({
1141
- type: props.type,
1142
- format: props.format,
1143
- value
1144
- });
1145
- }
1146
- }
1147
- };
1148
-
1149
- // src/model/table-presentation.ts
1150
- import { Atom as Atom3 } from "@effect-atom/atom-react";
1151
- import * as Predicate from "effect/Predicate";
1152
- import { Obj as Obj2 } from "@dxos/echo";
1153
- import { Format as Format3, TypeEnum } from "@dxos/echo/Format";
1154
- import { SchemaEx as SchemaEx2 } from "@dxos/effect";
1155
- import { cellClassesForFieldType, formatForDisplay } from "@dxos/react-ui-form";
1156
- import { toPlaneCellIndex } from "@dxos/react-ui-grid";
1157
- import { VIEW_FIELD_LIMIT } from "@dxos/schema";
1158
- import { mx } from "@dxos/ui-theme";
1159
- var TablePresentation = class {
1160
- model;
1161
- _registry;
1162
- _visibleRange;
1163
- fieldProjectionCache = /* @__PURE__ */ new Map();
1164
- constructor(registry, model) {
1165
- this.model = model;
1166
- this._registry = registry;
1167
- this._visibleRange = Atom3.make({
1168
- start: {
1169
- row: 0,
1170
- col: 0
1171
- },
1172
- end: {
1173
- row: 0,
1174
- col: 0
1175
- }
1176
- });
1177
- }
1178
- getCells(range, plane) {
1179
- this.fieldProjectionCache.clear();
1180
- let cells;
1181
- switch (plane) {
1182
- case "grid":
1183
- this._registry.set(this._visibleRange, range);
1184
- cells = this.getMainGridCells(range);
1185
- break;
1186
- case "frozenRowsStart":
1187
- cells = this.getHeaderCells(range);
1188
- break;
1189
- case "frozenColsStart":
1190
- cells = this.getSelectionColumnCells(range);
1191
- break;
1192
- case "frozenColsEnd":
1193
- cells = this.getActionColumnCells(range);
1194
- break;
1195
- case "fixedStartStart":
1196
- cells = this.getSelectAllCell();
1197
- break;
1198
- case "fixedStartEnd":
1199
- cells = this.getNewColumnCell();
1200
- break;
1201
- case "frozenRowsEnd":
1202
- cells = this.getDraftRowCells(range);
1203
- break;
1204
- case "fixedEndStart":
1205
- cells = this.getDraftIconCells(range);
1206
- break;
1207
- case "fixedEndEnd":
1208
- cells = this.getDraftActionCells(range);
1209
- break;
1210
- default:
1211
- cells = {};
1212
- }
1213
- if (plane === "grid" && this.model.features.dataEditable === false) {
1214
- Object.values(cells).forEach((cell) => {
1215
- cell.readonly = "text-select";
1216
- });
1217
- }
1218
- return cells;
1219
- }
1220
- /**
1221
- * Gets a field projection, using cache if available within the current render pass.
1222
- */
1223
- getFieldProjection(fieldId) {
1224
- let projection = this.fieldProjectionCache.get(fieldId);
1225
- if (!projection) {
1226
- projection = this.model.projection.getFieldProjection(fieldId);
1227
- this.fieldProjectionCache.set(fieldId, projection);
1228
- }
1229
- return projection;
1230
- }
1231
- createDataCell(cells, obj, field, colIndex, displayIndex) {
1232
- const { props } = this.getFieldProjection(field.id);
1233
- const cell = {
1234
- get value() {
1235
- const value = SchemaEx2.getValue(obj, field.path);
1236
- if (value == null) {
1237
- return "";
1238
- }
1239
- if (props.type === "array") {
1240
- return "";
1241
- }
1242
- switch (props.format) {
1243
- case Format3.TypeFormat.Boolean:
1244
- case Format3.TypeFormat.SingleSelect:
1245
- case Format3.TypeFormat.MultiSelect: {
1246
- return "";
1247
- }
1248
- case Format3.TypeFormat.Ref: {
1249
- if (!field.referencePath) {
1250
- return "";
1251
- }
1252
- return SchemaEx2.getValue(value.target, field.referencePath);
1253
- }
1254
- default: {
1255
- return formatForDisplay({
1256
- type: props.type,
1257
- format: props.format,
1258
- value
1259
- });
1260
- }
1261
- }
1262
- }
1263
- };
1264
- const classes = [];
1265
- const formatClasses = cellClassesForFieldType(props);
1266
- if (formatClasses) {
1267
- classes.push(formatClasses);
1268
- }
1269
- const rowSelectionClasses = cellClassesForRowSelection(this.model.selection.isObjectSelected(obj), this.model.selection.selectionMode);
1270
- if (rowSelectionClasses) {
1271
- classes.push(rowSelectionClasses);
1272
- }
1273
- cell.className = mx(classes);
1274
- if (props.type === TypeEnum.Array) {
1275
- const targetArray = SchemaEx2.getValue(obj, field.path);
1276
- if (targetArray && Array.isArray(targetArray)) {
1277
- const getLabel = (value) => {
1278
- if (!value) {
1279
- return void 0;
1280
- }
1281
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1282
- return String(value);
1283
- }
1284
- if (Array.isArray(value)) {
1285
- return "Array";
1286
- }
1287
- if (typeof value === "object" && value.name) {
1288
- return value.name;
1289
- }
1290
- if (typeof value === "object" && value.value) {
1291
- return `${value.value}`;
1292
- }
1293
- return "Object";
1294
- };
1295
- const tags = targetArray.map(getLabel).filter(Predicate.isNotNullable).map((title) => {
1296
- return `<span class="dx-tag" data-hue="neutral">${title}</span>`;
1297
- }).join("");
1298
- cell.accessoryHtml = `<div class="flex flex-row gap-1 overflow-x-auto">${tags}</div>`;
1299
- }
1300
- }
1301
- if (props.format === Format3.TypeFormat.Ref && props.referenceSchema) {
1302
- const targetObj = SchemaEx2.getValue(obj, field.path)?.target;
1303
- if (targetObj) {
1304
- const uri = Obj2.getURI(targetObj);
1305
- cell.accessoryHtml = `<div role="none" class="absolute end-0 inset-y-0 p-(--dx-grid-cell-content-padding-block)"><dx-anchor uri=${uri} class="dx-button w-6 aspect-square min-h-0" data-dx-grid-action="accessory"><dx-icon icon="ph--link-simple--regular"/></dx-anchor></div>`;
1306
- }
1307
- }
1308
- if (props.format === Format3.TypeFormat.URL) {
1309
- const value = SchemaEx2.getValue(obj, field.path);
1310
- const href = typeof value === "string" ? safeHttpUrl(value) : void 0;
1311
- if (href) {
1312
- cell.accessoryHtml = `<div role="none" class="absolute end-0 inset-y-0 p-(--dx-grid-cell-content-padding-block)"><a href="${escapeHtmlAttribute(href)}" target="_blank" rel="noopener noreferrer" class="dx-button w-6 aspect-square min-h-0" data-dx-grid-action="accessory"><dx-icon icon="ph--arrow-square-out--regular"/></a></div>`;
1313
- }
1314
- }
1315
- if (props.format === Format3.TypeFormat.Boolean) {
1316
- const value = SchemaEx2.getValue(obj, field.path);
1317
- cell.accessoryHtml = tableControls.switch.render({
1318
- colIndex,
1319
- rowIndex: displayIndex,
1320
- checked: value ?? false
1321
- });
1322
- cell.readonly = "no-text-select";
1323
- }
1324
- if (props.format === Format3.TypeFormat.SingleSelect) {
1325
- const value = SchemaEx2.getValue(obj, field.path);
1326
- const options = this.model.projection.getFieldProjection(field.id).props.options;
1327
- if (options) {
1328
- const option = options.find((o) => o.id === value);
1329
- if (option) {
1330
- cell.accessoryHtml = `<span class="dx-tag" data-hue="${option.color}">${option.title}</span>`;
1331
- }
1332
- }
1333
- }
1334
- if (props.format === Format3.TypeFormat.MultiSelect) {
1335
- const values = SchemaEx2.getValue(obj, field.path);
1336
- const options = this.model.projection.getFieldProjection(field.id).props.options;
1337
- if (options && values && values.length > 0) {
1338
- const tags = values.map((value) => {
1339
- const option = options.find((o) => o.id === value);
1340
- if (option) {
1341
- return `<span class="dx-tag" data-hue="${option.color}">${option.title}</span>`;
1342
- }
1343
- return null;
1344
- }).filter(Boolean).join("");
1345
- if (tags) {
1346
- cell.accessoryHtml = tags;
1347
- }
1348
- }
1349
- }
1350
- const idx = toPlaneCellIndex({
1351
- col: colIndex,
1352
- row: displayIndex
1353
- });
1354
- cells[idx] = cell;
1355
- }
1356
- getMainGridCells(range) {
1357
- const cells = {};
1358
- const fields = this.model.projection?.getFields() ?? [];
1359
- for (let row = range.start.row; row <= range.end.row && row < this.model.getRowCount(); row++) {
1360
- for (let col = range.start.col; col <= range.end.col && col < fields.length; col++) {
1361
- const field = fields[col];
1362
- if (!field) {
1363
- continue;
1364
- }
1365
- this.createDataCell(cells, this.model.getRows()[row], field, col, row);
1366
- }
1367
- }
1368
- return cells;
1369
- }
1370
- getDraftRowCells(range) {
1371
- const cells = {};
1372
- const fields = this.model.projection?.getFields() ?? [];
1373
- const draftRows = this.model.getDraftRows();
1374
- if (draftRows.length === 0) {
1375
- for (let col = range.start.col; col <= range.end.col && col < fields.length; col++) {
1376
- cells[toPlaneCellIndex({
1377
- col,
1378
- row: 0
1379
- })] = {
1380
- value: "",
1381
- readonly: true,
1382
- className: "dx-grid__row--cta__cell"
1383
- };
1384
- }
1385
- } else {
1386
- for (let row = range.start.row; row <= range.end.row && row < draftRows.length; row++) {
1387
- const draftRow = draftRows[row];
1388
- for (let col = range.start.col; col <= range.end.col && col < fields.length; col++) {
1389
- const cellIndex = toPlaneCellIndex({
1390
- col,
1391
- row
1392
- });
1393
- const field = fields[col];
1394
- if (!field) {
1395
- continue;
1396
- }
1397
- this.createDataCell(cells, draftRow.data, field, col, row);
1398
- if (this.model.hasDraftRowValidationError(row, field.path)) {
1399
- const cellValue = cells[cellIndex];
1400
- if (cellValue) {
1401
- const existingClasses = cellValue.className || "";
1402
- const draftClasses = "dx-grid__cell--flagged";
1403
- cellValue.className = existingClasses ? `${existingClasses} ${draftClasses}` : draftClasses;
1404
- }
1405
- }
1406
- }
1407
- }
1408
- }
1409
- return cells;
1410
- }
1411
- getHeaderCells(range) {
1412
- const cells = {};
1413
- const fields = this.model.projection?.getFields() ?? [];
1414
- const currentSort = this.model.getSorting();
1415
- for (let col = range.start.col; col <= range.end.col && col < fields.length; col++) {
1416
- const { field, props } = this.model.projection.getFieldProjection(fields[col].id);
1417
- const direction = currentSort?.fieldId === field.id ? currentSort.direction : void 0;
1418
- cells[toPlaneCellIndex({
1419
- col,
1420
- row: 0
1421
- })] = {
1422
- // TODO(burdon): Use same logic as form for fallback title.
1423
- value: "",
1424
- resizeHandle: "col",
1425
- accessoryHtml: `
1426
- <span class="grow min-w-0 truncate">${props.title ?? field.path}</span>
1427
- ${direction !== void 0 ? tableButtons.sort.render({
1428
- fieldId: field.id,
1429
- direction
1430
- }) : ""}
1431
- ${tableButtons.columnSettings.render({
1432
- fieldId: field.id
1433
- })}
1434
- `,
1435
- className: "bg-axis-surface! text-axis-text! [&>div]:flex [&>div]:items-stretch"
1436
- };
1437
- }
1438
- return cells;
1439
- }
1440
- getSelectionColumnCells(range) {
1441
- const cells = {};
1442
- for (let row = range.start.row; row <= range.end.row && row < this.model.getRowCount(); row++) {
1443
- const isSelected = this.model.selection.isRowIndexSelected(row);
1444
- const classes = cellClassesForRowSelection(isSelected, this.model.selection.selectionMode);
1445
- cells[toPlaneCellIndex({
1446
- col: 0,
1447
- row
1448
- })] = {
1449
- value: "",
1450
- readonly: "no-text-select",
1451
- className: classes ? mx(classes) : void 0,
1452
- accessoryHtml: tableControls.checkbox.render({
1453
- rowIndex: row,
1454
- checked: isSelected
1455
- })
1456
- };
1457
- }
1458
- return cells;
1459
- }
1460
- getActionColumnCells(range) {
1461
- const cells = {};
1462
- for (let row = range.start.row; row <= range.end.row && row < this.model.getRowCount(); row++) {
1463
- const isSelected = this.model.selection.isRowIndexSelected(row);
1464
- const classes = cellClassesForRowSelection(isSelected, this.model.selection.selectionMode);
1465
- cells[toPlaneCellIndex({
1466
- col: 0,
1467
- row
1468
- })] = {
1469
- value: "",
1470
- readonly: true,
1471
- className: classes ? mx(classes) : void 0,
1472
- accessoryHtml: tableButtons.rowMenu.render({
1473
- rowIndex: row
1474
- })
1475
- };
1476
- }
1477
- return cells;
1478
- }
1479
- getSelectAllCell() {
1480
- if (!this.model.features.selection.enabled || this.model.selection.selectionMode === "single") {
1481
- return {
1482
- [toPlaneCellIndex({
1483
- col: 0,
1484
- row: 0
1485
- })]: {
1486
- className: "bg-axis-surface!",
1487
- readonly: true,
1488
- value: ""
1489
- }
1490
- };
1491
- }
1492
- return {
1493
- [toPlaneCellIndex({
1494
- col: 0,
1495
- row: 0
1496
- })]: {
1497
- accessoryHtml: tableControls.checkbox.render({
1498
- rowIndex: 0,
1499
- header: true,
1500
- checked: this.model.selection.allRowsSelected
1501
- }),
1502
- className: "bg-axis-surface!",
1503
- readonly: true,
1504
- value: ""
1505
- }
1506
- };
1507
- }
1508
- getNewColumnCell() {
1509
- return {
1510
- [toPlaneCellIndex({
1511
- col: 0,
1512
- row: 0
1513
- })]: {
1514
- accessoryHtml: this.model.features.schemaEditable ? tableButtons.addColumn.render({
1515
- disabled: (this.model.projection?.getFields()?.length ?? 0) >= VIEW_FIELD_LIMIT
1516
- }) : void 0,
1517
- className: "bg-axis-surface!",
1518
- readonly: true,
1519
- value: ""
1520
- }
1521
- };
1522
- }
1523
- getDraftActionCells(range) {
1524
- const cells = {};
1525
- const draftRows = this.model.getDraftRows();
1526
- if (draftRows.length === 0) {
1527
- cells[toPlaneCellIndex({
1528
- col: 0,
1529
- row: 0
1530
- })] = {
1531
- value: "",
1532
- className: "dx-grid__row--cta__cell",
1533
- readonly: true
1534
- };
1535
- } else {
1536
- for (let row = range.start.row; row <= range.end.row && row < draftRows.length; row++) {
1537
- const draftRow = draftRows[row];
1538
- const disabled = !draftRow.valid;
1539
- cells[toPlaneCellIndex({
1540
- col: 0,
1541
- row
1542
- })] = {
1543
- value: "",
1544
- readonly: true,
1545
- accessoryHtml: tableButtons.saveDraftRow.render({
1546
- rowIndex: row,
1547
- disabled
1548
- })
1549
- };
1550
- }
1551
- }
1552
- return cells;
1553
- }
1554
- getDraftIconCells(range) {
1555
- const cells = {};
1556
- const draftRows = this.model.getDraftRows();
1557
- for (let row = range.start.row; row <= range.end.row; row++) {
1558
- cells[toPlaneCellIndex({
1559
- col: 0,
1560
- row
1561
- })] = {
1562
- value: "",
1563
- readonly: true,
1564
- accessoryHtml: '<dx-icon icon="ph--plus--regular" class="contents"></dx-icon>',
1565
- className: mx("[&>div]:grid [&>div]:place-content-center", draftRows.length < 1 && "dx-grid__row--cta__cell")
1566
- };
1567
- }
1568
- return cells;
1569
- }
1570
- };
1571
- var safeHttpUrl = (value) => {
1572
- try {
1573
- const normalized = /^https?:\/\//i.test(value) ? value : `https://${value}`;
1574
- const url = new URL(normalized);
1575
- return url.protocol === "http:" || url.protocol === "https:" ? url.href : void 0;
1576
- } catch {
1577
- return void 0;
1578
- }
1579
- };
1580
- var escapeHtmlAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1581
- var cellClassesForRowSelection = (selected, selectionMode) => {
1582
- if (!selected) {
1583
- if (selectionMode === "single") {
1584
- return [
1585
- "cursor-pointer!"
1586
- ];
1587
- } else {
1588
- return void 0;
1589
- }
1590
- }
1591
- switch (selectionMode) {
1592
- case "single":
1593
- return [
1594
- "dx-grid__cell--no-focus-unfurl bg-current-surface! hover:bg-hover-surface cursor-pointer!"
1595
- ];
1596
- case "multiple":
1597
- return [
1598
- "bg-grid-cell-selected!"
1599
- ];
1600
- }
1601
- };
1602
-
1603
- // src/hooks/useAddRow.ts
1604
- import { useCallback } from "react";
1605
- import { Obj as Obj3 } from "@dxos/echo";
1606
- var useAddRow = ({ db, schema }) => {
1607
- return useCallback((data) => {
1608
- if (db && schema) {
1609
- try {
1610
- db.add(Obj3.make(schema, data ?? {}));
1611
- return "final";
1612
- } catch (error) {
1613
- return "draft";
1614
- }
1615
- }
1616
- return "final";
1617
- }, [
1618
- db,
1619
- schema
1620
- ]);
1621
- };
1622
-
1623
- // src/hooks/useProjectionModel.ts
1624
- import { useState } from "react";
1625
- import { Type as Type2 } from "@dxos/echo";
1626
- import { useAsyncEffect } from "@dxos/react-ui";
1627
- import { ProjectionModel, createEchoChangeCallback as createEchoChangeCallback2 } from "@dxos/schema";
1628
- var useProjectionModel = (schema, table, registry) => {
1629
- const [projection, setProjection] = useState();
1630
- useAsyncEffect(async () => {
1631
- if (schema && table) {
1632
- const view = await table.view.load();
1633
- const jsonSchema = schema.jsonSchema;
1634
- const change = createEchoChangeCallback2(view, Type2.getDatabase(schema) != null ? schema : void 0);
1635
- const projection2 = new ProjectionModel({
1636
- registry,
1637
- view,
1638
- baseSchema: jsonSchema,
1639
- change
1640
- });
1641
- projection2.normalizeView();
1642
- setProjection(projection2);
1643
- }
1644
- }, [
1645
- schema,
1646
- table,
1647
- registry
1648
- ]);
1649
- return projection;
1650
- };
1651
-
1652
- // src/hooks/useTableModel.ts
1653
- import { RegistryContext } from "@effect-atom/atom-react";
1654
- import { useContext, useEffect, useMemo, useState as useState2 } from "react";
1655
- import { Obj as Obj4 } from "@dxos/echo";
1656
- import { useSelection, useSelectionActions, useViewStateManagerOptional } from "@dxos/react-ui-attention";
1657
- var useTableModel = ({ object, projection, db, rows, rowActions, features, onSelectionChanged, onRowAction, ...props }) => {
1658
- const registry = useContext(RegistryContext);
1659
- const viewState = useViewStateManagerOptional();
1660
- const selected = useSelection(object && Obj4.getURI(object), "multi");
1661
- const initialSelection = useMemo(() => selected, [
1662
- object
1663
- ]);
1664
- const [model, setModel] = useState2();
1665
- useEffect(() => {
1666
- if (!object || !projection) {
1667
- return;
1668
- }
1669
- let model2;
1670
- const t = setTimeout(async () => {
1671
- model2 = new TableModel({
1672
- registry,
1673
- object,
1674
- projection,
1675
- db,
1676
- viewState,
1677
- change: createEchoChangeCallback(object),
1678
- features,
1679
- rowActions,
1680
- initialSelection,
1681
- onRowAction,
1682
- ...props
1683
- });
1684
- await model2.open();
1685
- setModel(model2);
1686
- });
1687
- return () => {
1688
- clearTimeout(t);
1689
- void model2?.close();
1690
- };
1691
- }, [
1692
- registry,
1693
- viewState,
1694
- object,
1695
- projection,
1696
- features,
1697
- rowActions,
1698
- initialSelection
1699
- ]);
1700
- useEffect(() => {
1701
- if (rows && model) {
1702
- model.setRows(rows);
1703
- }
1704
- }, [
1705
- model,
1706
- rows
1707
- ]);
1708
- const { multi, clear } = useSelectionActions(model?.id);
1709
- useEffect(() => {
1710
- if (!model) {
1711
- return;
1712
- }
1713
- const unsubscribe = registry.subscribe(model.selection.selectionAtom, () => {
1714
- const selectedItems = [
1715
- ...model.selection.selection
1716
- ];
1717
- multi(selectedItems);
1718
- onSelectionChanged?.(selectedItems);
1719
- });
1720
- return () => {
1721
- clear();
1722
- unsubscribe();
1723
- };
1724
- }, [
1725
- registry,
1726
- model,
1727
- onSelectionChanged
1728
- ]);
1729
- return model;
1730
- };
1731
-
1732
- export {
1733
- extractOrder,
1734
- getSortValue,
1735
- compareValues,
1736
- BUTTON_IDENTIFIERS,
1737
- tableButtons,
1738
- CONTROL_IDENTIFIERS,
1739
- CheckboxStory,
1740
- SwitchStory,
1741
- tableControls,
1742
- FieldSortSchema,
1743
- tableSortAspect,
1744
- createEchoChangeCallback,
1745
- createDirectChangeCallback,
1746
- TableModel,
1747
- TablePresentation,
1748
- cellClassesForRowSelection,
1749
- useAddRow,
1750
- useProjectionModel,
1751
- useTableModel
1752
- };
1753
- //# sourceMappingURL=chunk-E6V274ZW.mjs.map