@dxos/react-ui-table 0.8.4-main.fd6878d → 0.8.4-staging.60fe92afc8

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