@dxos/react-ui-table 0.8.4-main.c4373fc → 0.8.4-main.d05673bc65

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 (136) hide show
  1. package/dist/lib/browser/chunk-BF54SSNL.mjs +70 -0
  2. package/dist/lib/browser/chunk-BF54SSNL.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-PTHMYAAM.mjs +1751 -0
  4. package/dist/lib/browser/chunk-PTHMYAAM.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +1158 -1024
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/testing/index.mjs +30 -42
  9. package/dist/lib/browser/testing/index.mjs.map +3 -3
  10. package/dist/lib/browser/types/index.mjs +3 -3
  11. package/dist/lib/node-esm/chunk-GI72MQSG.mjs +1753 -0
  12. package/dist/lib/node-esm/chunk-GI72MQSG.mjs.map +7 -0
  13. package/dist/lib/node-esm/chunk-SIRDIPHZ.mjs +71 -0
  14. package/dist/lib/node-esm/chunk-SIRDIPHZ.mjs.map +7 -0
  15. package/dist/lib/node-esm/index.mjs +1158 -1024
  16. package/dist/lib/node-esm/index.mjs.map +4 -4
  17. package/dist/lib/node-esm/meta.json +1 -1
  18. package/dist/lib/node-esm/testing/index.mjs +30 -42
  19. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  20. package/dist/lib/node-esm/types/index.mjs +3 -3
  21. package/dist/types/src/components/Table/ColumnActionsMenu.d.ts +1 -2
  22. package/dist/types/src/components/Table/ColumnActionsMenu.d.ts.map +1 -1
  23. package/dist/types/src/components/Table/ColumnSettings.d.ts +2 -2
  24. package/dist/types/src/components/Table/ColumnSettings.d.ts.map +1 -1
  25. package/dist/types/src/components/Table/DynamicTable.d.ts +7 -7
  26. package/dist/types/src/components/Table/DynamicTable.d.ts.map +1 -1
  27. package/dist/types/src/components/Table/DynamicTable.stories.d.ts +4 -18
  28. package/dist/types/src/components/Table/DynamicTable.stories.d.ts.map +1 -1
  29. package/dist/types/src/components/Table/Relations.stories.d.ts +12 -9
  30. package/dist/types/src/components/Table/Relations.stories.d.ts.map +1 -1
  31. package/dist/types/src/components/Table/RowActionsMenu.d.ts.map +1 -1
  32. package/dist/types/src/components/Table/Table.d.ts +11 -11
  33. package/dist/types/src/components/Table/Table.d.ts.map +1 -1
  34. package/dist/types/src/components/Table/Table.stories.d.ts +71 -5
  35. package/dist/types/src/components/Table/Table.stories.d.ts.map +1 -1
  36. package/dist/types/src/components/TableCellEditor/CellValidationMessage.d.ts +1 -1
  37. package/dist/types/src/components/TableCellEditor/FormCellEditor.d.ts +10 -12
  38. package/dist/types/src/components/TableCellEditor/FormCellEditor.d.ts.map +1 -1
  39. package/dist/types/src/components/TableCellEditor/TableCellEditor.d.ts +5 -7
  40. package/dist/types/src/components/TableCellEditor/TableCellEditor.d.ts.map +1 -1
  41. package/dist/types/src/components/TableCellEditor/TableCellEditor.stories.d.ts +4 -4
  42. package/dist/types/src/components/TableCellEditor/TableCellEditor.stories.d.ts.map +1 -1
  43. package/dist/types/src/components/TableToolbar/TableToolbar.d.ts +5 -5
  44. package/dist/types/src/components/TableToolbar/TableToolbar.d.ts.map +1 -1
  45. package/dist/types/src/components/testing.d.ts +22 -15
  46. package/dist/types/src/components/testing.d.ts.map +1 -1
  47. package/dist/types/src/hooks/index.d.ts +2 -1
  48. package/dist/types/src/hooks/index.d.ts.map +1 -1
  49. package/dist/types/src/hooks/useAddRow.d.ts +5 -6
  50. package/dist/types/src/hooks/useAddRow.d.ts.map +1 -1
  51. package/dist/types/src/hooks/useProjectionModel.d.ts +6 -0
  52. package/dist/types/src/hooks/useProjectionModel.d.ts.map +1 -0
  53. package/dist/types/src/hooks/useTableModel.d.ts +9 -9
  54. package/dist/types/src/hooks/useTableModel.d.ts.map +1 -1
  55. package/dist/types/src/model/modal-controller.d.ts +5 -1
  56. package/dist/types/src/model/modal-controller.d.ts.map +1 -1
  57. package/dist/types/src/model/selection-model.d.ts +17 -8
  58. package/dist/types/src/model/selection-model.d.ts.map +1 -1
  59. package/dist/types/src/model/table-model.d.ts +105 -25
  60. package/dist/types/src/model/table-model.d.ts.map +1 -1
  61. package/dist/types/src/model/table-presentation.d.ts +3 -1
  62. package/dist/types/src/model/table-presentation.d.ts.map +1 -1
  63. package/dist/types/src/playwright/TableManager.d.ts +2 -1
  64. package/dist/types/src/playwright/TableManager.d.ts.map +1 -1
  65. package/dist/types/src/testing/useTestTableModel.d.ts +18 -15
  66. package/dist/types/src/testing/useTestTableModel.d.ts.map +1 -1
  67. package/dist/types/src/translations.d.ts +4 -4
  68. package/dist/types/src/translations.d.ts.map +1 -1
  69. package/dist/types/src/types/Table.d.ts +26 -0
  70. package/dist/types/src/types/Table.d.ts.map +1 -0
  71. package/dist/types/src/types/index.d.ts +1 -1
  72. package/dist/types/src/types/index.d.ts.map +1 -1
  73. package/dist/types/src/util/dynamic-table.d.ts +14 -11
  74. package/dist/types/src/util/dynamic-table.d.ts.map +1 -1
  75. package/dist/types/src/util/dynamic-table.test.d.ts +2 -0
  76. package/dist/types/src/util/dynamic-table.test.d.ts.map +1 -0
  77. package/dist/types/src/util/index.d.ts +2 -0
  78. package/dist/types/src/util/index.d.ts.map +1 -1
  79. package/dist/types/src/util/query-ast.d.ts +7 -0
  80. package/dist/types/src/util/query-ast.d.ts.map +1 -0
  81. package/dist/types/src/util/sort.d.ts +12 -0
  82. package/dist/types/src/util/sort.d.ts.map +1 -0
  83. package/dist/types/tsconfig.tsbuildinfo +1 -1
  84. package/package.json +54 -54
  85. package/src/components/Table/ColumnActionsMenu.tsx +10 -6
  86. package/src/components/Table/ColumnSettings.tsx +8 -9
  87. package/src/components/Table/DynamicTable.stories.tsx +16 -16
  88. package/src/components/Table/DynamicTable.tsx +30 -22
  89. package/src/components/Table/Relations.stories.tsx +52 -60
  90. package/src/components/Table/RowActionsMenu.tsx +24 -15
  91. package/src/components/Table/Table.stories.tsx +116 -98
  92. package/src/components/Table/Table.tsx +324 -299
  93. package/src/components/TableCellEditor/CellValidationMessage.tsx +5 -5
  94. package/src/components/TableCellEditor/FormCellEditor.tsx +117 -134
  95. package/src/components/TableCellEditor/TableCellEditor.stories.tsx +18 -13
  96. package/src/components/TableCellEditor/TableCellEditor.tsx +31 -31
  97. package/src/components/TableToolbar/TableToolbar.tsx +53 -37
  98. package/src/components/testing.ts +38 -12
  99. package/src/hooks/index.ts +2 -1
  100. package/src/hooks/useAddRow.ts +8 -10
  101. package/src/hooks/useProjectionModel.ts +39 -0
  102. package/src/hooks/useTableModel.ts +36 -34
  103. package/src/model/modal-controller.ts +23 -12
  104. package/src/model/selection-model.ts +75 -44
  105. package/src/model/table-model.test.ts +82 -54
  106. package/src/model/table-model.ts +436 -170
  107. package/src/model/table-presentation.test.ts +59 -49
  108. package/src/model/table-presentation.ts +43 -37
  109. package/src/playwright/TableManager.ts +13 -6
  110. package/src/playwright/playwright.config.ts +1 -1
  111. package/src/playwright/smoke.spec.ts +56 -10
  112. package/src/testing/useTestTableModel.ts +45 -38
  113. package/src/translations.ts +3 -3
  114. package/src/types/Table.ts +79 -0
  115. package/src/types/index.ts +1 -1
  116. package/src/util/dynamic-table.test.ts +70 -0
  117. package/src/util/dynamic-table.ts +41 -28
  118. package/src/util/index.ts +2 -0
  119. package/src/util/query-ast.ts +22 -0
  120. package/src/util/sort.ts +90 -0
  121. package/src/util/table-buttons.ts +1 -1
  122. package/src/util/table-controls.ts +2 -2
  123. package/dist/lib/browser/chunk-4K7JPALT.mjs +0 -66
  124. package/dist/lib/browser/chunk-4K7JPALT.mjs.map +0 -7
  125. package/dist/lib/browser/chunk-OZTXLZGM.mjs +0 -1804
  126. package/dist/lib/browser/chunk-OZTXLZGM.mjs.map +0 -7
  127. package/dist/lib/node-esm/chunk-MK6OVUF6.mjs +0 -67
  128. package/dist/lib/node-esm/chunk-MK6OVUF6.mjs.map +0 -7
  129. package/dist/lib/node-esm/chunk-S56Z4V4X.mjs +0 -1805
  130. package/dist/lib/node-esm/chunk-S56Z4V4X.mjs.map +0 -7
  131. package/dist/types/src/model/table-sorting.d.ts +0 -52
  132. package/dist/types/src/model/table-sorting.d.ts.map +0 -1
  133. package/dist/types/src/types/schema.d.ts +0 -28
  134. package/dist/types/src/types/schema.d.ts.map +0 -1
  135. package/src/model/table-sorting.ts +0 -225
  136. package/src/types/schema.ts +0 -73
@@ -2,23 +2,16 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { type ReadonlySignal, computed, effect, signal } from '@preact/signals-core';
5
+ import { Atom, type Registry } from '@effect-atom/atom-react';
6
6
 
7
7
  import { Resource } from '@dxos/context';
8
- import { Obj, Ref } from '@dxos/echo';
9
- import {
10
- FormatEnum,
11
- type JsonProp,
12
- type JsonSchemaType,
13
- getSchema,
14
- getValue,
15
- setValue,
16
- toEffectSchema,
17
- } from '@dxos/echo/internal';
8
+ import { type Database, Format, Obj, Order, Query, type QueryAST, Ref } from '@dxos/echo';
9
+ import { type View } from '@dxos/echo';
10
+ import { type JsonProp, type JsonSchemaType, type Mutable, toEffectSchema } from '@dxos/echo/internal';
11
+ import { getSnapshot } from '@dxos/echo/internal';
12
+ import { getValue, setValue } from '@dxos/effect';
18
13
  import { invariant } from '@dxos/invariant';
19
14
  import { ObjectId } from '@dxos/keys';
20
- import { getSnapshot, isLiveObject } from '@dxos/live-object';
21
- import { fullyQualifiedId } from '@dxos/react-client/echo';
22
15
  import { type Label } from '@dxos/react-ui';
23
16
  import { formatForEditing, parseValue } from '@dxos/react-ui-form';
24
17
  import {
@@ -27,21 +20,57 @@ import {
27
20
  type DxGridPlaneRange,
28
21
  type DxGridPosition,
29
22
  } from '@dxos/react-ui-grid';
30
- import {
31
- type DataType,
32
- type FieldSortType,
33
- ProjectionModel,
34
- type PropertyType,
35
- type ValidationError,
36
- validateSchema,
37
- } from '@dxos/schema';
38
-
39
- import { Table } from '../types';
40
- import { touch } from '../util';
23
+ import { type ProjectionModel, type PropertyType, type ValidationError, validateSchema } from '@dxos/schema';
24
+
25
+ import { type Table } from '../types';
26
+ import { extractOrder } from '../util';
27
+ import { compareValues } from '../util/sort';
41
28
  import { extractTagIds } from '../util/tag';
42
29
 
30
+ /**
31
+ * Field sort configuration.
32
+ */
33
+ export type FieldSortType = {
34
+ fieldId: string;
35
+ direction: QueryAST.OrderDirection;
36
+ };
37
+
43
38
  import { type SelectionMode, SelectionModel } from './selection-model';
44
- import { TableSorting } from './table-sorting';
39
+
40
+ /**
41
+ * Callback type for wrapping mutations in Obj.change().
42
+ * Contains separate callbacks for table object and row mutations.
43
+ */
44
+ export type TableChangeCallback<T extends TableRow> = {
45
+ /** Callback to wrap table object mutations. */
46
+ table: (mutate: (mutableTable: Table.Table) => void) => void;
47
+ /** Callback to wrap row mutations. */
48
+ row: (row: T, mutate: (mutableRow: T) => void) => void;
49
+ };
50
+
51
+ /**
52
+ * Creates a change callback for ECHO-backed table and rows.
53
+ * Use this when the table and rows are stored in the ECHO database.
54
+ */
55
+ export const createEchoChangeCallback = <T extends TableRow>(table: Table.Table): TableChangeCallback<T> => ({
56
+ table: (mutate) => Obj.change(table, (mutableTable) => mutate(mutableTable as unknown as Table.Table)),
57
+ row: (row, mutate) => {
58
+ if (Obj.isObject(row)) {
59
+ Obj.change(row, (mutableRow) => mutate(mutableRow as T));
60
+ } else {
61
+ mutate(row);
62
+ }
63
+ },
64
+ });
65
+
66
+ /**
67
+ * Creates a change callback that directly mutates objects without wrapping.
68
+ * Use this for plain JavaScript objects (tests, non-ECHO scenarios).
69
+ */
70
+ export const createDirectChangeCallback = <T extends TableRow>(table: Table.Table): TableChangeCallback<T> => ({
71
+ table: (mutate) => mutate(table),
72
+ row: (row, mutate) => mutate(row),
73
+ });
45
74
 
46
75
  // Domain types for cell classification
47
76
  export type TableCellType = 'standard' | 'draft' | 'header';
@@ -78,70 +107,89 @@ const defaultFeatures: TableFeatures = {
78
107
  export type InsertRowResult = 'draft' | 'final';
79
108
 
80
109
  export type TableModelProps<T extends TableRow = TableRow> = {
81
- view: DataType.View;
82
- schema: JsonSchemaType;
83
- projection?: ProjectionModel;
110
+ registry: Registry.Registry;
111
+ object: Table.Table;
112
+ projection: ProjectionModel;
113
+ db?: Database.Database;
114
+ /**
115
+ * Callbacks to wrap mutations in Obj.change().
116
+ * Use createEchoChangeCallback() for ECHO-backed objects or createDirectChangeCallback() for plain objects.
117
+ */
118
+ change?: TableChangeCallback<T>;
84
119
  features?: Partial<TableFeatures>;
85
- sorting?: FieldSortType[];
86
120
  initialSelection?: string[];
87
121
  pinnedRows?: { top: number[]; bottom: number[] };
88
122
  rowActions?: TableRowAction[];
89
123
  onResolveSchema?: (typename: string) => Promise<JsonSchemaType>;
90
124
  onInsertRow?: (data?: any) => InsertRowResult;
91
125
  onDeleteRows?: (index: number, obj: T[]) => void;
92
- onDeleteColumn?: (fieldId: string) => void;
126
+ onColumnDelete?: (fieldId: string) => void;
93
127
  onCellUpdate?: (cell: DxGridPosition) => void;
94
128
  onRowOrderChange?: () => void;
95
129
  onRowAction?: (actionId: string, data: T) => void;
96
130
  };
97
131
 
98
132
  export class TableModel<T extends TableRow = TableRow> extends Resource {
99
- private readonly _view: DataType.View;
133
+ private readonly _registry: Registry.Registry;
134
+ private readonly _object: Table.Table;
100
135
  private readonly _projection: ProjectionModel;
101
- private _table?: Table.Table;
136
+ private readonly _db?: Database.Database;
137
+ private readonly _change: TableChangeCallback<T>;
102
138
 
103
- private readonly _visibleRange = signal<DxGridPlaneRange>({
104
- start: { row: 0, col: 0 },
105
- end: { row: 0, col: 0 },
106
- });
139
+ private readonly _visibleRange: Atom.Writable<DxGridPlaneRange>;
107
140
 
108
141
  private readonly _onInsertRow?: (data?: any) => InsertRowResult;
109
142
  private readonly _onDeleteRows?: TableModelProps<T>['onDeleteRows'];
110
- private readonly _onDeleteColumn?: TableModelProps<T>['onDeleteColumn'];
143
+ private readonly _onColumnDelete?: TableModelProps<T>['onColumnDelete'];
111
144
  private readonly _onCellUpdate?: TableModelProps<T>['onCellUpdate'];
112
145
  private readonly _onRowOrderChange?: TableModelProps<T>['onRowOrderChange'];
113
146
  private readonly _onRowAction?: TableModelProps<T>['onRowAction'];
114
147
  private readonly _rowActions: TableRowAction[];
115
148
  private readonly _features: TableFeatures;
116
149
 
117
- private readonly _rows = signal<T[]>([]);
118
- private readonly _draftRows = signal<DraftRow<T>[]>([]);
119
- private readonly _sorting: TableSorting<T>;
150
+ private readonly _rows: Atom.Writable<T[]>;
151
+ private readonly _draftRows: Atom.Writable<DraftRow<T>[]>;
152
+ // In-memory sort state - changes are local until saved.
153
+ private readonly _inMemorySort: Atom.Writable<FieldSortType | undefined>;
154
+ // Derived atom for persisted sort from view.query.ast.
155
+ private readonly _persistedSort: Atom.Atom<FieldSortType | undefined>;
156
+ // Derived atom for current sort (in-memory takes precedence over persisted).
157
+ private readonly _sorting: Atom.Atom<FieldSortType | undefined>;
158
+ // Derived atom for sorted rows (used by rows getter and SelectionModel).
159
+ private readonly _sortedRows: Atom.Atom<T[]>;
160
+ // Derived atom for viewDirty state.
161
+ private readonly _viewDirty: Atom.Atom<boolean>;
120
162
 
121
163
  private _pinnedRows: NonNullable<TableModelProps<T>['pinnedRows']>;
122
164
  private _selection!: SelectionModel<T>;
123
- private _columnMeta?: ReadonlySignal<DxGridAxisMeta>;
165
+ private _columnMeta?: Atom.Atom<DxGridAxisMeta>;
166
+ // Counter atom that increments when cells are updated - allows UI to react to cell changes.
167
+ private readonly _cellUpdateCounter: Atom.Writable<number>;
124
168
 
125
169
  constructor({
126
- view,
127
- schema,
170
+ registry,
171
+ object,
128
172
  projection,
173
+ db,
174
+ change,
129
175
  features = {},
130
- sorting = [],
131
176
  initialSelection = [],
132
177
  pinnedRows = { top: [], bottom: [] },
133
178
  rowActions = [],
134
179
  onCellUpdate,
135
- onDeleteColumn,
180
+ onColumnDelete,
136
181
  onDeleteRows,
137
182
  onInsertRow,
138
183
  onRowOrderChange,
139
184
  onRowAction,
140
185
  }: TableModelProps<T>) {
141
186
  super();
142
- this._view = view;
143
- this._projection = projection ?? new ProjectionModel(schema, view.projection);
187
+ this._registry = registry;
188
+ this._object = object;
189
+ this._projection = projection;
144
190
  this._projection.normalizeView();
191
+ this._db = db;
192
+ this._change = change ?? createEchoChangeCallback<T>(object);
145
193
 
146
194
  // TODO(ZaymonFC): Use our more robust config merging module?
147
195
  this._features = { ...defaultFeatures, ...features };
@@ -151,49 +199,154 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
151
199
  'Single selection is not compatible with editable tables.',
152
200
  );
153
201
 
154
- this._sorting = new TableSorting(this._rows, this._view, this._projection);
202
+ // Initialize writable atoms.
203
+ this._visibleRange = Atom.make<DxGridPlaneRange>({
204
+ start: { row: 0, col: 0 },
205
+ end: { row: 0, col: 0 },
206
+ });
207
+ this._rows = Atom.make<T[]>([]);
208
+ this._draftRows = Atom.make<DraftRow<T>[]>([]);
209
+ this._inMemorySort = Atom.make<FieldSortType | undefined>(undefined);
210
+ this._cellUpdateCounter = Atom.make<number>(0);
211
+
212
+ // Create derived atom for persisted sort from view.query.ast.
213
+ this._persistedSort = Atom.make((_get) => {
214
+ // Note: This depends on the view being loaded and the projection being set.
215
+ // The view is loaded in _open().
216
+ const viewSnapshot = Obj.getSnapshot(this.view);
217
+ const ast = viewSnapshot.query.ast;
218
+ const orders = extractOrder(ast);
219
+
220
+ if (orders && orders.length > 0) {
221
+ const firstOrder = orders[0];
222
+ if (firstOrder.kind === 'property') {
223
+ // Find field by property path.
224
+ const field = this._projection.getFields().find((f) => f.path === firstOrder.property);
225
+ if (field) {
226
+ return {
227
+ fieldId: field.id,
228
+ direction: firstOrder.direction,
229
+ };
230
+ }
231
+ }
232
+ }
233
+
234
+ return undefined;
235
+ });
155
236
 
156
- if (sorting.length > 0) {
157
- const [sort] = sorting;
158
- this._sorting.setSort(sort.fieldId, sort.direction);
159
- }
237
+ // Create derived atom for current sort (in-memory takes precedence over persisted).
238
+ this._sorting = Atom.make((get) => {
239
+ const inMemorySort = get(this._inMemorySort);
240
+ return inMemorySort ?? get(this._persistedSort);
241
+ });
242
+
243
+ // Create derived atom for sorted rows (used by rows getter and SelectionModel).
244
+ this._sortedRows = Atom.make((get) => {
245
+ const rows = get(this._rows);
246
+ const sort = get(this._sorting);
247
+
248
+ if (!sort || rows.length === 0) {
249
+ return rows;
250
+ }
251
+
252
+ const field = this._projection.getFields().find((f) => f.id === sort.fieldId);
253
+ if (!field) {
254
+ return rows;
255
+ }
256
+
257
+ // Get field projection to check format.
258
+ const fieldProjection = this._projection.getFieldProjection(field.id);
259
+
260
+ const sorted = [...rows].sort((a, b) => {
261
+ const aValue = getValue(a, field.path);
262
+ const bValue = getValue(b, field.path);
263
+ return compareValues(aValue, bValue, fieldProjection.props.format, sort.direction);
264
+ });
265
+
266
+ return sorted;
267
+ });
160
268
 
161
269
  this._selection = new SelectionModel(
162
- this._sorting.sortedRows,
270
+ this._registry,
271
+ this._sortedRows,
163
272
  this._features.selection.mode ?? 'multiple',
164
273
  initialSelection,
165
274
  () => this._onRowOrderChange?.(),
166
275
  );
167
276
 
277
+ // Create derived atom for viewDirty.
278
+ this._viewDirty = Atom.make((get) => {
279
+ const inMemorySort = get(this._inMemorySort);
280
+ if (!inMemorySort) {
281
+ return false;
282
+ }
283
+
284
+ const persisted = get(this._persistedSort);
285
+ if (!persisted) {
286
+ return true; // In-memory sort but no persisted sort.
287
+ }
288
+
289
+ return inMemorySort.fieldId !== persisted.fieldId || inMemorySort.direction !== persisted.direction;
290
+ });
291
+
168
292
  this._pinnedRows = pinnedRows;
169
293
  this._rowActions = rowActions;
170
294
  this._onInsertRow = onInsertRow;
171
295
  this._onDeleteRows = onDeleteRows;
172
- this._onDeleteColumn = onDeleteColumn;
296
+ this._onColumnDelete = onColumnDelete;
173
297
  this._onCellUpdate = onCellUpdate;
174
298
  this._onRowOrderChange = onRowOrderChange;
175
299
  this._onRowAction = onRowAction;
176
300
  }
177
301
 
178
302
  public get id(): string {
179
- return fullyQualifiedId(this._view);
303
+ return Obj.getDXN(this._object).toString();
180
304
  }
181
305
 
182
- public get view(): DataType.View {
183
- return this._view;
306
+ public get view(): View.View {
307
+ const view = this._object.view.target;
308
+ invariant(view, 'Table model not initialized');
309
+ return view;
184
310
  }
185
311
 
186
312
  public get table(): Table.Table {
187
- invariant(this._table, 'Model not initialized');
188
- return this._table;
313
+ return this._object;
189
314
  }
190
315
 
191
316
  public get projection(): ProjectionModel {
192
317
  return this._projection;
193
318
  }
194
319
 
195
- public get rows(): ReadonlySignal<T[]> {
196
- return this.sorting.sortedRows;
320
+ public get db(): Database.Database | undefined {
321
+ return this._db;
322
+ }
323
+
324
+ /**
325
+ * Atom for reactive access to rows with in-memory sorting applied.
326
+ */
327
+ public get rows(): Atom.Atom<T[]> {
328
+ return this._sortedRows;
329
+ }
330
+
331
+ /**
332
+ * Gets rows with in-memory sorting applied.
333
+ * In-memory sort is local to this instance until saved.
334
+ */
335
+ public getRows(): T[] {
336
+ return this._registry.get(this._sortedRows);
337
+ }
338
+
339
+ /** Atom for reactive access to cell changes. */
340
+ public get cellUpdate(): Atom.Atom<number> {
341
+ return this._cellUpdateCounter;
342
+ }
343
+
344
+ /**
345
+ * Change a row using the configured change callback.
346
+ * Use this instead of directly mutating to ensure consistent mutation handling.
347
+ */
348
+ public changeRow(row: T, mutate: (mutableRow: T) => void): void {
349
+ this._change.row(row, mutate);
197
350
  }
198
351
 
199
352
  public get features(): TableFeatures {
@@ -201,28 +354,30 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
201
354
  }
202
355
 
203
356
  /**
204
- * @reactive
357
+ * Gets the current sort state.
358
+ * Priority: in-memory sort (local changes) > persisted sort (from query AST).
205
359
  */
206
- public get sorting(): TableSorting<T> {
207
- return this._sorting;
360
+ public getSorting(): FieldSortType | undefined {
361
+ return this._registry.get(this._sorting);
208
362
  }
209
363
 
210
364
  /**
211
365
  * Gets the row data at the specified display index.
212
366
  */
213
367
  public getRowAt(displayIndex: number): T | undefined {
214
- if (displayIndex < 0 || displayIndex >= this.sorting.sortedRows.value.length) {
368
+ const sortedRows = this._registry.get(this._sortedRows);
369
+ if (displayIndex < 0 || displayIndex >= sortedRows.length) {
215
370
  return undefined;
216
371
  }
217
372
 
218
- return this.sorting.sortedRows.value[displayIndex];
373
+ return sortedRows[displayIndex];
219
374
  }
220
375
 
221
376
  public get pinnedRows(): NonNullable<TableModelProps<T>['pinnedRows']> {
222
377
  return this._pinnedRows;
223
378
  }
224
379
 
225
- public get columnMeta(): ReadonlySignal<DxGridAxisMeta> {
380
+ public get columnMeta(): Atom.Atom<DxGridAxisMeta> {
226
381
  invariant(this._columnMeta);
227
382
  return this._columnMeta;
228
383
  }
@@ -231,11 +386,6 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
231
386
  return this._selection;
232
387
  }
233
388
 
234
- /** @reactive */
235
- public get isViewDirty(): boolean {
236
- return this.sorting.isDirty;
237
- }
238
-
239
389
  public get rowActions(): TableRowAction[] {
240
390
  return this._rowActions;
241
391
  }
@@ -245,18 +395,19 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
245
395
  //
246
396
 
247
397
  protected override async _open(): Promise<void> {
248
- const presentation = this._view.presentation.target ?? (await this._view.presentation.load());
249
- invariant(Obj.instanceOf(Table.Table, presentation));
250
- this._table = presentation;
251
-
398
+ await this._object.view.load();
252
399
  this.initializeColumnMeta();
253
400
  this.initializeEffects();
254
401
  await this._selection.open(this._ctx);
255
402
  }
256
403
 
257
404
  private initializeColumnMeta(): void {
258
- this._columnMeta = computed(() => {
259
- const fields = this._projection?.fields ?? [];
405
+ invariant(this._object.view.target, 'View must be loaded before initializing column meta');
406
+
407
+ // Derive columnMeta from the projection's fields atom - updates when fields change.
408
+ // The projection.fields atom handles subscriptions to view changes internally.
409
+ this._columnMeta = Atom.make((get) => {
410
+ const fields = get(this._projection.fields);
260
411
  const meta = Object.fromEntries(
261
412
  fields.map((field, index: number) => [index, { size: this.table.sizes[field.path] ?? 256, resizeable: true }]),
262
413
  );
@@ -270,40 +421,51 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
270
421
  }
271
422
 
272
423
  private initializeEffects(): void {
273
- const rowOrderWatcher = effect(() => {
274
- touch(this.sorting.sortedRows.value);
424
+ // Subscribe to rows changes to notify row order changed.
425
+ const rowsUnsubscribe = this._registry.subscribe(this._rows, () => {
275
426
  this._onRowOrderChange?.();
276
427
  });
277
- this._ctx.onDispose(rowOrderWatcher);
278
-
279
- /**
280
- * Creates reactive effects for each row in the visible range.
281
- * Subscribes to changes in the visible range, recreating row effects when it changes.
282
- * When a row's data changes, invokes onCellUpdate to notify subscribers and trigger UI updates.
283
- */
284
- const rowEffectManager = effect(() => {
285
- const { start, end } = touch(this._visibleRange.value);
286
- const rowEffects: ReturnType<typeof effect>[] = [];
287
- for (let row = start.row; row <= end.row; row++) {
288
- rowEffects.push(
289
- effect(() => {
290
- const obj = this.sorting.sortedRows.value[row];
291
- this._projection?.fields.forEach((field) => touch(getValue(obj, field.path)));
292
- this._onCellUpdate?.({ row, col: start.col, plane: 'grid' });
293
- }),
294
- );
428
+ this._ctx.onDispose(rowsUnsubscribe);
429
+
430
+ // Track row subscriptions for cleanup.
431
+ const rowSubscriptions = new Map<string, () => void>();
432
+
433
+ // Subscribe to visible range changes to set up row subscriptions.
434
+ const visibleRangeUnsubscribe = this._registry.subscribe(this._visibleRange, () => {
435
+ // Unsubscribe from old row subscriptions.
436
+ for (const [id, unsub] of rowSubscriptions) {
437
+ unsub();
438
+ rowSubscriptions.delete(id);
295
439
  }
296
440
 
297
- return () => rowEffects.forEach((cleanup) => cleanup());
441
+ const { start, end } = this._registry.get(this._visibleRange);
442
+ const sortedRows = this._registry.get(this._sortedRows);
443
+
444
+ // Subscribe to each visible row's changes.
445
+ for (let row = start.row; row <= end.row && row < sortedRows.length; row++) {
446
+ const obj = sortedRows[row];
447
+ if (Obj.isObject(obj) && !rowSubscriptions.has(obj.id)) {
448
+ const unsub = Obj.subscribe(obj, () => {
449
+ // Increment cell update counter to notify UI of changes.
450
+ this._registry.set(this._cellUpdateCounter, this._registry.get(this._cellUpdateCounter) + 1);
451
+ this._onCellUpdate?.({ row, col: start.col, plane: 'grid' });
452
+ });
453
+ rowSubscriptions.set(obj.id, unsub);
454
+ }
455
+ }
456
+ });
457
+ this._ctx.onDispose(() => {
458
+ visibleRangeUnsubscribe();
459
+ for (const unsub of rowSubscriptions.values()) {
460
+ unsub();
461
+ }
298
462
  });
299
- this._ctx.onDispose(rowEffectManager);
300
463
 
301
- const draftRowsWatcher = effect(() => {
302
- touch(this._draftRows.value);
303
- // Notify grid that draft rows have changed
464
+ // Subscribe to draft rows changes to notify grid.
465
+ const draftRowsUnsubscribe = this._registry.subscribe(this._draftRows, () => {
304
466
  this._onRowOrderChange?.();
305
467
  });
306
- this._ctx.onDispose(draftRowsWatcher);
468
+ this._ctx.onDispose(draftRowsUnsubscribe);
307
469
  }
308
470
 
309
471
  //
@@ -311,21 +473,25 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
311
473
  //
312
474
 
313
475
  public setRows = (obj: T[]): void => {
314
- this._rows.value = obj;
476
+ this._registry.set(this._rows, obj);
315
477
  };
316
478
 
317
- public getRowCount = (): number => this._rows.value.length;
479
+ public getRowCount = (): number => this._registry.get(this._sortedRows).length;
318
480
 
319
- /**
320
- * @reactive
321
- */
322
- public getDraftRowCount = (): number => this._draftRows.value.length;
481
+ public getDraftRowCount(): number {
482
+ return this._registry.get(this._draftRows).length;
483
+ }
323
484
 
324
- // TODO(ZaymonFC): Return .value instead of exposing the signal.
325
- public get draftRows(): ReadonlySignal<DraftRow<T>[]> {
485
+ /** Atom for reactive access to draft rows. */
486
+ public get draftRows(): Atom.Atom<DraftRow<T>[]> {
326
487
  return this._draftRows;
327
488
  }
328
489
 
490
+ /** Gets the current draft rows. */
491
+ public getDraftRows(): DraftRow<T>[] {
492
+ return this._registry.get(this._draftRows);
493
+ }
494
+
329
495
  /**
330
496
  * Checks if a specific field path has validation errors for a given draft row.
331
497
  * @param draftRowIndex - The index of the draft row to check
@@ -333,20 +499,20 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
333
499
  * @returns true if the field has validation errors, false otherwise
334
500
  */
335
501
  public hasDraftRowValidationError(draftRowIndex: number, fieldPath: string): boolean {
336
- if (draftRowIndex < 0 || draftRowIndex >= this._draftRows.value.length) {
502
+ if (draftRowIndex < 0 || draftRowIndex >= this._registry.get(this._draftRows).length) {
337
503
  return false;
338
504
  }
339
505
 
340
- const draftRow = this._draftRows.value[draftRowIndex];
506
+ const draftRow = this._registry.get(this._draftRows)[draftRowIndex];
341
507
  const validationErrors = draftRow.validationErrors || [];
342
508
  return validationErrors.some((error) => error.path === fieldPath);
343
509
  }
344
510
 
345
- public getColumnCount = (): number => this._projection?.fields.length ?? 0;
511
+ public getColumnCount = (): number => this._projection?.getFields().length ?? 0;
346
512
 
347
513
  public insertRow = (): InsertRowResult => {
348
514
  const result = this._onInsertRow?.();
349
- if (result === 'draft' && this._draftRows.value.length === 0) {
515
+ if (result === 'draft' && this._registry.get(this._draftRows).length === 0) {
350
516
  this.createDraftRow();
351
517
  }
352
518
  return result ?? 'final';
@@ -367,15 +533,15 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
367
533
  validationErrors,
368
534
  };
369
535
 
370
- this._draftRows.value = [...this._draftRows.value, draftRow];
536
+ this._registry.set(this._draftRows, [...this._registry.get(this._draftRows), draftRow]);
371
537
  }
372
538
 
373
539
  private validateDraftRow(draftRowIndex: number): void {
374
- if (draftRowIndex < 0 || draftRowIndex >= this._draftRows.value.length) {
540
+ if (draftRowIndex < 0 || draftRowIndex >= this._registry.get(this._draftRows).length) {
375
541
  return;
376
542
  }
377
543
 
378
- const draftRow = this._draftRows.value[draftRowIndex];
544
+ const draftRow = this._registry.get(this._draftRows)[draftRowIndex];
379
545
  const validationErrors = this.validateDraftRowData(draftRow.data);
380
546
 
381
547
  const updatedDraftRow = {
@@ -384,9 +550,9 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
384
550
  validationErrors,
385
551
  };
386
552
 
387
- const newDraftRows = [...this._draftRows.value];
553
+ const newDraftRows = [...this._registry.get(this._draftRows)];
388
554
  newDraftRows[draftRowIndex] = updatedDraftRow;
389
- this._draftRows.value = newDraftRows;
555
+ this._registry.set(this._draftRows, newDraftRows);
390
556
  }
391
557
 
392
558
  private validateDraftRowData(data: T): ValidationError[] {
@@ -395,11 +561,11 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
395
561
  }
396
562
 
397
563
  public commitDraftRow = (draftRowIndex: number): boolean => {
398
- if (draftRowIndex < 0 || draftRowIndex >= this._draftRows.value.length) {
564
+ if (draftRowIndex < 0 || draftRowIndex >= this._registry.get(this._draftRows).length) {
399
565
  return false;
400
566
  }
401
567
 
402
- const draftRow = this._draftRows.value[draftRowIndex];
568
+ const draftRow = this._registry.get(this._draftRows)[draftRowIndex];
403
569
  if (!draftRow.valid) {
404
570
  return false;
405
571
  }
@@ -407,26 +573,28 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
407
573
  const insertRowResult = this._onInsertRow?.(draftRow.data);
408
574
 
409
575
  if (insertRowResult === 'final') {
410
- const newDraftRows = this._draftRows.value.filter((_, index) => index !== draftRowIndex);
411
- this._draftRows.value = newDraftRows;
576
+ const newDraftRows = this._registry.get(this._draftRows).filter((_, index) => index !== draftRowIndex);
577
+ this._registry.set(this._draftRows, newDraftRows);
412
578
  }
413
579
 
414
580
  return insertRowResult === 'final';
415
581
  };
416
582
 
417
583
  public deleteRow = (rowIndex: number): void => {
418
- const row = this._sorting.getDataIndex(rowIndex);
419
- const obj = this._rows.value[row];
584
+ const sortedRows = this._registry.get(this._sortedRows);
585
+ const obj = sortedRows[rowIndex];
420
586
  const objectsToDelete = [];
421
587
 
422
- if (this.features.selection.enabled && this._selection.hasSelection.value) {
588
+ if (this.features.selection.enabled && this._selection.hasSelection) {
423
589
  const selectedRows = this._selection.getSelectedRows();
424
590
  objectsToDelete.push(...selectedRows);
425
- } else {
591
+ } else if (obj) {
426
592
  objectsToDelete.push(obj);
427
593
  }
428
594
 
429
- this._onDeleteRows?.(row, objectsToDelete);
595
+ if (objectsToDelete.length > 0) {
596
+ this._onDeleteRows?.(rowIndex, objectsToDelete);
597
+ }
430
598
  };
431
599
 
432
600
  public handleRowAction = (actionId: string, rowIndex: number): void => {
@@ -434,8 +602,8 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
434
602
  return;
435
603
  }
436
604
 
437
- const row = this._sorting.getDataIndex(rowIndex);
438
- const data = this._rows.value[row];
605
+ const sortedRows = this._registry.get(this._sortedRows);
606
+ const data = sortedRows[rowIndex];
439
607
 
440
608
  if (data) {
441
609
  this._onRowAction(actionId, data);
@@ -444,7 +612,7 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
444
612
 
445
613
  public getCellData = (cell: DxGridPosition): any => {
446
614
  const { col, row, plane } = cell;
447
- const fields = this._projection?.fields ?? [];
615
+ const fields = this._projection?.getFields() ?? [];
448
616
  if (col < 0 || col >= fields.length) {
449
617
  return undefined;
450
618
  }
@@ -454,15 +622,15 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
454
622
 
455
623
  if (plane === 'frozenRowsEnd') {
456
624
  // Get data from draft row
457
- if (row >= 0 && row < this._draftRows.value.length) {
458
- value = getValue(this._draftRows.value[row].data, field.path);
625
+ if (row >= 0 && row < this._registry.get(this._draftRows).length) {
626
+ value = getValue(this._registry.get(this._draftRows)[row].data, field.path);
459
627
  } else {
460
628
  return undefined;
461
629
  }
462
630
  } else {
463
- // Get data from regular row
464
- const dataIndex = this._sorting.getDataIndex(row);
465
- value = getValue(this._rows.value[dataIndex], field.path);
631
+ // Get data from regular row (use sorted rows for display index)
632
+ const sortedRows = this._registry.get(this._sortedRows);
633
+ value = getValue(sortedRows[row], field.path);
466
634
  }
467
635
 
468
636
  if (value == null) {
@@ -471,7 +639,7 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
471
639
 
472
640
  const { props } = this._projection.getFieldProjection(field.id);
473
641
  switch (props.format) {
474
- case FormatEnum.Ref: {
642
+ case Format.TypeFormat.Ref: {
475
643
  if (!field.referencePath) {
476
644
  return ''; // TODO(burdon): Show error.
477
645
  }
@@ -480,13 +648,17 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
480
648
  }
481
649
 
482
650
  default: {
483
- return formatForEditing({ type: props.type, format: props.format, value });
651
+ return formatForEditing({
652
+ type: props.type,
653
+ format: props.format,
654
+ value,
655
+ });
484
656
  }
485
657
  }
486
658
  };
487
659
 
488
660
  public validateCellData = async ({ col, row, plane }: DxGridPosition, value: any): Promise<ValidationResult> => {
489
- const fields = this._projection?.fields ?? [];
661
+ const fields = this._projection?.getFields() ?? [];
490
662
  if (col < 0 || col >= fields.length) {
491
663
  return { valid: false, error: 'Invalid column index' };
492
664
  }
@@ -498,12 +670,12 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
498
670
  const isDraftRow = plane === 'frozenRowsEnd';
499
671
 
500
672
  if (isDraftRow) {
501
- const isInvalidDraftRowIndex = row < 0 || row >= this._draftRows.value.length;
673
+ const isInvalidDraftRowIndex = row < 0 || row >= this._registry.get(this._draftRows).length;
502
674
  if (isInvalidDraftRowIndex) {
503
675
  return { valid: false, error: 'Invalid draft row index' };
504
676
  }
505
677
 
506
- const draftRow = this._draftRows.value[row];
678
+ const draftRow = this._registry.get(this._draftRows)[row];
507
679
  const snapshot = { ...draftRow.data };
508
680
  setValue(snapshot, field.path, transformedValue);
509
681
 
@@ -517,14 +689,13 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
517
689
  }
518
690
  return { valid: true };
519
691
  } else {
520
- const rowIdx = this._sorting.getDataIndex(row);
521
- const currentRow = this._rows.value[rowIdx];
692
+ const currentRow = this._registry.get(this._rows)[row];
522
693
  invariant(currentRow, 'Invalid row index');
523
694
 
524
- const snapshot = getSnapshot(currentRow);
695
+ const snapshot = { ...getSnapshot(currentRow) };
525
696
  setValue(snapshot, field.path, transformedValue);
526
697
 
527
- const schema = getSchema(currentRow);
698
+ const schema = Obj.getSchema(currentRow);
528
699
  invariant(schema);
529
700
 
530
701
  const validationResult = validateSchema(schema, snapshot);
@@ -540,7 +711,7 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
540
711
 
541
712
  public setCellData = (cell: DxGridPosition, value: any): void => {
542
713
  const { col, row, plane } = cell;
543
- const fields = this._projection?.fields ?? [];
714
+ const fields = this._projection?.getFields() ?? [];
544
715
  if (col < 0 || col >= fields.length) {
545
716
  return;
546
717
  }
@@ -550,21 +721,24 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
550
721
  const transformedValue = editorTextToCellValue(props, value);
551
722
 
552
723
  // Special handling for Ref format to preserve existing behavior
553
- if (props.format === FormatEnum.Ref && !isLiveObject(value)) {
724
+ if (props.format === Format.TypeFormat.Ref && !Obj.isObject(value)) {
554
725
  return;
555
726
  }
556
727
 
557
728
  if (plane === 'frozenRowsEnd') {
558
- // Update draft row data
559
- if (row >= 0 && row < this._draftRows.value.length) {
560
- setValue(this._draftRows.value[row].data, field.path, transformedValue);
729
+ // Update draft row data (draft rows are plain objects, not ECHO objects).
730
+ if (row >= 0 && row < this._registry.get(this._draftRows).length) {
731
+ setValue(this._registry.get(this._draftRows)[row].data, field.path, transformedValue);
561
732
  // Re-validate the draft row after the update
562
733
  this.validateDraftRow(row);
563
734
  }
564
735
  } else {
565
- // Update regular row data
566
- const rowIdx = this._sorting.getDataIndex(row);
567
- setValue(this._rows.value[rowIdx], field.path, transformedValue);
736
+ // Update regular row data (use sorted rows for display index)
737
+ const sortedRows = this._registry.get(this._sortedRows);
738
+ const rowData = sortedRows[row];
739
+ this._change.row(rowData, (mutableRow) => {
740
+ setValue(mutableRow, field.path, transformedValue);
741
+ });
568
742
  }
569
743
  };
570
744
 
@@ -574,13 +748,16 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
574
748
  * @param {(value: any) => any} update - A function that takes the current value and returns the updated value.
575
749
  */
576
750
  public updateCellData({ col, row }: DxGridPlanePosition, update: (value: any) => any): void {
577
- const dataRow = this._sorting.getDataIndex(row);
578
- const fields = this._projection?.fields ?? [];
751
+ const fields = this._projection?.getFields() ?? [];
579
752
  const field = fields[col];
753
+ const sortedRows = this._registry.get(this._sortedRows);
754
+ const rowData = sortedRows[row];
580
755
 
581
- const value = getValue(this._rows.value[dataRow], field.path);
756
+ const value = getValue(rowData, field.path);
582
757
  const updatedValue = update(value);
583
- setValue(this._rows.value[dataRow], field.path, updatedValue);
758
+ this._change.row(rowData, (mutableRow) => {
759
+ setValue(mutableRow, field.path, updatedValue);
760
+ });
584
761
  }
585
762
 
586
763
  /**
@@ -619,9 +796,9 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
619
796
  return;
620
797
  }
621
798
 
622
- const field = this._projection?.fields.find((field) => field.id === fieldId);
623
- if (field && this._onDeleteColumn) {
624
- this._onDeleteColumn(field.id);
799
+ const field = this._projection?.getFields().find((field) => field.id === fieldId);
800
+ if (field && this._onColumnDelete) {
801
+ this._onColumnDelete(field.id);
625
802
  }
626
803
  }
627
804
 
@@ -630,12 +807,14 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
630
807
  //
631
808
 
632
809
  public setColumnWidth(columnIndex: number, width: number): void {
633
- const fields = this._projection?.fields ?? [];
810
+ const fields = this._projection?.getFields() ?? [];
634
811
  if (columnIndex < fields.length) {
635
812
  const newWidth = Math.max(0, width);
636
813
  const field = fields[columnIndex];
637
814
  if (field) {
638
- this.table.sizes[field.path] = newWidth;
815
+ this._change.table((mutableTable) => {
816
+ mutableTable.sizes[field.path] = newWidth;
817
+ });
639
818
  }
640
819
  }
641
820
  }
@@ -655,25 +834,112 @@ export class TableModel<T extends TableRow = TableRow> extends Resource {
655
834
  }
656
835
 
657
836
  //
658
- // View operations
837
+ // Sort operations
659
838
  //
660
839
 
840
+ /**
841
+ * Sets the sort order for a field in-memory (local to this instance).
842
+ * Use saveView() to persist the sort to the view query.
843
+ */
844
+ public setSort(fieldId: string, direction: QueryAST.OrderDirection): void {
845
+ const field = this._projection.getFields().find((f) => f.id === fieldId);
846
+ if (!field) {
847
+ return;
848
+ }
849
+
850
+ // Update in-memory sort (local changes).
851
+ this._registry.set(this._inMemorySort, {
852
+ fieldId,
853
+ direction,
854
+ });
855
+ }
856
+
857
+ /**
858
+ * Toggles the sort direction for a field in-memory.
859
+ */
860
+ public toggleSort(fieldId: string): void {
861
+ const currentSort = this.getSorting();
862
+ if (!currentSort || currentSort.fieldId !== fieldId) {
863
+ this.setSort(fieldId, 'asc');
864
+ return;
865
+ }
866
+
867
+ const newDirection = currentSort.direction === 'asc' ? 'desc' : 'asc';
868
+ this.setSort(fieldId, newDirection);
869
+ }
870
+
871
+ /**
872
+ * Clears the in-memory sort order.
873
+ */
874
+ public clearSort(): void {
875
+ this._registry.set(this._inMemorySort, undefined);
876
+ }
877
+
878
+ /**
879
+ * Saves the current in-memory sort to the view query AST.
880
+ * This persists the sort so it becomes the default for all viewers.
881
+ */
661
882
  public saveView(): void {
662
- this._sorting.save();
883
+ const view = this.view;
884
+ const inMemorySort = this._registry.get(this._inMemorySort);
885
+
886
+ // Snapshot view before accessing query.ast
887
+ const viewSnapshot = Obj.getSnapshot(view);
888
+ const currentQuery = Query.fromAst(viewSnapshot.query.ast);
889
+ const baseQuery = this._getBaseQuery(currentQuery);
890
+
891
+ if (inMemorySort) {
892
+ // Find the field to get its path
893
+ const field = this._projection.getFields().find((f) => f.id === inMemorySort.fieldId);
894
+ if (field) {
895
+ // Persist sort to view.query.ast
896
+ const newQuery = baseQuery.orderBy(Order.property<any>(field.path as string, inMemorySort.direction));
897
+ Obj.change(view, (v) => {
898
+ v.query.ast = newQuery.ast as Mutable<typeof newQuery.ast>;
899
+ });
900
+ }
901
+ } else {
902
+ // Clear sort from view.query.ast
903
+ Obj.change(view, (v) => {
904
+ v.query.ast = baseQuery.ast as Mutable<typeof baseQuery.ast>;
905
+ });
906
+ }
907
+
908
+ // Clear in-memory sort since it's now persisted.
909
+ this._registry.set(this._inMemorySort, undefined);
910
+ }
911
+
912
+ /**
913
+ * Extracts the base query without order clauses.
914
+ */
915
+ private _getBaseQuery(query: Query.Any): Query.Any {
916
+ const ast = query.ast;
917
+ // If the query has an order clause, extract the inner query
918
+ if (ast.type === 'order') {
919
+ return Query.fromAst(ast.query);
920
+ }
921
+ return query;
922
+ }
923
+
924
+ /**
925
+ * Checks if the view has unsaved changes (in-memory sort differs from persisted sort).
926
+ */
927
+ public getViewDirty(): boolean {
928
+ return this._registry.get(this._viewDirty);
663
929
  }
664
930
  }
665
931
 
666
932
  const editorTextToCellValue = (props: PropertyType, value: any): any => {
667
933
  switch (props.format) {
668
- case FormatEnum.Ref: {
669
- if (isLiveObject(value)) {
934
+ case Format.TypeFormat.Ref: {
935
+ if (Obj.isObject(value)) {
670
936
  return Ref.make(value);
671
937
  } else {
672
938
  return value;
673
939
  }
674
940
  }
675
941
 
676
- case FormatEnum.SingleSelect: {
942
+ case Format.TypeFormat.SingleSelect: {
677
943
  const ids = extractTagIds(value);
678
944
  if (ids && ids.length > 0) {
679
945
  return ids[0];
@@ -682,7 +948,7 @@ const editorTextToCellValue = (props: PropertyType, value: any): any => {
682
948
  }
683
949
  }
684
950
 
685
- case FormatEnum.MultiSelect: {
951
+ case Format.TypeFormat.MultiSelect: {
686
952
  const ids = extractTagIds(value);
687
953
  return ids || value;
688
954
  }