@dxos/react-ui-table 0.8.4-main.dedc0f3 → 0.8.4-main.dfabb4ec29

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