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