@dxos/react-ui-table 0.8.4-main.f9ba587 → 0.8.4-main.fcfe5033a5

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