@dxos/react-ui-table 0.7.4 → 0.7.5-main.499c70c

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 (90) hide show
  1. package/dist/lib/browser/{chunk-IYCSJDMB.mjs → chunk-AT7O4RAD.mjs} +4 -4
  2. package/dist/lib/browser/{chunk-IYCSJDMB.mjs.map → chunk-AT7O4RAD.mjs.map} +2 -2
  3. package/dist/lib/browser/index.mjs +1398 -1216
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/types/index.mjs +1 -1
  7. package/dist/lib/node/{chunk-MHBMVCFZ.cjs → chunk-YSBXNBDJ.cjs} +6 -6
  8. package/dist/lib/node/{chunk-MHBMVCFZ.cjs.map → chunk-YSBXNBDJ.cjs.map} +2 -2
  9. package/dist/lib/node/index.cjs +1130 -934
  10. package/dist/lib/node/index.cjs.map +4 -4
  11. package/dist/lib/node/meta.json +1 -1
  12. package/dist/lib/node/types/index.cjs +3 -3
  13. package/dist/lib/node/types/index.cjs.map +1 -1
  14. package/dist/lib/node-esm/{chunk-BMWGPXPL.mjs → chunk-6OH2NHUX.mjs} +4 -4
  15. package/dist/lib/node-esm/{chunk-BMWGPXPL.mjs.map → chunk-6OH2NHUX.mjs.map} +2 -2
  16. package/dist/lib/node-esm/index.mjs +1398 -1216
  17. package/dist/lib/node-esm/index.mjs.map +4 -4
  18. package/dist/lib/node-esm/meta.json +1 -1
  19. package/dist/lib/node-esm/types/index.mjs +1 -1
  20. package/dist/types/src/_deprecated/hooks/useColumnSorting.d.ts +1 -1
  21. package/dist/types/src/components/Table/ColumnActionsMenu.d.ts +4 -3
  22. package/dist/types/src/components/Table/ColumnActionsMenu.d.ts.map +1 -1
  23. package/dist/types/src/components/Table/ColumnSettings.d.ts +3 -2
  24. package/dist/types/src/components/Table/ColumnSettings.d.ts.map +1 -1
  25. package/dist/types/src/components/Table/CreateRefPanel.d.ts +3 -2
  26. package/dist/types/src/components/Table/CreateRefPanel.d.ts.map +1 -1
  27. package/dist/types/src/components/Table/RefPanel.d.ts +4 -3
  28. package/dist/types/src/components/Table/RefPanel.d.ts.map +1 -1
  29. package/dist/types/src/components/Table/RowActionsMenu.d.ts +3 -2
  30. package/dist/types/src/components/Table/RowActionsMenu.d.ts.map +1 -1
  31. package/dist/types/src/components/Table/Table.d.ts +2 -1
  32. package/dist/types/src/components/Table/Table.d.ts.map +1 -1
  33. package/dist/types/src/components/Table/Table.stories.d.ts.map +1 -1
  34. package/dist/types/src/components/TableCellEditor/TableCellEditor.d.ts +3 -2
  35. package/dist/types/src/components/TableCellEditor/TableCellEditor.d.ts.map +1 -1
  36. package/dist/types/src/components/TableCellEditor/TableCellEditor.stories.d.ts.map +1 -1
  37. package/dist/types/src/components/testing.d.ts +55 -71
  38. package/dist/types/src/components/testing.d.ts.map +1 -1
  39. package/dist/types/src/index.d.ts +1 -0
  40. package/dist/types/src/index.d.ts.map +1 -1
  41. package/dist/types/src/model/index.d.ts +1 -0
  42. package/dist/types/src/model/index.d.ts.map +1 -1
  43. package/dist/types/src/model/modal-controller.d.ts +6 -2
  44. package/dist/types/src/model/modal-controller.d.ts.map +1 -1
  45. package/dist/types/src/model/selection-model.d.ts.map +1 -1
  46. package/dist/types/src/model/table-model.d.ts +8 -12
  47. package/dist/types/src/model/table-model.d.ts.map +1 -1
  48. package/dist/types/src/model/table-presentation.d.ts +22 -0
  49. package/dist/types/src/model/table-presentation.d.ts.map +1 -0
  50. package/dist/types/src/model/table-presentation.test.d.ts +2 -0
  51. package/dist/types/src/model/table-presentation.test.d.ts.map +1 -0
  52. package/dist/types/src/playwright/TableManager.d.ts +2 -1
  53. package/dist/types/src/playwright/TableManager.d.ts.map +1 -1
  54. package/dist/types/src/types/table.d.ts +118 -154
  55. package/dist/types/src/types/table.d.ts.map +1 -1
  56. package/dist/types/src/util/index.d.ts +1 -0
  57. package/dist/types/src/util/index.d.ts.map +1 -1
  58. package/dist/types/src/util/table-buttons.d.ts +50 -20
  59. package/dist/types/src/util/table-buttons.d.ts.map +1 -1
  60. package/dist/types/src/util/table-controls.d.ts +32 -9
  61. package/dist/types/src/util/table-controls.d.ts.map +1 -1
  62. package/dist/types/src/util/table.d.ts +2 -2
  63. package/dist/types/src/util/table.d.ts.map +1 -1
  64. package/dist/types/tsconfig.tsbuildinfo +1 -0
  65. package/package.json +29 -29
  66. package/src/components/Table/ColumnActionsMenu.tsx +8 -8
  67. package/src/components/Table/ColumnSettings.tsx +11 -11
  68. package/src/components/Table/CreateRefPanel.tsx +10 -10
  69. package/src/components/Table/RefPanel.tsx +9 -9
  70. package/src/components/Table/RowActionsMenu.tsx +6 -7
  71. package/src/components/Table/Table.stories.tsx +40 -23
  72. package/src/components/Table/Table.tsx +235 -148
  73. package/src/components/TableCellEditor/TableCellEditor.stories.tsx +13 -12
  74. package/src/components/TableCellEditor/TableCellEditor.tsx +6 -4
  75. package/src/components/testing.ts +10 -8
  76. package/src/index.ts +2 -0
  77. package/src/model/index.ts +1 -0
  78. package/src/model/modal-controller.ts +15 -48
  79. package/src/model/selection-model.ts +12 -1
  80. package/src/model/table-model.test.ts +4 -71
  81. package/src/model/table-model.ts +59 -232
  82. package/src/model/table-presentation.test.ts +102 -0
  83. package/src/model/table-presentation.ts +214 -0
  84. package/src/playwright/TableManager.ts +5 -1
  85. package/src/playwright/smoke.spec.ts +64 -1
  86. package/src/types/table.ts +3 -3
  87. package/src/util/index.ts +1 -0
  88. package/src/util/table-buttons.ts +97 -48
  89. package/src/util/table-controls.ts +71 -7
  90. package/src/util/table.ts +21 -13
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  TableSchema,
3
3
  TableType
4
- } from "./chunk-IYCSJDMB.mjs";
4
+ } from "./chunk-AT7O4RAD.mjs";
5
5
 
6
6
  // packages/ui/react-ui-table/src/translations.ts
7
7
  var translationKey = "table";
@@ -35,33 +35,33 @@ var translations_default = [
35
35
  ];
36
36
 
37
37
  // packages/ui/react-ui-table/src/components/Table/Table.tsx
38
- import React7, { forwardRef, useCallback as useCallback4, useImperativeHandle, useState as useState2 } from "react";
39
- import { getValue } from "@dxos/echo-schema";
40
- import { invariant as invariant2 } from "@dxos/invariant";
38
+ import React7, { forwardRef, useCallback as useCallback4, useImperativeHandle, useState as useState2, useMemo as useMemo4 } from "react";
39
+ import { getValue as getValue3 } from "@dxos/echo-schema";
40
+ import { invariant as invariant3 } from "@dxos/invariant";
41
41
  import { Filter, getSpace as getSpace4, fullyQualifiedId } from "@dxos/react-client/echo";
42
42
  import { useTranslation as useTranslation3 } from "@dxos/react-ui";
43
43
  import { useAttention } from "@dxos/react-ui-attention";
44
44
  import { Grid, closestCell } from "@dxos/react-ui-grid";
45
- import { mx } from "@dxos/react-ui-theme";
45
+ import { mx as mx2 } from "@dxos/react-ui-theme";
46
46
  import { isNotFalsy } from "@dxos/util";
47
47
 
48
48
  // packages/ui/react-ui-table/src/components/Table/ColumnActionsMenu.tsx
49
49
  import React from "react";
50
50
  import { DropdownMenu, useTranslation } from "@dxos/react-ui";
51
- var ColumnActionsMenu = ({ model }) => {
51
+ var ColumnActionsMenu = ({ model, modals }) => {
52
52
  const { t } = useTranslation(translationKey);
53
- const state = model?.modalController.state.value;
54
- if (!model || state?.type !== "column") {
53
+ const state = modals.state.value;
54
+ if (state?.type !== "column") {
55
55
  return null;
56
56
  }
57
57
  const currentSort = model.sorting;
58
58
  const isCurrentColumnSorted = currentSort?.fieldId === state.fieldId;
59
59
  return /* @__PURE__ */ React.createElement(DropdownMenu.Root, {
60
60
  modal: false,
61
- open: state?.type === "column",
62
- onOpenChange: model.modalController.close
61
+ open: true,
62
+ onOpenChange: modals.close
63
63
  }, /* @__PURE__ */ React.createElement(DropdownMenu.VirtualTrigger, {
64
- virtualRef: model.modalController.trigger
64
+ virtualRef: modals.trigger
65
65
  }), /* @__PURE__ */ React.createElement(DropdownMenu.Portal, null, /* @__PURE__ */ React.createElement(DropdownMenu.Content, null, /* @__PURE__ */ React.createElement(DropdownMenu.Viewport, null, (!isCurrentColumnSorted || currentSort?.direction === "asc") && /* @__PURE__ */ React.createElement(DropdownMenu.Item, {
66
66
  "data-testid": "column-sort-descending",
67
67
  onClick: () => model.setSort(state.fieldId, "desc")
@@ -76,7 +76,7 @@ var ColumnActionsMenu = ({ model }) => {
76
76
  onClick: () => model.deleteColumn(state.fieldId)
77
77
  }, t("column action delete")), /* @__PURE__ */ React.createElement(DropdownMenu.Item, {
78
78
  "data-testid": "column-settings",
79
- onClick: () => model.modalController.openColumnSettings()
79
+ onClick: () => modals.openColumnSettings()
80
80
  }, t("column action settings"))), /* @__PURE__ */ React.createElement(DropdownMenu.Arrow, null))));
81
81
  };
82
82
 
@@ -85,9 +85,9 @@ import React2, { useCallback, useEffect, useMemo, useState } from "react";
85
85
  import { getSpace } from "@dxos/react-client/echo";
86
86
  import { DropdownMenu as DropdownMenu2 } from "@dxos/react-ui";
87
87
  import { FieldEditor } from "@dxos/react-ui-form";
88
- var ColumnSettings = ({ model, onNewColumn }) => {
88
+ var ColumnSettings = ({ model, modals, onNewColumn }) => {
89
89
  const [newField, setNewField] = useState();
90
- const state = model?.modalController.state.value;
90
+ const state = modals.state.value;
91
91
  const space = getSpace(model?.table);
92
92
  useEffect(() => {
93
93
  if (state?.type === "columnSettings" && state.mode.type === "create" && model?.projection) {
@@ -106,19 +106,19 @@ var ColumnSettings = ({ model, onNewColumn }) => {
106
106
  if (state?.type === "columnSettings") {
107
107
  const { mode } = state;
108
108
  if (mode.type === "edit") {
109
- return model?.table?.view?.fields.find((f) => f.id === mode.fieldId);
109
+ return model?.table?.view?.target?.fields.find((f) => f.id === mode.fieldId);
110
110
  }
111
111
  }
112
112
  return void 0;
113
113
  }, [
114
- model?.table?.view?.fields,
114
+ model?.table?.view?.target?.fields,
115
115
  state
116
116
  ]);
117
117
  const field = existingField ?? newField;
118
118
  const handleSave = useCallback(() => {
119
- model?.modalController.close();
119
+ modals.close();
120
120
  }, [
121
- model?.modalController
121
+ modals
122
122
  ]);
123
123
  const handleCancel = useCallback(() => {
124
124
  if (state?.type === "columnSettings" && state.mode.type === "create" && newField) {
@@ -129,18 +129,18 @@ var ColumnSettings = ({ model, onNewColumn }) => {
129
129
  state,
130
130
  newField
131
131
  ]);
132
- if (!model?.table?.view || !model.projection || !field) {
132
+ if (!model?.table?.view?.target || !model.projection || !field) {
133
133
  return null;
134
134
  }
135
135
  return /* @__PURE__ */ React2.createElement(DropdownMenu2.Root, {
136
136
  modal: false,
137
137
  open: state?.type === "columnSettings"
138
138
  }, /* @__PURE__ */ React2.createElement(DropdownMenu2.VirtualTrigger, {
139
- virtualRef: model.modalController.trigger
139
+ virtualRef: modals.trigger
140
140
  }), /* @__PURE__ */ React2.createElement(DropdownMenu2.Portal, null, /* @__PURE__ */ React2.createElement(DropdownMenu2.Content, {
141
141
  classNames: "md:is-64"
142
142
  }, /* @__PURE__ */ React2.createElement(DropdownMenu2.Viewport, null, /* @__PURE__ */ React2.createElement(FieldEditor, {
143
- view: model.table.view,
143
+ view: model.table.view.target,
144
144
  projection: model.projection,
145
145
  field,
146
146
  registry: space?.db.schemaRegistry,
@@ -156,10 +156,10 @@ import { create, getSpace as getSpace2 } from "@dxos/react-client/echo";
156
156
  import { Popover } from "@dxos/react-ui";
157
157
  import { Form } from "@dxos/react-ui-form";
158
158
  import { useGridContext } from "@dxos/react-ui-grid";
159
- var CreateRefPanel = ({ model, __gridScope }) => {
159
+ var CreateRefPanel = ({ model, modals, __gridScope }) => {
160
160
  const { id: gridId } = useGridContext("TableCellEditor", __gridScope);
161
161
  const space = getSpace2(model?.table);
162
- const state = model?.modalController.state.value;
162
+ const state = modals.state.value;
163
163
  const schema = useMemo2(() => {
164
164
  if (!space || state?.type !== "createRefPanel") {
165
165
  return;
@@ -182,18 +182,18 @@ var CreateRefPanel = ({ model, __gridScope }) => {
182
182
  const obj = space.db.add(create(schema2, values));
183
183
  state.onCreate?.(obj);
184
184
  }
185
- void model.modalController.close();
185
+ void modals.close();
186
186
  }, [
187
- model?.modalController,
187
+ modals,
188
188
  space,
189
189
  state
190
190
  ]);
191
191
  const handleCancel = useCallback2(() => {
192
192
  if (model) {
193
- model.modalController.close();
193
+ modals.close();
194
194
  }
195
195
  }, [
196
- model?.modalController
196
+ modals
197
197
  ]);
198
198
  if (!model?.table?.view || !model.projection) {
199
199
  return null;
@@ -203,11 +203,11 @@ var CreateRefPanel = ({ model, __gridScope }) => {
203
203
  open: state?.type === "createRefPanel" && !!schema,
204
204
  onOpenChange: (nextOpen) => {
205
205
  if (model && !nextOpen) {
206
- return model.modalController.close();
206
+ return modals.close();
207
207
  }
208
208
  }
209
209
  }, /* @__PURE__ */ React3.createElement(Popover.VirtualTrigger, {
210
- virtualRef: model.modalController.trigger
210
+ virtualRef: modals.trigger
211
211
  }), /* @__PURE__ */ React3.createElement(Popover.Portal, null, /* @__PURE__ */ React3.createElement(Popover.Content, {
212
212
  classNames: "md:is-64",
213
213
  "data-grid": gridId
@@ -231,24 +231,24 @@ var getRefTargetObj = (space, id) => {
231
231
  return void 0;
232
232
  }
233
233
  };
234
- var RefPanel = ({ model }) => {
235
- const state = model?.modalController.state.value;
236
- const space = getSpace3(model?.table);
234
+ var RefPanel = ({ model, modals }) => {
235
+ const state = modals.state.value;
236
+ const space = getSpace3(model.table);
237
237
  const targetObj = getRefTargetObj(space, state?.type === "refPanel" ? state.targetId : void 0);
238
238
  const schema = space && state?.type === "refPanel" ? space.db.schemaRegistry.getSchema(state.typename) : void 0;
239
- if (!model?.table?.view || !model.projection) {
239
+ if (!model.table?.view || !model.projection) {
240
240
  return null;
241
241
  }
242
242
  return /* @__PURE__ */ React4.createElement(Popover2.Root, {
243
243
  modal: false,
244
244
  open: state?.type === "refPanel" && !!targetObj && !!schema,
245
245
  onOpenChange: (nextOpen) => {
246
- if (model && !nextOpen) {
247
- return model.modalController.close();
246
+ if (!nextOpen) {
247
+ return modals.close();
248
248
  }
249
249
  }
250
250
  }, /* @__PURE__ */ React4.createElement(Popover2.VirtualTrigger, {
251
- virtualRef: model.modalController.trigger
251
+ virtualRef: modals.trigger
252
252
  }), /* @__PURE__ */ React4.createElement(Popover2.Portal, null, /* @__PURE__ */ React4.createElement(Popover2.Content, {
253
253
  classNames: "md:is-64"
254
254
  }, targetObj && schema && /* @__PURE__ */ React4.createElement(Form2, {
@@ -261,691 +261,700 @@ var RefPanel = ({ model }) => {
261
261
  // packages/ui/react-ui-table/src/components/Table/RowActionsMenu.tsx
262
262
  import React5 from "react";
263
263
  import { DropdownMenu as DropdownMenu3, useTranslation as useTranslation2 } from "@dxos/react-ui";
264
- var RowActionsMenu = ({ model }) => {
264
+ var RowActionsMenu = ({ model, modals }) => {
265
265
  const { t } = useTranslation2(translationKey);
266
266
  const hasSelection = model.selection.hasSelection.value;
267
- const state = model.modalController.state.value;
267
+ const state = modals.state.value;
268
268
  if (state?.type !== "row") {
269
269
  return null;
270
270
  }
271
271
  return /* @__PURE__ */ React5.createElement(DropdownMenu3.Root, {
272
272
  modal: false,
273
273
  open: true,
274
- onOpenChange: model.modalController.close
274
+ onOpenChange: modals.close
275
275
  }, /* @__PURE__ */ React5.createElement(DropdownMenu3.VirtualTrigger, {
276
- virtualRef: model.modalController.trigger
276
+ virtualRef: modals.trigger
277
277
  }), /* @__PURE__ */ React5.createElement(DropdownMenu3.Content, null, /* @__PURE__ */ React5.createElement(DropdownMenu3.Viewport, null, /* @__PURE__ */ React5.createElement(DropdownMenu3.Item, {
278
278
  "data-testid": "row-menu-delete",
279
279
  onClick: () => model.deleteRow(state.rowIndex)
280
280
  }, t(hasSelection ? "bulk delete row label" : "delete row label"))), /* @__PURE__ */ React5.createElement(DropdownMenu3.Arrow, null)));
281
281
  };
282
282
 
283
- // packages/ui/react-ui-table/src/components/TableCellEditor/TableCellEditor.tsx
284
- import React6, { useCallback as useCallback3, useMemo as useMemo3, useRef } from "react";
285
- import { FormatEnum } from "@dxos/echo-schema";
283
+ // packages/ui/react-ui-table/src/model/table-model.ts
284
+ import { computed as computed2, effect as effect2, signal as signal2 } from "@preact/signals-core";
285
+ import orderBy from "lodash.orderby";
286
+ import { Resource as Resource2 } from "@dxos/context";
287
+ import { getValue, setValue, FormatEnum as FormatEnum2 } from "@dxos/echo-schema";
286
288
  import { invariant } from "@dxos/invariant";
287
- import { cellQuery, editorKeys, parseCellIndex, useGridContext as useGridContext2, GridCellEditor } from "@dxos/react-ui-grid";
289
+ import { isReactiveObject, makeRef as makeRef2 } from "@dxos/live-object";
290
+ import { PublicKey as PublicKey2 } from "@dxos/react-client";
291
+ import { formatForDisplay, formatForEditing, parseValue } from "@dxos/react-ui-form";
288
292
 
289
- // packages/ui/react-ui-table/src/components/TableCellEditor/extension.ts
290
- import { autocompletion, pickedCompletion } from "@codemirror/autocomplete";
291
- import { EditorView } from "@codemirror/view";
292
- var completion = ({ debug, onQuery, onMatch }) => {
293
- return [
294
- EditorView.theme({
295
- ".cm-completionDialog": {
296
- width: "var(--dx-gridCellWidth)"
297
- }
298
- }),
299
- autocompletion({
300
- icons: false,
301
- activateOnTyping: true,
302
- closeOnBlur: !debug,
303
- override: [
304
- async (context) => {
305
- const text = context.state.doc.toString();
306
- return {
307
- from: 0,
308
- options: await onQuery(text)
309
- };
310
- }
311
- ],
312
- // TODO(burdon): Consts from grid (to line-up with grid).
313
- tooltipClass: () => "cm-completionDialog !mt-[8px] !-ml-[4px] [&>ul]:!max-h-[264px]",
314
- optionClass: () => "flex h-[33px] items-center"
293
+ // packages/ui/react-ui-table/src/model/selection-model.ts
294
+ import { computed, effect, signal } from "@preact/signals-core";
295
+ import { Resource } from "@dxos/context";
296
+
297
+ // packages/ui/react-ui-table/src/util/signals.ts
298
+ var touch = (value) => value;
299
+
300
+ // packages/ui/react-ui-table/src/util/table.ts
301
+ import { AST, Format, FormatEnum, S as S2, TypedObject, TypeEnum } from "@dxos/echo-schema";
302
+ import { log } from "@dxos/log";
303
+ import { PublicKey } from "@dxos/react-client";
304
+ import { create as create2, makeRef } from "@dxos/react-client/echo";
305
+ import { createFieldId, createView, ViewProjection } from "@dxos/schema";
306
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/ui/react-ui-table/src/util/table.ts";
307
+ var initializeTable = async ({ space, table, initialRow = true }) => {
308
+ log("initializeTable", {
309
+ table
310
+ }, {
311
+ F: __dxlog_file,
312
+ L: 36,
313
+ S: void 0,
314
+ C: (f, a) => f(...a)
315
+ });
316
+ const ContactSchema = TypedObject({
317
+ typename: `example.com/type/${PublicKey.random().truncate()}`,
318
+ version: "0.1.0"
319
+ })({
320
+ name: S2.optional(S2.String).annotations({
321
+ [AST.TitleAnnotationId]: "Name"
315
322
  }),
316
- // Check for accepted completion metadata in the transaction.
317
- EditorView.updateListener.of((update) => {
318
- update.transactions.forEach((tr) => {
319
- const completion2 = tr.annotation(pickedCompletion);
320
- if (completion2) {
321
- onMatch(completion2.data);
322
- }
323
- });
323
+ active: S2.optional(S2.Boolean),
324
+ email: S2.optional(Format.Email),
325
+ salary: S2.optional(Format.Currency()).annotations({
326
+ [AST.TitleAnnotationId]: "Salary"
324
327
  })
325
- ];
326
- };
327
-
328
- // packages/ui/react-ui-table/src/components/TableCellEditor/TableCellEditor.tsx
329
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/ui/react-ui-table/src/components/TableCellEditor/TableCellEditor.tsx";
330
- var newValue = Symbol.for("newValue");
331
- var createOption = (text) => ({
332
- [newValue]: true,
333
- text
334
- });
335
- var isCreateOption = (data) => typeof data === "object" && data[newValue];
336
- var TableCellEditor = ({ model, onEnter, onFocus, onQuery, __gridScope }) => {
337
- const { id: gridId, editing, setEditing } = useGridContext2("TableCellEditor", __gridScope);
338
- const suppressNextBlur = useRef(false);
339
- const fieldProjection = useMemo3(() => {
340
- if (!model || !editing) {
341
- return;
342
- }
343
- const { col } = parseCellIndex(editing.index);
344
- const field = model.projection.view.fields[col];
345
- const fieldProjection2 = model.projection.getFieldProjection(field.id);
346
- invariant(fieldProjection2, void 0, {
347
- F: __dxlog_file,
348
- L: 65,
349
- S: void 0,
350
- A: [
351
- "fieldProjection",
352
- ""
353
- ]
354
- });
355
- return fieldProjection2;
356
- }, [
357
- model,
358
- editing
359
- ]);
360
- const handleEnter = useCallback3((value) => {
361
- if (!model || !editing) {
362
- return;
363
- }
364
- const cell = parseCellIndex(editing.index);
365
- model.setCellData(cell, value);
366
- onEnter?.(cell);
367
- onFocus?.();
368
- setEditing(null);
369
- }, [
370
- model,
371
- editing
372
- ]);
373
- const handleBlur = useCallback3((value) => {
374
- if (!model || !editing) {
375
- return;
376
- }
377
- if (suppressNextBlur.current) {
378
- suppressNextBlur.current = false;
379
- return;
380
- }
381
- const cell = parseCellIndex(editing.index);
382
- if (value !== void 0) {
383
- model.setCellData(cell, value);
384
- }
385
- }, [
386
- model,
387
- editing
388
- ]);
389
- const handleClose = useCallback3((value, event) => {
390
- if (!model || !editing || !fieldProjection) {
391
- return;
392
- }
393
- const cell = parseCellIndex(editing.index);
394
- onEnter?.(cell);
395
- if (event && onFocus) {
396
- onFocus(determineNavigationAxis(event), determineNavigationDelta(event));
397
- }
398
- }, [
399
- model,
400
- editing,
401
- onFocus,
402
- onEnter,
403
- fieldProjection,
404
- determineNavigationAxis,
405
- determineNavigationDelta
406
- ]);
407
- const extension = useMemo3(() => {
408
- if (!fieldProjection) {
409
- return [];
410
- }
411
- const extension2 = [
412
- editorKeys({
413
- onClose: handleClose,
414
- ...editing?.initialContent && {
415
- onNav: handleClose
416
- }
417
- })
418
- ];
419
- if (onQuery) {
420
- switch (fieldProjection.props.format) {
421
- case FormatEnum.Ref: {
422
- extension2.push([
423
- completion({
424
- onQuery: (text) => onQuery(fieldProjection, text),
425
- onMatch: (data) => {
426
- if (model && editing) {
427
- if (isCreateOption(data)) {
428
- const { field, props } = fieldProjection;
429
- if (props.referenceSchema) {
430
- suppressNextBlur.current = true;
431
- model.modalController.openCreateRef(props.referenceSchema, document.querySelector(cellQuery(editing.index, gridId)), {
432
- [field.referencePath]: data.text
433
- }, (data2) => {
434
- handleEnter(data2);
435
- });
436
- }
437
- } else {
438
- handleEnter(data);
439
- }
440
- }
441
- }
442
- })
443
- ]);
444
- break;
445
- }
446
- }
447
- }
448
- return extension2;
449
- }, [
450
- model,
451
- editing,
452
- fieldProjection,
453
- handleClose
328
+ });
329
+ const [contactSchema] = await space.db.schemaRegistry.register([
330
+ ContactSchema
454
331
  ]);
455
- const getCellContent = useCallback3(() => {
456
- if (model && editing) {
457
- const value = model.getCellData(parseCellIndex(editing.index));
458
- return value !== void 0 ? String(value) : "";
332
+ table.view = makeRef(createView({
333
+ name: "Test",
334
+ typename: contactSchema.typename,
335
+ jsonSchema: contactSchema.jsonSchema,
336
+ fields: [
337
+ "name",
338
+ "active",
339
+ "email",
340
+ "salary"
341
+ ]
342
+ }));
343
+ const projection = new ViewProjection(contactSchema, table.view.target);
344
+ projection.setFieldProjection({
345
+ field: {
346
+ id: table.view.target.fields.find((f) => f.path === "salary").id,
347
+ path: "salary",
348
+ size: 150
459
349
  }
460
- }, [
461
- model,
462
- editing
463
- ]);
464
- return /* @__PURE__ */ React6.createElement(GridCellEditor, {
465
- extension,
466
- getCellContent,
467
- onBlur: handleBlur
468
350
  });
469
- };
470
- var determineNavigationAxis = ({ key }) => {
471
- switch (key) {
472
- case "ArrowUp":
473
- case "ArrowDown":
474
- case "Enter": {
475
- return "row";
351
+ projection.setFieldProjection({
352
+ field: {
353
+ id: createFieldId(),
354
+ path: "manager",
355
+ referencePath: "name"
356
+ },
357
+ props: {
358
+ property: "manager",
359
+ type: TypeEnum.Ref,
360
+ format: FormatEnum.Ref,
361
+ referenceSchema: contactSchema.typename,
362
+ title: "Manager"
476
363
  }
477
- case "ArrowLeft":
478
- case "ArrowRight":
479
- case "Tab":
480
- return "col";
481
- }
482
- };
483
- var determineNavigationDelta = ({ key, shift }) => {
484
- switch (key) {
485
- case "ArrowUp":
486
- case "ArrowLeft":
487
- return -1;
488
- case "ArrowDown":
489
- case "ArrowRight":
490
- return 1;
364
+ });
365
+ if (initialRow) {
366
+ space.db.add(create2(contactSchema, {}));
491
367
  }
492
- return shift ? -1 : 1;
368
+ return contactSchema;
493
369
  };
494
370
 
495
- // packages/ui/react-ui-table/src/components/Table/Table.tsx
496
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-table/src/components/Table/Table.tsx";
497
- var inlineEndLine = "[&>.dx-grid]:relative [&>.dx-grid]:after:absolute [&>.dx-grid]:after:inset-block-0 [&>.dx-grid]:after:-inline-end-px [&>.dx-grid]:after:is-px [&>.dx-grid]:after:bg-separator";
498
- var blockEndLine = "[&>.dx-grid]:before:absolute [&>.dx-grid]:before:inset-inline-0 [&>.dx-grid]:before:-block-end-px [&>.dx-grid]:before:bs-px [&>.dx-grid]:before:bg-separator";
499
- var frozen = {
500
- frozenRowsStart: 1,
501
- frozenColsStart: 1,
502
- frozenColsEnd: 1
371
+ // packages/ui/react-ui-table/src/util/table-buttons.ts
372
+ var BUTTON_IDENTIFIERS = {
373
+ columnSettings: "data-table-column-settings-button",
374
+ newColumn: "data-table-new-column-button",
375
+ referencedCell: "data-table-ref-cell-button",
376
+ rowMenu: "data-table-row-menu-button"
503
377
  };
504
- var TableRoot = ({ children, role }) => {
505
- return /* @__PURE__ */ React7.createElement("div", {
506
- role: "none",
507
- className: mx("relative border-bs !border-separator", role === "section" ? "attention-surface overflow-hidden [&_.dx-grid]:max-is-[--dx-grid-content-inline-size]" : "flex flex-col [&_.dx-grid]:grow [&_.dx-grid]:max-is-[--dx-grid-content-inline-size] [&_.dx-grid]:bs-0 [&_.dx-grid]:max-bs-[--dx-grid-content-block-size]")
508
- }, children);
378
+ var createButton = ({ attr, data, disabled = false, icon, testId }) => {
379
+ const dataAttrs = Object.entries(data).map(([k, v]) => `${k}="${v}"`).join(" ");
380
+ return `<button ${attr} data-testid="${testId}" class="ch-button is-6 pli-0.5 min-bs-0 absolute inset-block-1 inline-end-2" ${dataAttrs} ${disabled ? "disabled" : ""}><svg><use href="/icons.svg#${icon}"/></svg></button>`;
509
381
  };
510
- var TableMain = /* @__PURE__ */ forwardRef(({ model, ignoreAttention }, forwardedRef) => {
511
- const [dxGrid, setDxGrid] = useState2(null);
512
- const { hasAttention } = useAttention(model?.table ? fullyQualifiedId(model.table) : "table");
513
- const { t } = useTranslation3(translationKey);
514
- useImperativeHandle(forwardedRef, () => {
515
- if (!model || !dxGrid) {
516
- return {};
517
- }
518
- dxGrid.getCells = model.getCells.bind(model);
519
- return {
520
- update: (cell) => {
521
- if (cell) {
522
- dxGrid.updateIfWithinBounds(cell);
523
- } else {
524
- dxGrid.updateCells(true);
525
- }
526
- }
527
- };
528
- }, [
529
- model,
530
- dxGrid
531
- ]);
532
- const handleFocus = useCallback4((increment, delta) => {
533
- if (dxGrid) {
534
- dxGrid.refocus(increment, delta);
535
- }
536
- }, [
537
- dxGrid
538
- ]);
539
- const handleEnter = useCallback4((cell) => {
540
- if (model && cell.row === model.getRowCount() - 1) {
541
- model.insertRow(cell.row);
542
- if (dxGrid) {
543
- requestAnimationFrame(() => {
544
- dxGrid?.scrollToRow(cell.row + 1);
545
- dxGrid?.refocus("row", 1);
546
- });
547
- }
548
- }
549
- }, [
550
- model,
551
- dxGrid
552
- ]);
553
- const handleKeyDown = useCallback4((event) => {
554
- const cell = closestCell(event.target);
555
- if (!model || !cell) {
556
- return;
557
- }
558
- switch (event.key) {
559
- case "Backspace":
560
- case "Delete": {
561
- model.setCellData(cell, void 0);
562
- break;
563
- }
564
- }
565
- }, [
566
- model
567
- ]);
568
- const handleAxisResize = useCallback4((event) => {
569
- if (event.axis === "col") {
570
- const columnIndex = parseInt(event.index, 10);
571
- model?.setColumnWidth(columnIndex, event.size);
572
- }
573
- }, [
574
- model
575
- ]);
576
- const handleWheel = useCallback4((event) => {
577
- if (!ignoreAttention && !hasAttention) {
578
- event.stopPropagation();
579
- }
580
- }, [
581
- hasAttention,
582
- ignoreAttention
583
- ]);
584
- const handleNewColumn = useCallback4(() => {
585
- const columns = model?.getColumnCount();
586
- if (dxGrid && columns) {
587
- dxGrid.scrollToColumn(columns - 1);
588
- }
589
- }, [
590
- model,
591
- dxGrid
592
- ]);
593
- const handleQuery = useCallback4(async ({ field, props }, text) => {
594
- if (model && props.referenceSchema && field.referencePath) {
595
- const space = getSpace4(model.table);
596
- invariant2(space, void 0, {
597
- F: __dxlog_file2,
598
- L: 180,
599
- S: void 0,
600
- A: [
601
- "space",
602
- ""
603
- ]
604
- });
605
- const schema = space.db.schemaRegistry.getSchema(props.referenceSchema);
606
- if (schema) {
607
- const { objects } = await space.db.query(Filter.schema(schema)).run();
608
- const options = objects.map((obj) => {
609
- const value = getValue(obj, field.referencePath);
610
- if (!value || typeof value !== "string") {
611
- return void 0;
612
- }
613
- return {
614
- label: value,
615
- data: obj
616
- };
617
- }).filter(isNotFalsy);
618
- return [
619
- ...options,
620
- {
621
- label: t("create new object label", {
622
- text
623
- }),
624
- data: createOption(text)
625
- }
626
- ];
627
- }
628
- }
629
- return [];
630
- }, [
631
- model
632
- ]);
633
- if (!model) {
634
- return /* @__PURE__ */ React7.createElement("span", {
635
- role: "none",
636
- className: "attention-surface"
382
+ var addColumnButton = {
383
+ attr: BUTTON_IDENTIFIERS.newColumn,
384
+ icon: "ph--plus--regular",
385
+ render: ({ disabled }) => {
386
+ return createButton({
387
+ attr: BUTTON_IDENTIFIERS.newColumn,
388
+ icon: addColumnButton.icon,
389
+ disabled,
390
+ data: {},
391
+ testId: "table-new-column-button"
637
392
  });
638
- }
639
- return /* @__PURE__ */ React7.createElement(Grid.Root, {
640
- id: model.table.id ?? "table-grid"
641
- }, /* @__PURE__ */ React7.createElement(TableCellEditor, {
642
- model,
643
- onEnter: handleEnter,
644
- onFocus: handleFocus,
645
- onQuery: handleQuery
646
- }), /* @__PURE__ */ React7.createElement(Grid.Content, {
647
- onWheelCapture: handleWheel,
648
- className: mx("[--dx-grid-base:var(--surface-bg)]", inlineEndLine, blockEndLine),
649
- frozen,
650
- columns: model.columnMeta.value,
651
- limitRows: model.getRowCount() ?? 0,
652
- limitColumns: model.table.view?.fields?.length ?? 0,
653
- onAxisResize: handleAxisResize,
654
- onClick: model?.handleGridClick,
655
- onKeyDown: handleKeyDown,
656
- overscroll: "trap",
657
- ref: setDxGrid
658
- }), /* @__PURE__ */ React7.createElement(RowActionsMenu, {
659
- model
660
- }), /* @__PURE__ */ React7.createElement(ColumnActionsMenu, {
661
- model
662
- }), /* @__PURE__ */ React7.createElement(ColumnSettings, {
663
- model,
664
- onNewColumn: handleNewColumn
665
- }), /* @__PURE__ */ React7.createElement(RefPanel, {
666
- model
667
- }), /* @__PURE__ */ React7.createElement(CreateRefPanel, {
668
- model
669
- }));
670
- });
671
- var Table = {
672
- Root: TableRoot,
673
- Main: TableMain
393
+ },
394
+ getData: (_el) => ({
395
+ type: "newColumn"
396
+ })
674
397
  };
675
-
676
- // packages/ui/react-ui-table/src/components/Toolbar/Toolbar.tsx
677
- import { createContext } from "@radix-ui/react-context";
678
- import React9 from "react";
679
- import { Toolbar as NaturalToolbar2, useTranslation as useTranslation4 } from "@dxos/react-ui";
680
-
681
- // packages/ui/react-ui-table/src/components/Toolbar/common.tsx
682
- import React8 from "react";
683
- import { Icon, Toolbar as NaturalToolbar, Tooltip } from "@dxos/react-ui";
684
- var buttonStyles = "min-bs-0 p-2";
685
- var tooltipProps = {
686
- side: "top",
687
- classNames: "z-10"
398
+ var columnSettingsButton = {
399
+ attr: BUTTON_IDENTIFIERS.columnSettings,
400
+ icon: "ph--caret-down--regular",
401
+ render: ({ fieldId }) => {
402
+ return createButton({
403
+ attr: BUTTON_IDENTIFIERS.columnSettings,
404
+ icon: columnSettingsButton.icon,
405
+ data: {
406
+ "data-field-id": fieldId
407
+ },
408
+ testId: "table-column-settings-button"
409
+ });
410
+ },
411
+ getData: (el) => ({
412
+ type: "columnSettings",
413
+ fieldId: el.getAttribute("data-field-id")
414
+ })
688
415
  };
689
- var ToolbarSeparator = () => /* @__PURE__ */ React8.createElement("div", {
690
- role: "separator",
691
- className: "grow"
692
- });
693
- var ToolbarButton = ({ icon, children, ...props }) => {
694
- return /* @__PURE__ */ React8.createElement(Tooltip.Root, null, /* @__PURE__ */ React8.createElement(Tooltip.Trigger, {
695
- asChild: true
696
- }, /* @__PURE__ */ React8.createElement(NaturalToolbar.Button, {
697
- variant: "ghost",
698
- ...props,
699
- classNames: buttonStyles
700
- }, /* @__PURE__ */ React8.createElement(Icon, {
701
- icon,
702
- size: 5
703
- }), /* @__PURE__ */ React8.createElement("span", {
704
- className: "sr-only"
705
- }, children))), /* @__PURE__ */ React8.createElement(Tooltip.Portal, null, /* @__PURE__ */ React8.createElement(Tooltip.Content, tooltipProps, children, /* @__PURE__ */ React8.createElement(Tooltip.Arrow, null))));
416
+ var referencedCellButton = {
417
+ attr: BUTTON_IDENTIFIERS.referencedCell,
418
+ icon: "ph--link-simple-horizontal--regular",
419
+ render: ({ targetId, schemaId }) => {
420
+ return createButton({
421
+ attr: BUTTON_IDENTIFIERS.referencedCell,
422
+ icon: referencedCellButton.icon,
423
+ data: {
424
+ "data-target-id": targetId,
425
+ "data-schema-id": schemaId
426
+ },
427
+ testId: "table-ref-cell-button"
428
+ });
429
+ },
430
+ getData: (el) => ({
431
+ type: "referencedCell",
432
+ targetId: el.getAttribute("data-target-id"),
433
+ schemaId: el.getAttribute("data-schema-id")
434
+ })
435
+ };
436
+ var rowMenuButton = {
437
+ attr: BUTTON_IDENTIFIERS.rowMenu,
438
+ icon: "ph--dots-three--regular",
439
+ render: ({ rowIndex }) => {
440
+ return createButton({
441
+ attr: BUTTON_IDENTIFIERS.rowMenu,
442
+ icon: rowMenuButton.icon,
443
+ data: {
444
+ "data-row-index": rowIndex.toString()
445
+ },
446
+ testId: "table-row-menu-button"
447
+ });
448
+ },
449
+ getData: (el) => ({
450
+ type: "rowMenu",
451
+ rowIndex: Number(el.getAttribute("data-row-index"))
452
+ })
453
+ };
454
+ var tableButtons = {
455
+ addColumn: addColumnButton,
456
+ columnSettings: columnSettingsButton,
457
+ referencedCell: referencedCellButton,
458
+ rowMenu: rowMenuButton
706
459
  };
707
460
 
708
- // packages/ui/react-ui-table/src/components/Toolbar/Toolbar.tsx
709
- var [ToolbarContextProvider, useToolbarContext] = createContext("Toolbar");
710
- var ToolbarRoot = ({ classNames, children, onAction }) => {
711
- return /* @__PURE__ */ React9.createElement(ToolbarContextProvider, {
712
- onAction
713
- }, /* @__PURE__ */ React9.createElement(NaturalToolbar2.Root, {
714
- classNames: [
715
- "is-full shrink-0 overflow-x-auto overflow-y-hidden p-1 attention-surface",
716
- classNames
717
- ]
718
- }, children));
461
+ // packages/ui/react-ui-table/src/util/table-controls.ts
462
+ var CONTROL_IDENTIFIERS = {
463
+ checkbox: "data-table-checkbox",
464
+ switch: "data-table-switch"
719
465
  };
720
- var Editing = () => {
721
- const { onAction } = useToolbarContext("Editing");
722
- const { t } = useTranslation4(translationKey);
723
- return /* @__PURE__ */ React9.createElement(React9.Fragment, null, /* @__PURE__ */ React9.createElement(ToolbarButton, {
724
- value: "add-row",
725
- icon: "ph--plus--regular",
726
- "data-testid": "table.toolbar.add-row",
727
- onClick: () => onAction?.({
728
- type: "add-row"
729
- })
730
- }, t("add row")));
466
+ var BASE_CLASSES = {
467
+ checkbox: "absolute inset-block-[.375rem] inline-end-[.375rem] ch-checkbox",
468
+ switch: "absolute inset-block-[.25rem] inline-end-[.25rem] ch-checkbox--switch"
731
469
  };
732
- var Actions = () => {
733
- const { onAction } = useToolbarContext("Actions");
734
- const { t } = useTranslation4(translationKey);
735
- return /* @__PURE__ */ React9.createElement(React9.Fragment, null, /* @__PURE__ */ React9.createElement(ToolbarButton, {
736
- value: "comment",
737
- icon: "ph--chat-text--regular",
738
- "data-testid": "table.toolbar.comment",
739
- onClick: () => onAction?.({
740
- type: "comment"
741
- })
742
- }, t("create comment")));
470
+ var renderAttributes = (data) => {
471
+ return Object.entries(data).map(([k, v]) => `${k}="${v}"`).join(" ");
743
472
  };
744
- var Toolbar = {
745
- Root: ToolbarRoot,
746
- Editing,
747
- Actions,
748
- Separator: ToolbarSeparator
473
+ var renderInput = (baseClass, attrs, checked = false, disabled = false, preventToggle = false, testId) => {
474
+ return `<input type="checkbox" class="${baseClass}" ${renderAttributes(attrs)} ${checked ? "checked" : ""} ${preventToggle ? 'onclick="return false"' : ""} ${disabled ? "disabled" : ""} data-testid="${testId}"/>`;
475
+ };
476
+ var renderCheckbox = ({ rowIndex, header = false, checked = false, disabled = false }) => {
477
+ const attrs = {
478
+ [CONTROL_IDENTIFIERS.checkbox]: "",
479
+ "data-row-index": rowIndex.toString(),
480
+ ...header && {
481
+ "data-header": ""
482
+ }
483
+ };
484
+ return renderInput(BASE_CLASSES.checkbox, attrs, checked, disabled, true, "table-selection");
485
+ };
486
+ var renderSwitch = ({ colIndex, rowIndex, checked = false, disabled = false }) => {
487
+ const attrs = {
488
+ [CONTROL_IDENTIFIERS.switch]: "",
489
+ "data-row-index": rowIndex.toString(),
490
+ "data-col-index": colIndex.toString()
491
+ };
492
+ return renderInput(BASE_CLASSES.switch, attrs, checked, disabled, true, "table-switch");
493
+ };
494
+ var tableControls = {
495
+ checkbox: {
496
+ attr: CONTROL_IDENTIFIERS.checkbox,
497
+ render: renderCheckbox,
498
+ getData: (el) => ({
499
+ type: "checkbox",
500
+ rowIndex: Number(el.getAttribute("data-row-index")),
501
+ header: el.hasAttribute("data-header")
502
+ })
503
+ },
504
+ switch: {
505
+ attr: CONTROL_IDENTIFIERS.switch,
506
+ render: renderSwitch,
507
+ getData: (el) => ({
508
+ type: "switch",
509
+ rowIndex: Number(el.getAttribute("data-row-index")),
510
+ colIndex: Number(el.getAttribute("data-col-index"))
511
+ })
512
+ }
749
513
  };
750
514
 
751
- // packages/ui/react-ui-table/src/hooks/useTableModel.ts
752
- import { useEffect as useEffect2, useState as useState3 } from "react";
753
-
754
- // packages/ui/react-ui-table/src/model/table-model.ts
755
- import { computed as computed2, effect as effect2, signal as signal3 } from "@preact/signals-core";
756
- import orderBy from "lodash.orderby";
757
- import { Resource as Resource2 } from "@dxos/context";
758
- import { getValue as getValue2, setValue, FormatEnum as FormatEnum3 } from "@dxos/echo-schema";
759
- import { invariant as invariant3 } from "@dxos/invariant";
760
- import { PublicKey as PublicKey2 } from "@dxos/react-client";
761
- import { cellClassesForFieldType, cellClassesForRowSelection, formatForDisplay, formatForEditing, parseValue } from "@dxos/react-ui-form";
762
- import { toPlaneCellIndex } from "@dxos/react-ui-grid";
763
- import { mx as mx2 } from "@dxos/react-ui-theme";
764
- import { VIEW_FIELD_LIMIT } from "@dxos/schema";
765
-
766
- // packages/ui/react-ui-table/src/model/modal-controller.ts
767
- import { signal } from "@preact/signals-core";
768
- import { log as log2 } from "@dxos/log";
769
-
770
- // packages/ui/react-ui-table/src/util/signals.ts
771
- var touch = (value) => value;
515
+ // packages/ui/react-ui-table/src/model/selection-model.ts
516
+ var SelectionModel = class extends Resource {
517
+ constructor(_rows, _onSelectionChanged) {
518
+ super();
519
+ this._rows = _rows;
520
+ this._onSelectionChanged = _onSelectionChanged;
521
+ this._selection = signal(/* @__PURE__ */ new Set());
522
+ this._validSelectedIds = computed(() => {
523
+ const rows = this._rows.value;
524
+ if (!rows) {
525
+ return /* @__PURE__ */ new Set();
526
+ }
527
+ const validIds = new Set(rows.map((row) => row.id));
528
+ return new Set([
529
+ ...this._selection.value
530
+ ].filter((id) => validIds.has(id)));
531
+ });
532
+ this._hasSelection = computed(() => this._validSelectedIds.value.size > 0);
533
+ this._allSelected = computed(() => {
534
+ const rows = this._rows.value;
535
+ if (rows.length === 0) {
536
+ return false;
537
+ }
538
+ return rows.every((row) => this._selection.value.has(row.id));
539
+ });
540
+ this.getSelectedRows = () => {
541
+ const selectedIds = this._validSelectedIds.value;
542
+ return this._rows.value.filter((row) => selectedIds.has(row.id));
543
+ };
544
+ this.isRowIndexSelected = (rowIndex) => {
545
+ const row = this._rows.value[rowIndex];
546
+ return this._selection.value.has(row.id);
547
+ };
548
+ this.isObjectSelected = (object) => {
549
+ return this._selection.value.has(object.id);
550
+ };
551
+ this.toggleSelectionForRowIndex = (rowIndex) => {
552
+ const row = this._rows.value[rowIndex];
553
+ const newSelection = new Set(this._selection.value);
554
+ if (newSelection.has(row.id)) {
555
+ newSelection.delete(row.id);
556
+ } else {
557
+ newSelection.add(row.id);
558
+ }
559
+ this._selection.value = newSelection;
560
+ };
561
+ this.setSelection = (mode) => {
562
+ switch (mode) {
563
+ case "all": {
564
+ this._selection.value = new Set(this._rows.value.map((row) => row.id));
565
+ break;
566
+ }
567
+ case "none": {
568
+ this._selection.value = /* @__PURE__ */ new Set();
569
+ break;
570
+ }
571
+ }
572
+ };
573
+ }
574
+ async _open() {
575
+ const selectionWatcher = effect(() => {
576
+ touch(this._selection.value);
577
+ this._onSelectionChanged?.();
578
+ });
579
+ this._ctx.onDispose(selectionWatcher);
580
+ }
581
+ //
582
+ // Getters
583
+ //
584
+ get selection() {
585
+ return this._selection;
586
+ }
587
+ get hasSelection() {
588
+ return this._hasSelection;
589
+ }
590
+ get allRowsSeleted() {
591
+ return this._allSelected;
592
+ }
593
+ };
772
594
 
773
- // packages/ui/react-ui-table/src/util/table.ts
774
- import { AST, Format, FormatEnum as FormatEnum2, S as S2, TypedObject, TypeEnum } from "@dxos/echo-schema";
775
- import { log } from "@dxos/log";
776
- import { PublicKey } from "@dxos/react-client";
777
- import { create as create2 } from "@dxos/react-client/echo";
778
- import { createFieldId, createView, ViewProjection } from "@dxos/schema";
779
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-table/src/util/table.ts";
780
- var initializeTable = ({ space, table, initialRow = true }) => {
781
- log.info("initializeTable", {
782
- table
783
- }, {
784
- F: __dxlog_file3,
785
- L: 32,
786
- S: void 0,
787
- C: (f, a) => f(...a)
788
- });
789
- const ContactSchema = TypedObject({
790
- typename: `example.com/type/${PublicKey.random().truncate()}`,
791
- version: "0.1.0"
792
- })({
793
- name: S2.optional(S2.String).annotations({
794
- [AST.TitleAnnotationId]: "Name"
795
- }),
796
- email: S2.optional(Format.Email),
797
- salary: S2.optional(Format.Currency()).annotations({
798
- [AST.TitleAnnotationId]: "Salary"
799
- })
800
- });
801
- const contactSchema = space.db.schemaRegistry.addSchema(ContactSchema);
802
- table.view = createView({
803
- name: "Test",
804
- typename: contactSchema.typename,
805
- jsonSchema: contactSchema.jsonSchema,
806
- fields: [
807
- "name",
808
- "email",
809
- "salary"
810
- ]
811
- });
812
- const projection = new ViewProjection(contactSchema, table.view);
813
- projection.setFieldProjection({
814
- field: {
815
- id: table.view.fields[2].id,
816
- path: "salary",
817
- size: 150
595
+ // packages/ui/react-ui-table/src/model/table-model.ts
596
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-table/src/model/table-model.ts";
597
+ var TableModel = class extends Resource2 {
598
+ constructor({ table, projection, sorting = [], pinnedRows = {
599
+ top: [],
600
+ bottom: []
601
+ }, onCellUpdate, onDeleteColumn, onDeleteRows, onInsertRow, onRowOrderChanged }) {
602
+ super();
603
+ this.id = `table-model-${PublicKey2.random().truncate()}`;
604
+ this._visibleRange = signal2({
605
+ start: {
606
+ row: 0,
607
+ col: 0
608
+ },
609
+ end: {
610
+ row: 0,
611
+ col: 0
612
+ }
613
+ });
614
+ /**
615
+ * Maps display indices to data indices.
616
+ * Used for translating between sorted/displayed order and original data order.
617
+ * Keys are display indices, values are corresponding data indices.
618
+ */
619
+ this._displayToDataIndex = /* @__PURE__ */ new Map();
620
+ this._sorting = signal2(void 0);
621
+ this._rows = signal2([]);
622
+ //
623
+ // Data
624
+ //
625
+ this.setRows = (obj) => {
626
+ this._rows.value = obj;
627
+ };
628
+ this.getRowCount = () => this._rows.value.length;
629
+ this.getColumnCount = () => this.table.view?.target?.fields.length ?? 0;
630
+ this.insertRow = (rowIndex) => {
631
+ const row = rowIndex !== void 0 ? this._displayToDataIndex.get(rowIndex) ?? rowIndex : this._rows.value.length;
632
+ this._onInsertRow?.(row);
633
+ };
634
+ this.deleteRow = (rowIndex) => {
635
+ const row = this._displayToDataIndex.get(rowIndex) ?? rowIndex;
636
+ const obj = this._rows.value[row];
637
+ const objectsToDelete = [];
638
+ if (this._selection.hasSelection.value) {
639
+ const selectedRows = this._selection.getSelectedRows();
640
+ objectsToDelete.push(...selectedRows);
641
+ } else {
642
+ objectsToDelete.push(obj);
643
+ }
644
+ this._onDeleteRows?.(row, objectsToDelete);
645
+ };
646
+ this.getCellData = ({ col, row }) => {
647
+ const fields = this.table.view?.target?.fields ?? [];
648
+ if (col < 0 || col >= fields.length) {
649
+ return void 0;
650
+ }
651
+ const field = fields[col];
652
+ const dataIndex = this._displayToDataIndex.get(row) ?? row;
653
+ const value = getValue(this._rows.value[dataIndex], field.path);
654
+ if (value == null) {
655
+ return "";
656
+ }
657
+ const { props } = this._projection.getFieldProjection(field.id);
658
+ switch (props.format) {
659
+ case FormatEnum2.Ref: {
660
+ if (!field.referencePath) {
661
+ return "";
662
+ }
663
+ return getValue(value.target, field.referencePath);
664
+ }
665
+ default: {
666
+ return formatForEditing({
667
+ type: props.type,
668
+ format: props.format,
669
+ value
670
+ });
671
+ }
672
+ }
673
+ };
674
+ this.setCellData = ({ col, row }, value) => {
675
+ const rowIdx = this._displayToDataIndex.get(row) ?? row;
676
+ const fields = this.table.view?.target?.fields ?? [];
677
+ if (col < 0 || col >= fields.length) {
678
+ return;
679
+ }
680
+ const field = fields[col];
681
+ const { props } = this._projection.getFieldProjection(field.id);
682
+ switch (props.format) {
683
+ case FormatEnum2.Ref: {
684
+ if (isReactiveObject(value)) {
685
+ setValue(this._rows.value[rowIdx], field.path, makeRef2(value));
686
+ }
687
+ break;
688
+ }
689
+ default: {
690
+ setValue(this._rows.value[rowIdx], field.path, parseValue({
691
+ type: props.type,
692
+ format: props.format,
693
+ value
694
+ }));
695
+ break;
696
+ }
697
+ }
698
+ };
699
+ this._table = table;
700
+ this._projection = projection;
701
+ this._sorting.value = sorting.at(0);
702
+ this._pinnedRows = pinnedRows;
703
+ this._onInsertRow = onInsertRow;
704
+ this._onDeleteRows = onDeleteRows;
705
+ this._onDeleteColumn = onDeleteColumn;
706
+ this._onCellUpdate = onCellUpdate;
707
+ this._onRowOrderChanged = onRowOrderChanged;
708
+ }
709
+ get table() {
710
+ return this._table;
711
+ }
712
+ get projection() {
713
+ return this._projection;
714
+ }
715
+ get rows() {
716
+ return this._sortedRows;
717
+ }
718
+ get pinnedRows() {
719
+ return this._pinnedRows;
720
+ }
721
+ get columnMeta() {
722
+ invariant(this._columnMeta, void 0, {
723
+ F: __dxlog_file2,
724
+ L: 117,
725
+ S: this,
726
+ A: [
727
+ "this._columnMeta",
728
+ ""
729
+ ]
730
+ });
731
+ return this._columnMeta;
732
+ }
733
+ get sorting() {
734
+ return this._sorting.value;
735
+ }
736
+ get selection() {
737
+ return this._selection;
738
+ }
739
+ //
740
+ // Initialisation
741
+ //
742
+ async _open() {
743
+ this.initializeColumnMeta();
744
+ this.initializeSorting();
745
+ this.initializeEffects();
746
+ this._selection = new SelectionModel(this._sortedRows, () => this._onRowOrderChanged?.());
747
+ await this._selection.open(this._ctx);
748
+ }
749
+ initializeColumnMeta() {
750
+ this._columnMeta = computed2(() => {
751
+ const fields = this._table.view?.target?.fields ?? [];
752
+ const meta = Object.fromEntries(fields.map((field, index) => [
753
+ index,
754
+ {
755
+ size: field?.size ?? 256,
756
+ resizeable: true
757
+ }
758
+ ]));
759
+ return {
760
+ grid: meta,
761
+ frozenColsStart: {
762
+ 0: {
763
+ size: 30,
764
+ resizeable: false
765
+ }
766
+ },
767
+ frozenColsEnd: {
768
+ 0: {
769
+ size: 40,
770
+ resizeable: false
771
+ }
772
+ }
773
+ };
774
+ });
775
+ }
776
+ initializeSorting() {
777
+ this._sortedRows = computed2(() => {
778
+ this._displayToDataIndex.clear();
779
+ const sort = this._sorting.value;
780
+ if (!sort) {
781
+ return this._rows.value;
782
+ }
783
+ const field = this._table.view?.target?.fields.find((field2) => field2.id === sort.fieldId);
784
+ if (!field) {
785
+ return this._rows.value;
786
+ }
787
+ const { props } = this._projection.getFieldProjection(field.id);
788
+ const dataWithIndices = this._rows.value.map((item, index) => {
789
+ const rawValue = getValue(item, field.path);
790
+ let sortValue = rawValue;
791
+ if (props.type.startsWith("boolean")) {
792
+ sortValue = !!rawValue;
793
+ } else if (rawValue != null) {
794
+ if (props.format === FormatEnum2.Ref && field.referencePath) {
795
+ sortValue = getValue(rawValue, field.referencePath);
796
+ } else {
797
+ sortValue = formatForDisplay({
798
+ type: props.type,
799
+ format: props.format,
800
+ value: rawValue
801
+ });
802
+ }
803
+ }
804
+ return {
805
+ item,
806
+ index,
807
+ value: sortValue,
808
+ isEmpty: !props.type.startsWith("boolean") && (sortValue == null || sortValue === "")
809
+ };
810
+ });
811
+ const sorted = orderBy(dataWithIndices, [
812
+ "isEmpty",
813
+ "value"
814
+ ], [
815
+ "asc",
816
+ sort.direction
817
+ ]);
818
+ for (let displayIndex = 0; displayIndex < sorted.length; displayIndex++) {
819
+ const { index: dataIndex } = sorted[displayIndex];
820
+ if (displayIndex !== dataIndex) {
821
+ this._displayToDataIndex.set(displayIndex, dataIndex);
822
+ }
823
+ }
824
+ return sorted.map(({ item }) => item);
825
+ });
826
+ }
827
+ initializeEffects() {
828
+ const rowOrderWatcher = effect2(() => {
829
+ touch(this._sortedRows.value);
830
+ this._onRowOrderChanged?.();
831
+ });
832
+ this._ctx.onDispose(rowOrderWatcher);
833
+ const rowEffectManager = effect2(() => {
834
+ const { start, end } = touch(this._visibleRange.value);
835
+ const rowEffects = [];
836
+ for (let row = start.row; row <= end.row; row++) {
837
+ rowEffects.push(effect2(() => {
838
+ const obj = this._sortedRows.value[row];
839
+ this?._table?.view?.target?.fields.forEach((field) => touch(getValue(obj, field.path)));
840
+ this._onCellUpdate?.({
841
+ row,
842
+ col: start.col,
843
+ plane: "grid"
844
+ });
845
+ }));
846
+ }
847
+ return () => rowEffects.forEach((cleanup) => cleanup());
848
+ });
849
+ this._ctx.onDispose(rowEffectManager);
850
+ }
851
+ /**
852
+ * Updates a cell's value using a transform function.
853
+ * @param {DxGridPlanePosition} position - The position of the cell to update.
854
+ * @param {(value: any) => any} update - A function that takes the current value and returns the updated value.
855
+ */
856
+ updateCellData({ col, row }, update) {
857
+ const dataRow = this._displayToDataIndex.get(row) ?? row;
858
+ const fields = this.table.view?.target?.fields ?? [];
859
+ const field = fields[col];
860
+ const value = getValue(this._rows.value[dataRow], field.path);
861
+ const updatedValue = update(value);
862
+ setValue(this._rows.value[dataRow], field.path, updatedValue);
863
+ }
864
+ //
865
+ // Column Operations
866
+ //
867
+ deleteColumn(fieldId) {
868
+ if (!this.table.view) {
869
+ return;
818
870
  }
819
- });
820
- projection.setFieldProjection({
821
- field: {
822
- id: createFieldId(),
823
- path: "manager",
824
- referencePath: "name"
825
- },
826
- props: {
827
- property: "manager",
828
- type: TypeEnum.Ref,
829
- format: FormatEnum2.Ref,
830
- referenceSchema: contactSchema.typename,
831
- title: "Manager"
871
+ const field = this.table.view.target?.fields.find((field2) => field2.id === fieldId);
872
+ if (field && this._onDeleteColumn) {
873
+ if (this._sorting.value?.fieldId === fieldId) {
874
+ this.clearSort();
875
+ }
876
+ this._onDeleteColumn(field.id);
832
877
  }
833
- });
834
- if (initialRow) {
835
- space.db.add(create2(contactSchema, {}));
836
878
  }
837
- return contactSchema;
838
- };
839
-
840
- // packages/ui/react-ui-table/src/util/table-buttons.ts
841
- var TABLE_ATTRS = {
842
- referencedCell: "data-table-ref-cell-button",
843
- columnSettings: "data-table-column-settings-button",
844
- rowMenu: "data-table-row-menu-button",
845
- newColumn: "data-table-new-column-button"
846
- };
847
- var ICONS = {
848
- referencedCell: "ph--link-simple-horizontal--regular",
849
- columnSettings: "ph--caret-down--regular",
850
- rowMenu: "ph--dots-three--regular",
851
- newColumn: "ph--plus--regular"
852
- };
853
- var createButtonHtml = ({ button, value = "", disabled = false, testId }) => {
854
- const buttonClasses = "ch-button is-6 pli-0.5 min-bs-0 absolute inset-block-1 inline-end-2";
855
- return `<button class="${buttonClasses}" ${TABLE_ATTRS[button]}="${value}" data-testid="${testId}" ${disabled ? "disabled" : ""}><svg><use href="/icons.svg#${ICONS[button]}"/></svg></button>`;
856
- };
857
- var tableButtons = {
858
- referencedCell: {
859
- attr: TABLE_ATTRS.referencedCell,
860
- icon: ICONS.referencedCell,
861
- render: ({ targetId, schemaId }) => createButtonHtml({
862
- button: "referencedCell",
863
- value: `${schemaId}#${targetId}`,
864
- testId: "table-ref-cell-button"
865
- })
866
- },
867
- columnSettings: {
868
- attr: TABLE_ATTRS.columnSettings,
869
- icon: ICONS.columnSettings,
870
- render: ({ fieldId }) => createButtonHtml({
871
- button: "columnSettings",
872
- value: fieldId,
873
- testId: "table-column-settings-button"
874
- })
875
- },
876
- rowMenu: {
877
- attr: TABLE_ATTRS.rowMenu,
878
- icon: ICONS.rowMenu,
879
- render: ({ rowIndex }) => createButtonHtml({
880
- button: "rowMenu",
881
- value: rowIndex.toString(),
882
- testId: "table-row-menu-button"
883
- })
884
- },
885
- addColumn: {
886
- attr: TABLE_ATTRS.newColumn,
887
- icon: ICONS.newColumn,
888
- render: ({ disabled } = {}) => createButtonHtml({
889
- button: "newColumn",
890
- disabled,
891
- testId: "table-new-column-button"
892
- })
879
+ //
880
+ // Resize
881
+ //
882
+ setColumnWidth(columnIndex, width) {
883
+ const fields = this.table.view?.target?.fields ?? [];
884
+ if (columnIndex < fields.length) {
885
+ const newWidth = Math.max(0, width);
886
+ const field = fields[columnIndex];
887
+ if (field) {
888
+ field.size = newWidth;
889
+ }
890
+ }
891
+ }
892
+ //
893
+ // Sorting
894
+ //
895
+ setSort(fieldId, direction) {
896
+ this._sorting.value = {
897
+ fieldId,
898
+ direction
899
+ };
900
+ }
901
+ clearSort() {
902
+ this._sorting.value = void 0;
903
+ }
904
+ //
905
+ // Pinning
906
+ //
907
+ // TODO(burdon): Change to setPinned(on/off).
908
+ pinRow(rowIndex, side) {
909
+ this._pinnedRows[side].push(rowIndex);
910
+ }
911
+ unpinRow(rowIndex) {
912
+ this._pinnedRows.top = this._pinnedRows.top.filter((index) => index !== rowIndex);
913
+ this._pinnedRows.bottom = this._pinnedRows.bottom.filter((index) => index !== rowIndex);
893
914
  }
894
915
  };
895
916
 
896
917
  // packages/ui/react-ui-table/src/model/modal-controller.ts
897
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-table/src/model/modal-controller.ts";
918
+ import { signal as signal3 } from "@preact/signals-core";
919
+ import { log as log2 } from "@dxos/log";
920
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-table/src/model/modal-controller.ts";
898
921
  var ModalController = class {
899
922
  constructor() {
900
- this._state = signal({
923
+ this._state = signal3({
901
924
  type: "closed"
902
925
  });
903
926
  this._triggerRef = {
904
927
  current: null
905
928
  };
906
- this.handleClick = (event) => {
907
- const target = event.target;
908
- const rowButton = target.closest(`button[${tableButtons.rowMenu.attr}]`);
909
- if (rowButton) {
910
- this._triggerRef.current = rowButton;
911
- this._state.value = {
912
- type: "row",
913
- rowIndex: Number(rowButton.getAttribute(tableButtons.rowMenu.attr))
914
- };
915
- return true;
916
- }
917
- const columnButton = target.closest(`button[${tableButtons.columnSettings.attr}]`);
918
- if (columnButton) {
919
- const fieldId = columnButton.getAttribute(tableButtons.columnSettings.attr);
920
- this._triggerRef.current = columnButton;
921
- this._state.value = {
922
- type: "column",
923
- fieldId
924
- };
925
- return true;
926
- }
927
- const addColumnButton = target.closest(`button[${tableButtons.addColumn.attr}]`);
928
- if (addColumnButton) {
929
- this._triggerRef.current = addColumnButton;
930
- this._state.value = {
931
- type: "columnSettings",
932
- mode: {
933
- type: "create"
934
- }
935
- };
936
- return true;
937
- }
938
- const refButton = target.closest(`button[${tableButtons.referencedCell.attr}]`);
939
- if (refButton) {
940
- this._triggerRef.current = refButton;
941
- const [schemaId, targetId] = refButton.getAttribute(tableButtons.referencedCell.attr).split("#");
942
- this._state.value = {
943
- type: "refPanel",
944
- targetId,
945
- typename: schemaId
946
- };
947
- }
948
- return false;
929
+ this.setTrigger = (trigger) => {
930
+ this._triggerRef.current = trigger;
931
+ };
932
+ this.showRowMenu = (rowIndex) => {
933
+ this._state.value = {
934
+ type: "row",
935
+ rowIndex
936
+ };
937
+ };
938
+ this.showColumnMenu = (fieldId) => {
939
+ this._state.value = {
940
+ type: "column",
941
+ fieldId
942
+ };
943
+ };
944
+ this.showColumnCreator = () => {
945
+ this._state.value = {
946
+ type: "columnSettings",
947
+ mode: {
948
+ type: "create"
949
+ }
950
+ };
951
+ };
952
+ this.showReferencePanel = (targetId, schemaId) => {
953
+ this._state.value = {
954
+ type: "refPanel",
955
+ targetId,
956
+ typename: schemaId
957
+ };
949
958
  };
950
959
  this.openColumnSettings = () => {
951
960
  if (this._state.value.type === "column") {
@@ -972,8 +981,8 @@ var ModalController = class {
972
981
  };
973
982
  } else {
974
983
  log2.warn("anchor cell not found while creating new ref", void 0, {
975
- F: __dxlog_file4,
976
- L: 119,
984
+ F: __dxlog_file3,
985
+ L: 86,
977
986
  S: this,
978
987
  C: (f, a) => f(...a)
979
988
  });
@@ -988,602 +997,767 @@ var ModalController = class {
988
997
  get state() {
989
998
  return this._state;
990
999
  }
991
- get trigger() {
992
- return this._triggerRef;
993
- }
994
- };
995
-
996
- // packages/ui/react-ui-table/src/model/selection-model.ts
997
- import { computed, effect, signal as signal2 } from "@preact/signals-core";
998
- import { Resource } from "@dxos/context";
999
- var SelectionModel = class extends Resource {
1000
- constructor(_rows, _onSelectionChanged) {
1001
- super();
1002
- this._rows = _rows;
1003
- this._onSelectionChanged = _onSelectionChanged;
1004
- this._selection = signal2(/* @__PURE__ */ new Set());
1005
- this._validSelectedIds = computed(() => {
1006
- const rows = this._rows.value;
1007
- if (!rows) {
1008
- return /* @__PURE__ */ new Set();
1009
- }
1010
- const validIds = new Set(rows.map((row) => row.id));
1011
- return new Set([
1012
- ...this._selection.value
1013
- ].filter((id) => validIds.has(id)));
1014
- });
1015
- this._hasSelection = computed(() => this._validSelectedIds.value.size > 0);
1016
- this._allSelected = computed(() => {
1017
- const rows = this._rows.value;
1018
- if (rows.length === 0) {
1019
- return false;
1020
- }
1021
- return rows.every((row) => this._selection.value.has(row.id));
1022
- });
1023
- this.getSelectedRows = () => {
1024
- const selectedIds = this._validSelectedIds.value;
1025
- return this._rows.value.filter((row) => selectedIds.has(row.id));
1026
- };
1027
- this.isRowIndexSelected = (rowIndex) => {
1028
- const row = this._rows.value[rowIndex];
1029
- return this._selection.value.has(row.id);
1030
- };
1031
- this.isObjectSelected = (object) => {
1032
- return this._selection.value.has(object.id);
1033
- };
1034
- this.toggleSelectionForRowIndex = (rowIndex) => {
1035
- const row = this._rows.value[rowIndex];
1036
- const newSelection = new Set(this._selection.value);
1037
- if (newSelection.has(row.id)) {
1038
- newSelection.delete(row.id);
1039
- } else {
1040
- newSelection.add(row.id);
1041
- }
1042
- this._selection.value = newSelection;
1043
- };
1044
- this.setSelection = (mode) => {
1045
- this._selection.value = mode === "all" ? new Set(this._rows.value.map((row) => row.id)) : /* @__PURE__ */ new Set();
1046
- };
1047
- }
1048
- async _open() {
1049
- const selectionWatcher = effect(() => {
1050
- touch(this._selection.value);
1051
- this._onSelectionChanged?.();
1052
- });
1053
- this._ctx.onDispose(selectionWatcher);
1054
- }
1055
- //
1056
- // Getters
1057
- //
1058
- get selection() {
1059
- return this._selection;
1060
- }
1061
- get hasSelection() {
1062
- return this._hasSelection;
1063
- }
1064
- get allRowsSeleted() {
1065
- return this._allSelected;
1066
- }
1067
- };
1068
-
1069
- // packages/ui/react-ui-table/src/util/table-controls.ts
1070
- var checkboxAttributes = {
1071
- checkbox: "data-table-checkbox",
1072
- header: "data-table-header"
1073
- };
1074
- var renderCheckbox = ({ rowIndex, header = false, checked = false, disabled = false }) => {
1075
- const baseClasses = "absolute inset-block-[6px] inline-end-[6px] ch-checkbox";
1076
- const { attributes } = tableControls.checkbox;
1077
- return `<input type="checkbox" class="${baseClasses}" ${attributes.checkbox}="${rowIndex}" ${header ? attributes.header : ""} ${checked ? "checked" : ""} ${disabled ? "disabled" : ""} data-testid="table-selection"/>`;
1078
- };
1079
- var tableControls = {
1080
- checkbox: {
1081
- attributes: checkboxAttributes,
1082
- render: renderCheckbox
1083
- }
1000
+ get trigger() {
1001
+ return this._triggerRef;
1002
+ }
1084
1003
  };
1085
1004
 
1086
- // packages/ui/react-ui-table/src/model/table-model.ts
1087
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-table/src/model/table-model.ts";
1088
- var TableModel = class extends Resource2 {
1089
- constructor({ table, projection, sorting = [], pinnedRows = {
1090
- top: [],
1091
- bottom: []
1092
- }, onCellUpdate, onDeleteColumn, onDeleteRows, onInsertRow, onRowOrderChanged }) {
1093
- super();
1094
- this.id = `table-model-${PublicKey2.random().truncate()}`;
1095
- this._visibleRange = signal3({
1096
- start: {
1097
- row: 0,
1098
- col: 0
1099
- },
1100
- end: {
1101
- row: 0,
1102
- col: 0
1103
- }
1104
- });
1105
- /**
1106
- * Maps display indices to data indices.
1107
- * Used for translating between sorted/displayed order and original data order.
1108
- * Keys are display indices, values are corresponding data indices.
1109
- */
1110
- this._displayToDataIndex = /* @__PURE__ */ new Map();
1111
- this._sorting = signal3(void 0);
1112
- this._rows = signal3([]);
1113
- this._modalController = new ModalController();
1114
- //
1115
- // Get Cells
1116
- //
1117
- this.getCells = (range, plane) => {
1118
- switch (plane) {
1119
- case "grid": {
1120
- this._visibleRange.value = range;
1121
- return this.getMainGridCells(range);
1122
- }
1123
- case "frozenRowsStart": {
1124
- return this.getHeaderCells(range);
1125
- }
1126
- case "frozenColsStart": {
1127
- return this.getSelectionColumnCells(range);
1128
- }
1129
- case "frozenColsEnd": {
1130
- return this.getActionColumnCells(range);
1131
- }
1132
- case "fixedStartStart": {
1133
- return this.getSelectAllCell();
1134
- }
1135
- case "fixedStartEnd": {
1136
- return this.getNewColumnCell();
1137
- }
1138
- default: {
1139
- return {};
1140
- }
1141
- }
1142
- };
1143
- this.getMainGridCells = (range) => {
1144
- const cells = {};
1145
- const fields = this._table.view?.fields ?? [];
1146
- const addCell = (obj, field, colIndex, displayIndex) => {
1147
- const { props } = this._projection.getFieldProjection(field.id);
1148
- const cell = {
1149
- get value() {
1150
- const value = getValue2(obj, field.path);
1151
- if (value == null) {
1005
+ // packages/ui/react-ui-table/src/model/table-presentation.ts
1006
+ import { signal as signal4 } from "@preact/signals-core";
1007
+ import { FormatEnum as FormatEnum3, getValue as getValue2 } from "@dxos/echo-schema";
1008
+ import { cellClassesForFieldType, cellClassesForRowSelection, formatForDisplay as formatForDisplay2 } from "@dxos/react-ui-form";
1009
+ import { toPlaneCellIndex } from "@dxos/react-ui-grid";
1010
+ import { mx } from "@dxos/react-ui-theme";
1011
+ import { VIEW_FIELD_LIMIT } from "@dxos/schema";
1012
+ var TablePresentation = class {
1013
+ constructor(model, _visibleRange = signal4({
1014
+ start: {
1015
+ row: 0,
1016
+ col: 0
1017
+ },
1018
+ end: {
1019
+ row: 0,
1020
+ col: 0
1021
+ }
1022
+ })) {
1023
+ this.model = model;
1024
+ this._visibleRange = _visibleRange;
1025
+ }
1026
+ getCells(range, plane) {
1027
+ switch (plane) {
1028
+ case "grid":
1029
+ this._visibleRange.value = range;
1030
+ return this.getMainGridCells(range);
1031
+ case "frozenRowsStart":
1032
+ return this.getHeaderCells(range);
1033
+ case "frozenColsStart":
1034
+ return this.getSelectionColumnCells(range);
1035
+ case "frozenColsEnd":
1036
+ return this.getActionColumnCells(range);
1037
+ case "fixedStartStart":
1038
+ return this.getSelectAllCell();
1039
+ case "fixedStartEnd":
1040
+ return this.getNewColumnCell();
1041
+ default:
1042
+ return {};
1043
+ }
1044
+ }
1045
+ getMainGridCells(range) {
1046
+ const cells = {};
1047
+ const fields = this.model.table.view?.target?.fields ?? [];
1048
+ const addCell = (obj, field, colIndex, displayIndex) => {
1049
+ const { props } = this.model.projection.getFieldProjection(field.id);
1050
+ const cell = {
1051
+ get value() {
1052
+ const value = getValue2(obj, field.path);
1053
+ if (value == null) {
1054
+ return "";
1055
+ }
1056
+ switch (props.format) {
1057
+ case FormatEnum3.Boolean: {
1152
1058
  return "";
1153
1059
  }
1154
- switch (props.format) {
1155
- case FormatEnum3.Ref: {
1156
- if (!field.referencePath) {
1157
- return "";
1158
- }
1159
- return getValue2(value, field.referencePath);
1160
- }
1161
- default: {
1162
- return formatForDisplay({
1163
- type: props.type,
1164
- format: props.format,
1165
- value
1166
- });
1060
+ case FormatEnum3.Ref: {
1061
+ if (!field.referencePath) {
1062
+ return "";
1167
1063
  }
1064
+ return getValue2(value.target, field.referencePath);
1065
+ }
1066
+ default: {
1067
+ return formatForDisplay2({
1068
+ type: props.type,
1069
+ format: props.format,
1070
+ value
1071
+ });
1168
1072
  }
1169
1073
  }
1170
- };
1171
- const classes = [];
1172
- const formatClasses = cellClassesForFieldType({
1173
- type: props.type,
1174
- format: props.format
1175
- });
1176
- if (formatClasses) {
1177
- classes.push(formatClasses);
1178
- }
1179
- const rowSelectionClasses = cellClassesForRowSelection(this._selection.isObjectSelected(obj));
1180
- if (rowSelectionClasses) {
1181
- classes.push(rowSelectionClasses);
1182
1074
  }
1183
- if (classes.length > 0) {
1184
- cell.className = mx2(classes.flat());
1185
- }
1186
- if (cell.value && props.format === FormatEnum3.Ref && props.referenceSchema) {
1187
- const targetObj = getValue2(obj, field.path);
1075
+ };
1076
+ const classes = [];
1077
+ const formatClasses = cellClassesForFieldType({
1078
+ type: props.type,
1079
+ format: props.format
1080
+ });
1081
+ if (formatClasses) {
1082
+ classes.push(formatClasses);
1083
+ }
1084
+ const rowSelectionClasses = cellClassesForRowSelection(this.model.selection.isObjectSelected(obj));
1085
+ if (rowSelectionClasses) {
1086
+ classes.push(rowSelectionClasses);
1087
+ }
1088
+ if (classes.length > 0) {
1089
+ cell.className = mx(classes.flat());
1090
+ }
1091
+ if (props.format === FormatEnum3.Ref && props.referenceSchema) {
1092
+ const targetObj = getValue2(obj, field.path)?.target;
1093
+ if (targetObj) {
1188
1094
  cell.accessoryHtml = tableButtons.referencedCell.render({
1189
1095
  targetId: targetObj.id,
1190
1096
  schemaId: props.referenceSchema
1191
1097
  });
1192
1098
  }
1193
- const idx = toPlaneCellIndex({
1194
- col: colIndex,
1195
- row: displayIndex
1099
+ }
1100
+ if (props.format === FormatEnum3.Boolean) {
1101
+ const value = getValue2(obj, field.path);
1102
+ cell.accessoryHtml = tableControls.switch.render({
1103
+ colIndex,
1104
+ rowIndex: displayIndex,
1105
+ checked: value ?? false
1196
1106
  });
1197
- cells[idx] = cell;
1198
- };
1199
- for (let row = range.start.row; row <= range.end.row && row < this._sortedRows.value.length; row++) {
1200
- for (let col = range.start.col; col <= range.end.col && col < fields.length; col++) {
1201
- const field = fields[col];
1202
- if (!field) {
1203
- continue;
1204
- }
1205
- addCell(this._sortedRows.value[row], field, col, row);
1206
- }
1107
+ cell.readonly = true;
1207
1108
  }
1208
- return cells;
1109
+ const idx = toPlaneCellIndex({
1110
+ col: colIndex,
1111
+ row: displayIndex
1112
+ });
1113
+ cells[idx] = cell;
1209
1114
  };
1210
- this.getHeaderCells = (range) => {
1211
- const cells = {};
1212
- const fields = this.table.view?.fields ?? [];
1115
+ for (let row = range.start.row; row <= range.end.row && row < this.model.getRowCount(); row++) {
1213
1116
  for (let col = range.start.col; col <= range.end.col && col < fields.length; col++) {
1214
- const { field, props } = this._projection.getFieldProjection(fields[col].id);
1215
- cells[toPlaneCellIndex({
1216
- col,
1217
- row: 0
1218
- })] = {
1219
- // TODO(burdon): Use same logic as form for fallback title.
1220
- value: props.title ?? field.path,
1221
- readonly: true,
1222
- resizeHandle: "col",
1223
- accessoryHtml: tableButtons.columnSettings.render({
1224
- fieldId: field.id
1225
- })
1226
- };
1227
- }
1228
- return cells;
1229
- };
1230
- this.getSelectionColumnCells = (range) => {
1231
- const cells = {};
1232
- for (let row = range.start.row; row <= range.end.row && row < this._rows.value.length; row++) {
1233
- const isSelected = this._selection.isRowIndexSelected(row);
1234
- const classes = cellClassesForRowSelection(isSelected);
1235
- cells[toPlaneCellIndex({
1236
- col: 0,
1237
- row
1238
- })] = {
1239
- value: "",
1240
- readonly: true,
1241
- className: classes ? mx2(classes) : void 0,
1242
- accessoryHtml: tableControls.checkbox.render({
1243
- rowIndex: row,
1244
- checked: isSelected
1245
- })
1246
- };
1247
- }
1248
- return cells;
1249
- };
1250
- this.getActionColumnCells = (range) => {
1251
- const cells = {};
1252
- for (let row = range.start.row; row <= range.end.row && row < this._rows.value.length; row++) {
1253
- const isSelected = this._selection.isRowIndexSelected(row);
1254
- const classes = cellClassesForRowSelection(isSelected);
1255
- cells[toPlaneCellIndex({
1256
- col: 0,
1257
- row
1258
- })] = {
1259
- value: "",
1260
- readonly: true,
1261
- className: classes ? mx2(classes) : void 0,
1262
- accessoryHtml: tableButtons.rowMenu.render({
1263
- rowIndex: row
1264
- })
1265
- };
1266
- }
1267
- return cells;
1268
- };
1269
- this.getSelectAllCell = () => {
1270
- return {
1271
- [toPlaneCellIndex({
1272
- col: 0,
1273
- row: 0
1274
- })]: {
1275
- value: "",
1276
- accessoryHtml: tableControls.checkbox.render({
1277
- rowIndex: 0,
1278
- header: true,
1279
- checked: this._selection.allRowsSeleted.value
1280
- }),
1281
- readonly: true
1117
+ const field = fields[col];
1118
+ if (!field) {
1119
+ continue;
1282
1120
  }
1121
+ addCell(this.model.rows.value[row], field, col, row);
1122
+ }
1123
+ }
1124
+ return cells;
1125
+ }
1126
+ getHeaderCells(range) {
1127
+ const cells = {};
1128
+ const fields = this.model.table.view?.target?.fields ?? [];
1129
+ for (let col = range.start.col; col <= range.end.col && col < fields.length; col++) {
1130
+ const { field, props } = this.model.projection.getFieldProjection(fields[col].id);
1131
+ cells[toPlaneCellIndex({
1132
+ col,
1133
+ row: 0
1134
+ })] = {
1135
+ // TODO(burdon): Use same logic as form for fallback title.
1136
+ value: props.title ?? field.path,
1137
+ readonly: true,
1138
+ resizeHandle: "col",
1139
+ accessoryHtml: tableButtons.columnSettings.render({
1140
+ fieldId: field.id
1141
+ })
1283
1142
  };
1284
- };
1285
- this.getNewColumnCell = () => {
1286
- return {
1287
- [toPlaneCellIndex({
1288
- col: 0,
1289
- row: 0
1290
- })]: {
1291
- value: "",
1292
- accessoryHtml: tableButtons.addColumn.render({
1293
- disabled: (this._table.view?.fields?.length ?? 0) >= VIEW_FIELD_LIMIT
1294
- }),
1295
- readonly: true
1296
- }
1143
+ }
1144
+ return cells;
1145
+ }
1146
+ getSelectionColumnCells(range) {
1147
+ const cells = {};
1148
+ for (let row = range.start.row; row <= range.end.row && row < this.model.getRowCount(); row++) {
1149
+ const isSelected = this.model.selection.isRowIndexSelected(row);
1150
+ const classes = cellClassesForRowSelection(isSelected);
1151
+ cells[toPlaneCellIndex({
1152
+ col: 0,
1153
+ row
1154
+ })] = {
1155
+ value: "",
1156
+ readonly: true,
1157
+ className: classes ? mx(classes) : void 0,
1158
+ accessoryHtml: tableControls.checkbox.render({
1159
+ rowIndex: row,
1160
+ checked: isSelected
1161
+ })
1297
1162
  };
1298
- };
1299
- //
1300
- // Data
1301
- //
1302
- this.setRows = (obj) => {
1303
- this._rows.value = obj;
1304
- };
1305
- this.getRowCount = () => this._rows.value.length;
1306
- this.getColumnCount = () => this.table.view?.fields.length ?? 0;
1307
- this.insertRow = (rowIndex) => {
1308
- const row = rowIndex !== void 0 ? this._displayToDataIndex.get(rowIndex) ?? rowIndex : this._rows.value.length;
1309
- this._onInsertRow?.(row);
1310
- };
1311
- this.deleteRow = (rowIndex) => {
1312
- const row = this._displayToDataIndex.get(rowIndex) ?? rowIndex;
1313
- const obj = this._rows.value[row];
1314
- const objectsToDelete = [];
1315
- if (this._selection.hasSelection.value) {
1316
- const selectedRows = this._selection.getSelectedRows();
1317
- objectsToDelete.push(...selectedRows);
1318
- } else {
1319
- objectsToDelete.push(obj);
1163
+ }
1164
+ return cells;
1165
+ }
1166
+ getActionColumnCells(range) {
1167
+ const cells = {};
1168
+ for (let row = range.start.row; row <= range.end.row && row < this.model.getRowCount(); row++) {
1169
+ const isSelected = this.model.selection.isRowIndexSelected(row);
1170
+ const classes = cellClassesForRowSelection(isSelected);
1171
+ cells[toPlaneCellIndex({
1172
+ col: 0,
1173
+ row
1174
+ })] = {
1175
+ value: "",
1176
+ readonly: true,
1177
+ className: classes ? mx(classes) : void 0,
1178
+ accessoryHtml: tableButtons.rowMenu.render({
1179
+ rowIndex: row
1180
+ })
1181
+ };
1182
+ }
1183
+ return cells;
1184
+ }
1185
+ getSelectAllCell() {
1186
+ return {
1187
+ [toPlaneCellIndex({
1188
+ col: 0,
1189
+ row: 0
1190
+ })]: {
1191
+ value: "",
1192
+ accessoryHtml: tableControls.checkbox.render({
1193
+ rowIndex: 0,
1194
+ header: true,
1195
+ checked: this.model.selection.allRowsSeleted.value
1196
+ }),
1197
+ readonly: true
1320
1198
  }
1321
- this._onDeleteRows?.(row, objectsToDelete);
1322
1199
  };
1323
- this.getCellData = ({ col, row }) => {
1324
- const fields = this.table.view?.fields ?? [];
1325
- if (col < 0 || col >= fields.length) {
1326
- return void 0;
1200
+ }
1201
+ getNewColumnCell() {
1202
+ return {
1203
+ [toPlaneCellIndex({
1204
+ col: 0,
1205
+ row: 0
1206
+ })]: {
1207
+ value: "",
1208
+ accessoryHtml: tableButtons.addColumn.render({
1209
+ disabled: (this.model.table.view?.target?.fields?.length ?? 0) >= VIEW_FIELD_LIMIT
1210
+ }),
1211
+ readonly: true
1327
1212
  }
1328
- const field = fields[col];
1329
- const dataIndex = this._displayToDataIndex.get(row) ?? row;
1330
- const value = getValue2(this._rows.value[dataIndex], field.path);
1331
- if (value == null) {
1332
- return "";
1213
+ };
1214
+ }
1215
+ };
1216
+
1217
+ // packages/ui/react-ui-table/src/components/TableCellEditor/TableCellEditor.tsx
1218
+ import React6, { useCallback as useCallback3, useMemo as useMemo3, useRef } from "react";
1219
+ import { FormatEnum as FormatEnum4 } from "@dxos/echo-schema";
1220
+ import { invariant as invariant2 } from "@dxos/invariant";
1221
+ import { cellQuery, editorKeys, parseCellIndex, useGridContext as useGridContext2, GridCellEditor } from "@dxos/react-ui-grid";
1222
+
1223
+ // packages/ui/react-ui-table/src/components/TableCellEditor/extension.ts
1224
+ import { autocompletion, pickedCompletion } from "@codemirror/autocomplete";
1225
+ import { EditorView } from "@codemirror/view";
1226
+ var completion = ({ debug, onQuery, onMatch }) => {
1227
+ return [
1228
+ EditorView.theme({
1229
+ ".cm-completionDialog": {
1230
+ width: "var(--dx-gridCellWidth)"
1333
1231
  }
1334
- const { props } = this._projection.getFieldProjection(field.id);
1335
- switch (props.format) {
1336
- case FormatEnum3.Ref: {
1337
- if (!field.referencePath) {
1338
- return "";
1339
- }
1340
- return getValue2(value, field.referencePath);
1232
+ }),
1233
+ autocompletion({
1234
+ icons: false,
1235
+ activateOnTyping: true,
1236
+ closeOnBlur: !debug,
1237
+ override: [
1238
+ async (context) => {
1239
+ const text = context.state.doc.toString();
1240
+ return {
1241
+ from: 0,
1242
+ options: await onQuery(text)
1243
+ };
1244
+ }
1245
+ ],
1246
+ // TODO(burdon): Consts from grid (to line-up with grid).
1247
+ tooltipClass: () => "cm-completionDialog !mt-[8px] !-ml-[4px] [&>ul]:!max-h-[264px]",
1248
+ optionClass: () => "flex h-[33px] items-center"
1249
+ }),
1250
+ // Check for accepted completion metadata in the transaction.
1251
+ EditorView.updateListener.of((update) => {
1252
+ update.transactions.forEach((tr) => {
1253
+ const completion2 = tr.annotation(pickedCompletion);
1254
+ if (completion2) {
1255
+ onMatch(completion2.data);
1256
+ }
1257
+ });
1258
+ })
1259
+ ];
1260
+ };
1261
+
1262
+ // packages/ui/react-ui-table/src/components/TableCellEditor/TableCellEditor.tsx
1263
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-table/src/components/TableCellEditor/TableCellEditor.tsx";
1264
+ var newValue = Symbol.for("newValue");
1265
+ var createOption = (text) => ({
1266
+ [newValue]: true,
1267
+ text
1268
+ });
1269
+ var isCreateOption = (data) => typeof data === "object" && data[newValue];
1270
+ var TableCellEditor = ({ model, modals, onEnter, onFocus, onQuery, __gridScope }) => {
1271
+ const { id: gridId, editing, setEditing } = useGridContext2("TableCellEditor", __gridScope);
1272
+ const suppressNextBlur = useRef(false);
1273
+ const fieldProjection = useMemo3(() => {
1274
+ if (!model || !editing) {
1275
+ return;
1276
+ }
1277
+ const { col } = parseCellIndex(editing.index);
1278
+ const field = model.projection.view.fields[col];
1279
+ const fieldProjection2 = model.projection.getFieldProjection(field.id);
1280
+ invariant2(fieldProjection2, void 0, {
1281
+ F: __dxlog_file4,
1282
+ L: 67,
1283
+ S: void 0,
1284
+ A: [
1285
+ "fieldProjection",
1286
+ ""
1287
+ ]
1288
+ });
1289
+ return fieldProjection2;
1290
+ }, [
1291
+ model,
1292
+ editing
1293
+ ]);
1294
+ const handleEnter = useCallback3((value) => {
1295
+ if (!model || !editing) {
1296
+ return;
1297
+ }
1298
+ const cell = parseCellIndex(editing.index);
1299
+ model.setCellData(cell, value);
1300
+ onEnter?.(cell);
1301
+ onFocus?.();
1302
+ setEditing(null);
1303
+ }, [
1304
+ model,
1305
+ editing
1306
+ ]);
1307
+ const handleBlur = useCallback3((value) => {
1308
+ if (!model || !editing) {
1309
+ return;
1310
+ }
1311
+ if (suppressNextBlur.current) {
1312
+ suppressNextBlur.current = false;
1313
+ return;
1314
+ }
1315
+ const cell = parseCellIndex(editing.index);
1316
+ if (value !== void 0) {
1317
+ model.setCellData(cell, value);
1318
+ }
1319
+ }, [
1320
+ model,
1321
+ editing
1322
+ ]);
1323
+ const handleClose = useCallback3((value, event) => {
1324
+ if (!model || !editing || !fieldProjection) {
1325
+ return;
1326
+ }
1327
+ const cell = parseCellIndex(editing.index);
1328
+ onEnter?.(cell);
1329
+ if (event && onFocus) {
1330
+ onFocus(determineNavigationAxis(event), determineNavigationDelta(event));
1331
+ }
1332
+ }, [
1333
+ model,
1334
+ editing,
1335
+ onFocus,
1336
+ onEnter,
1337
+ fieldProjection,
1338
+ determineNavigationAxis,
1339
+ determineNavigationDelta
1340
+ ]);
1341
+ const extension = useMemo3(() => {
1342
+ if (!fieldProjection) {
1343
+ return [];
1344
+ }
1345
+ const extension2 = [
1346
+ editorKeys({
1347
+ onClose: handleClose,
1348
+ ...editing?.initialContent && {
1349
+ onNav: handleClose
1350
+ }
1351
+ })
1352
+ ];
1353
+ if (onQuery) {
1354
+ switch (fieldProjection.props.format) {
1355
+ case FormatEnum4.Ref: {
1356
+ extension2.push([
1357
+ completion({
1358
+ onQuery: (text) => onQuery(fieldProjection, text),
1359
+ onMatch: (data) => {
1360
+ if (model && editing && modals) {
1361
+ if (isCreateOption(data)) {
1362
+ const { field, props } = fieldProjection;
1363
+ if (props.referenceSchema) {
1364
+ suppressNextBlur.current = true;
1365
+ modals.openCreateRef(props.referenceSchema, document.querySelector(cellQuery(editing.index, gridId)), {
1366
+ [field.referencePath]: data.text
1367
+ }, (data2) => {
1368
+ handleEnter(data2);
1369
+ });
1370
+ }
1371
+ } else {
1372
+ handleEnter(data);
1373
+ }
1374
+ }
1375
+ }
1376
+ })
1377
+ ]);
1378
+ break;
1341
1379
  }
1342
- default: {
1343
- return formatForEditing({
1344
- type: props.type,
1345
- format: props.format,
1346
- value
1347
- });
1380
+ }
1381
+ }
1382
+ return extension2;
1383
+ }, [
1384
+ model,
1385
+ modals,
1386
+ editing,
1387
+ fieldProjection,
1388
+ handleClose
1389
+ ]);
1390
+ const getCellContent = useCallback3(() => {
1391
+ if (model && editing) {
1392
+ const value = model.getCellData(parseCellIndex(editing.index));
1393
+ return value !== void 0 ? String(value) : "";
1394
+ }
1395
+ }, [
1396
+ model,
1397
+ editing
1398
+ ]);
1399
+ return /* @__PURE__ */ React6.createElement(GridCellEditor, {
1400
+ extension,
1401
+ getCellContent,
1402
+ onBlur: handleBlur
1403
+ });
1404
+ };
1405
+ var determineNavigationAxis = ({ key }) => {
1406
+ switch (key) {
1407
+ case "ArrowUp":
1408
+ case "ArrowDown":
1409
+ case "Enter": {
1410
+ return "row";
1411
+ }
1412
+ case "ArrowLeft":
1413
+ case "ArrowRight":
1414
+ case "Tab":
1415
+ return "col";
1416
+ }
1417
+ };
1418
+ var determineNavigationDelta = ({ key, shift }) => {
1419
+ switch (key) {
1420
+ case "ArrowUp":
1421
+ case "ArrowLeft":
1422
+ return -1;
1423
+ case "ArrowDown":
1424
+ case "ArrowRight":
1425
+ return 1;
1426
+ }
1427
+ return shift ? -1 : 1;
1428
+ };
1429
+
1430
+ // packages/ui/react-ui-table/src/components/Table/Table.tsx
1431
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-table/src/components/Table/Table.tsx";
1432
+ var inlineEndLine = "[&>.dx-grid]:relative [&>.dx-grid]:after:absolute [&>.dx-grid]:after:inset-block-0 [&>.dx-grid]:after:-inline-end-px [&>.dx-grid]:after:is-px [&>.dx-grid]:after:bg-separator";
1433
+ var blockEndLine = "[&>.dx-grid]:before:absolute [&>.dx-grid]:before:inset-inline-0 [&>.dx-grid]:before:-block-end-px [&>.dx-grid]:before:bs-px [&>.dx-grid]:before:bg-separator";
1434
+ var frozen = {
1435
+ frozenRowsStart: 1,
1436
+ frozenColsStart: 1,
1437
+ frozenColsEnd: 1
1438
+ };
1439
+ var TableRoot = ({ children, role }) => {
1440
+ return /* @__PURE__ */ React7.createElement("div", {
1441
+ role: "none",
1442
+ className: mx2("relative border-bs !border-separator", role === "section" ? "attention-surface overflow-hidden [&_.dx-grid]:max-is-[--dx-grid-content-inline-size]" : "flex flex-col [&_.dx-grid]:grow [&_.dx-grid]:max-is-[--dx-grid-content-inline-size] [&_.dx-grid]:bs-0 [&_.dx-grid]:max-bs-[--dx-grid-content-block-size]")
1443
+ }, children);
1444
+ };
1445
+ var TableMain = /* @__PURE__ */ forwardRef(({ model, presentation, ignoreAttention }, forwardedRef) => {
1446
+ const [dxGrid, setDxGrid] = useState2(null);
1447
+ const { hasAttention } = useAttention(model?.table ? fullyQualifiedId(model.table) : "table");
1448
+ const { t } = useTranslation3(translationKey);
1449
+ const modals = useMemo4(() => new ModalController(), []);
1450
+ useImperativeHandle(forwardedRef, () => {
1451
+ if (!presentation || !dxGrid) {
1452
+ return {};
1453
+ }
1454
+ dxGrid.getCells = (range, plane) => presentation.getCells(range, plane);
1455
+ return {
1456
+ update: (cell) => {
1457
+ if (cell) {
1458
+ dxGrid.updateIfWithinBounds(cell);
1459
+ } else {
1460
+ dxGrid.updateCells(true);
1461
+ dxGrid.requestUpdate();
1348
1462
  }
1349
1463
  }
1350
1464
  };
1351
- this.setCellData = ({ col, row }, value) => {
1352
- const rowIdx = this._displayToDataIndex.get(row) ?? row;
1353
- const fields = this.table.view?.fields ?? [];
1354
- if (col < 0 || col >= fields.length) {
1465
+ }, [
1466
+ presentation,
1467
+ dxGrid
1468
+ ]);
1469
+ const handleGridClick = useCallback4((event) => {
1470
+ if (!modals) {
1471
+ return;
1472
+ }
1473
+ const buttonSelector = Object.values(tableButtons).map((button) => `button[${button.attr}]`).join(",");
1474
+ const tableButtonElement = event.target.closest(buttonSelector);
1475
+ if (tableButtonElement) {
1476
+ const button = Object.values(tableButtons).find((btn) => tableButtonElement.hasAttribute(btn.attr));
1477
+ if (!button) {
1355
1478
  return;
1356
1479
  }
1357
- const field = fields[col];
1358
- const { props } = this._projection.getFieldProjection(field.id);
1359
- switch (props.format) {
1360
- case FormatEnum3.Ref: {
1361
- setValue(this._rows.value[rowIdx], field.path, value);
1480
+ modals.setTrigger(tableButtonElement);
1481
+ const data = button.getData(tableButtonElement);
1482
+ switch (data.type) {
1483
+ case "rowMenu": {
1484
+ modals.showRowMenu(data.rowIndex);
1362
1485
  break;
1363
1486
  }
1364
- default: {
1365
- setValue(this._rows.value[rowIdx], field.path, parseValue({
1366
- type: props.type,
1367
- format: props.format,
1368
- value
1369
- }));
1487
+ case "columnSettings": {
1488
+ modals.showColumnMenu(data.fieldId);
1370
1489
  break;
1371
1490
  }
1372
- }
1373
- };
1374
- //
1375
- // Interactions
1376
- //
1377
- this.handleGridClick = (event) => {
1378
- if (!this._modalController.handleClick(event)) {
1379
- const target = event.target;
1380
- const selectionCheckbox = target.closest(`input[${tableControls.checkbox.attributes.checkbox}]`);
1381
- if (selectionCheckbox) {
1382
- const isHeader = selectionCheckbox.hasAttribute(tableControls.checkbox.attributes.header);
1383
- if (isHeader) {
1384
- if (this._selection.allRowsSeleted.value) {
1385
- this._selection.setSelection("none");
1386
- } else {
1387
- this._selection.setSelection("all");
1388
- }
1389
- } else {
1390
- const rowIndex = Number(selectionCheckbox.getAttribute(tableControls.checkbox.attributes.checkbox));
1391
- this._selection.toggleSelectionForRowIndex(rowIndex);
1392
- }
1393
- }
1394
- }
1395
- };
1396
- this._table = table;
1397
- this._projection = projection;
1398
- this._sorting.value = sorting.at(0);
1399
- this._pinnedRows = pinnedRows;
1400
- this._onInsertRow = onInsertRow;
1401
- this._onDeleteRows = onDeleteRows;
1402
- this._onDeleteColumn = onDeleteColumn;
1403
- this._onCellUpdate = onCellUpdate;
1404
- this._onRowOrderChanged = onRowOrderChanged;
1405
- }
1406
- get table() {
1407
- return this._table;
1408
- }
1409
- get projection() {
1410
- return this._projection;
1411
- }
1412
- get pinnedRows() {
1413
- return this._pinnedRows;
1414
- }
1415
- get columnMeta() {
1416
- invariant3(this._columnMeta, void 0, {
1417
- F: __dxlog_file5,
1418
- L: 126,
1419
- S: this,
1420
- A: [
1421
- "this._columnMeta",
1422
- ""
1423
- ]
1424
- });
1425
- return this._columnMeta;
1426
- }
1427
- get sorting() {
1428
- return this._sorting.value;
1429
- }
1430
- get modalController() {
1431
- return this._modalController;
1432
- }
1433
- get selection() {
1434
- return this._selection;
1435
- }
1436
- //
1437
- // Initialisation
1438
- //
1439
- async _open() {
1440
- this.initializeColumnMeta();
1441
- this.initializeSorting();
1442
- this.initializeEffects();
1443
- this._selection = new SelectionModel(this._sortedRows, () => this._onRowOrderChanged?.());
1444
- await this._selection.open(this._ctx);
1445
- }
1446
- initializeColumnMeta() {
1447
- this._columnMeta = computed2(() => {
1448
- const fields = this._table.view?.fields ?? [];
1449
- const meta = Object.fromEntries(fields.map((field, index) => [
1450
- index,
1451
- {
1452
- size: field?.size ?? 256,
1453
- resizeable: true
1491
+ case "newColumn": {
1492
+ modals.showColumnCreator();
1493
+ break;
1454
1494
  }
1455
- ]));
1456
- return {
1457
- grid: meta,
1458
- frozenColsStart: {
1459
- 0: {
1460
- size: 30,
1461
- resizeable: false
1462
- }
1463
- },
1464
- frozenColsEnd: {
1465
- 0: {
1466
- size: 40,
1467
- resizeable: false
1468
- }
1495
+ case "referencedCell": {
1496
+ modals.showReferencePanel(data.targetId, data.schemaId);
1497
+ break;
1469
1498
  }
1470
- };
1471
- });
1472
- }
1473
- initializeSorting() {
1474
- this._sortedRows = computed2(() => {
1475
- this._displayToDataIndex.clear();
1476
- const sort = this._sorting.value;
1477
- if (!sort) {
1478
- return this._rows.value;
1479
1499
  }
1480
- const field = this._table.view?.fields.find((field2) => field2.id === sort.fieldId);
1481
- if (!field) {
1482
- return this._rows.value;
1500
+ return;
1501
+ }
1502
+ const controlSelector = Object.values(tableControls).map((control) => `input[${control.attr}]`).join(",");
1503
+ const controlElement = event.target.closest(controlSelector);
1504
+ if (controlElement) {
1505
+ const control = Object.values(tableControls).find((ctrl) => controlElement.hasAttribute(ctrl.attr));
1506
+ if (!control) {
1507
+ return;
1483
1508
  }
1484
- const dataWithIndices = this._rows.value.map((item, index) => {
1485
- const value = getValue2(item, field.path);
1486
- return {
1487
- item,
1488
- index,
1489
- value,
1490
- isEmpty: value == null || value === ""
1491
- };
1492
- });
1493
- const sorted = orderBy(dataWithIndices, [
1494
- "isEmpty",
1495
- "value"
1496
- ], [
1497
- "asc",
1498
- sort.direction
1499
- ]);
1500
- for (let displayIndex = 0; displayIndex < sorted.length; displayIndex++) {
1501
- const { index: dataIndex } = sorted[displayIndex];
1502
- if (displayIndex !== dataIndex) {
1503
- this._displayToDataIndex.set(displayIndex, dataIndex);
1509
+ const data = control.getData(controlElement);
1510
+ switch (data.type) {
1511
+ case "checkbox": {
1512
+ if (data.header) {
1513
+ model?.selection.setSelection(model.selection.allRowsSeleted.value ? "none" : "all");
1514
+ } else {
1515
+ model?.selection.toggleSelectionForRowIndex(data.rowIndex);
1516
+ }
1517
+ break;
1518
+ }
1519
+ case "switch": {
1520
+ if (model) {
1521
+ model.updateCellData({
1522
+ row: data.rowIndex,
1523
+ col: data.colIndex
1524
+ }, (value) => !value);
1525
+ }
1526
+ break;
1504
1527
  }
1505
1528
  }
1506
- return sorted.map(({ item }) => item);
1507
- });
1508
- }
1509
- initializeEffects() {
1510
- const rowOrderWatcher = effect2(() => {
1511
- touch(this._sortedRows.value);
1512
- this._onRowOrderChanged?.();
1513
- });
1514
- this._ctx.onDispose(rowOrderWatcher);
1515
- const rowEffectManager = effect2(() => {
1516
- const { start, end } = touch(this._visibleRange.value);
1517
- const rowEffects = [];
1518
- for (let row = start.row; row <= end.row; row++) {
1519
- rowEffects.push(effect2(() => {
1520
- const obj = this._sortedRows.value[row];
1521
- this?._table?.view?.fields.forEach((field) => touch(getValue2(obj, field.path)));
1522
- this._onCellUpdate?.({
1523
- row,
1524
- col: start.col,
1525
- plane: "grid"
1526
- });
1527
- }));
1528
- }
1529
- return () => rowEffects.forEach((cleanup) => cleanup());
1530
- });
1531
- this._ctx.onDispose(rowEffectManager);
1532
- }
1533
- //
1534
- // Column Operations
1535
- //
1536
- deleteColumn(fieldId) {
1537
- if (!this.table.view) {
1529
+ }
1530
+ }, [
1531
+ model,
1532
+ modals
1533
+ ]);
1534
+ const handleFocus = useCallback4((increment, delta) => {
1535
+ if (dxGrid) {
1536
+ dxGrid.refocus(increment, delta);
1537
+ }
1538
+ }, [
1539
+ dxGrid
1540
+ ]);
1541
+ const handleEnter = useCallback4((cell) => {
1542
+ if (model && cell.row === model.getRowCount() - 1) {
1543
+ model.insertRow(cell.row);
1544
+ if (dxGrid) {
1545
+ requestAnimationFrame(() => {
1546
+ dxGrid?.scrollToRow(cell.row + 1);
1547
+ dxGrid?.refocus("row", 1);
1548
+ });
1549
+ }
1550
+ }
1551
+ }, [
1552
+ model,
1553
+ dxGrid
1554
+ ]);
1555
+ const handleKeyDown = useCallback4((event) => {
1556
+ const cell = closestCell(event.target);
1557
+ if (!model || !cell) {
1538
1558
  return;
1539
1559
  }
1540
- const field = this.table.view.fields.find((field2) => field2.id === fieldId);
1541
- if (field && this._onDeleteColumn) {
1542
- if (this._sorting.value?.fieldId === fieldId) {
1543
- this.clearSort();
1560
+ switch (event.key) {
1561
+ case "Backspace":
1562
+ case "Delete": {
1563
+ model.setCellData(cell, void 0);
1564
+ break;
1544
1565
  }
1545
- this._onDeleteColumn(field.id);
1546
1566
  }
1547
- }
1548
- //
1549
- // Resize
1550
- //
1551
- setColumnWidth(columnIndex, width) {
1552
- const fields = this.table.view?.fields ?? [];
1553
- if (columnIndex < fields.length) {
1554
- const newWidth = Math.max(0, width);
1555
- const field = fields[columnIndex];
1556
- if (field) {
1557
- field.size = newWidth;
1567
+ }, [
1568
+ model
1569
+ ]);
1570
+ const handleAxisResize = useCallback4((event) => {
1571
+ if (event.axis === "col") {
1572
+ const columnIndex = parseInt(event.index, 10);
1573
+ model?.setColumnWidth(columnIndex, event.size);
1574
+ }
1575
+ }, [
1576
+ model
1577
+ ]);
1578
+ const handleWheel = useCallback4((event) => {
1579
+ if (!ignoreAttention && !hasAttention) {
1580
+ event.stopPropagation();
1581
+ }
1582
+ }, [
1583
+ hasAttention,
1584
+ ignoreAttention
1585
+ ]);
1586
+ const handleNewColumn = useCallback4(() => {
1587
+ const columns = model?.getColumnCount();
1588
+ if (dxGrid && columns) {
1589
+ dxGrid.scrollToColumn(columns - 1);
1590
+ }
1591
+ }, [
1592
+ model,
1593
+ dxGrid
1594
+ ]);
1595
+ const handleQuery = useCallback4(async ({ field, props }, text) => {
1596
+ if (model && props.referenceSchema && field.referencePath) {
1597
+ const space = getSpace4(model.table);
1598
+ invariant3(space, void 0, {
1599
+ F: __dxlog_file5,
1600
+ L: 260,
1601
+ S: void 0,
1602
+ A: [
1603
+ "space",
1604
+ ""
1605
+ ]
1606
+ });
1607
+ const schema = space.db.schemaRegistry.getSchema(props.referenceSchema);
1608
+ if (schema) {
1609
+ const { objects } = await space.db.query(Filter.schema(schema)).run();
1610
+ const options = objects.map((obj) => {
1611
+ const value = getValue3(obj, field.referencePath);
1612
+ if (!value || typeof value !== "string") {
1613
+ return void 0;
1614
+ }
1615
+ return {
1616
+ label: value,
1617
+ data: obj
1618
+ };
1619
+ }).filter(isNotFalsy);
1620
+ return [
1621
+ ...options,
1622
+ {
1623
+ label: t("create new object label", {
1624
+ text
1625
+ }),
1626
+ data: createOption(text)
1627
+ }
1628
+ ];
1558
1629
  }
1559
1630
  }
1631
+ return [];
1632
+ }, [
1633
+ model
1634
+ ]);
1635
+ if (!model || !modals) {
1636
+ return /* @__PURE__ */ React7.createElement("span", {
1637
+ role: "none",
1638
+ className: "attention-surface"
1639
+ });
1560
1640
  }
1561
- //
1562
- // Sorting
1563
- //
1564
- setSort(fieldId, direction) {
1565
- this._sorting.value = {
1566
- fieldId,
1567
- direction
1568
- };
1569
- }
1570
- clearSort() {
1571
- this._sorting.value = void 0;
1572
- }
1573
- //
1574
- // Pinning
1575
- //
1576
- // TODO(burdon): Change to setPinned(on/off).
1577
- pinRow(rowIndex, side) {
1578
- this._pinnedRows[side].push(rowIndex);
1579
- }
1580
- unpinRow(rowIndex) {
1581
- this._pinnedRows.top = this._pinnedRows.top.filter((index) => index !== rowIndex);
1582
- this._pinnedRows.bottom = this._pinnedRows.bottom.filter((index) => index !== rowIndex);
1583
- }
1641
+ return /* @__PURE__ */ React7.createElement(Grid.Root, {
1642
+ id: model.table.id ?? "table-grid"
1643
+ }, /* @__PURE__ */ React7.createElement(TableCellEditor, {
1644
+ model,
1645
+ modals,
1646
+ onEnter: handleEnter,
1647
+ onFocus: handleFocus,
1648
+ onQuery: handleQuery
1649
+ }), /* @__PURE__ */ React7.createElement(Grid.Content, {
1650
+ onWheelCapture: handleWheel,
1651
+ className: mx2("[--dx-grid-base:var(--surface-bg)]", inlineEndLine, blockEndLine),
1652
+ frozen,
1653
+ columns: model.columnMeta.value,
1654
+ limitRows: model.getRowCount() ?? 0,
1655
+ limitColumns: model.table.view?.target?.fields?.length ?? 0,
1656
+ onAxisResize: handleAxisResize,
1657
+ onClick: handleGridClick,
1658
+ onKeyDown: handleKeyDown,
1659
+ overscroll: "trap",
1660
+ ref: setDxGrid
1661
+ }), /* @__PURE__ */ React7.createElement(RowActionsMenu, {
1662
+ model,
1663
+ modals
1664
+ }), /* @__PURE__ */ React7.createElement(ColumnActionsMenu, {
1665
+ model,
1666
+ modals
1667
+ }), /* @__PURE__ */ React7.createElement(ColumnSettings, {
1668
+ model,
1669
+ modals,
1670
+ onNewColumn: handleNewColumn
1671
+ }), /* @__PURE__ */ React7.createElement(RefPanel, {
1672
+ model,
1673
+ modals
1674
+ }), /* @__PURE__ */ React7.createElement(CreateRefPanel, {
1675
+ model,
1676
+ modals
1677
+ }));
1678
+ });
1679
+ var Table = {
1680
+ Root: TableRoot,
1681
+ Main: TableMain
1682
+ };
1683
+
1684
+ // packages/ui/react-ui-table/src/components/Toolbar/Toolbar.tsx
1685
+ import { createContext } from "@radix-ui/react-context";
1686
+ import React9 from "react";
1687
+ import { Toolbar as NaturalToolbar2, useTranslation as useTranslation4 } from "@dxos/react-ui";
1688
+
1689
+ // packages/ui/react-ui-table/src/components/Toolbar/common.tsx
1690
+ import React8 from "react";
1691
+ import { Icon, Toolbar as NaturalToolbar, Tooltip } from "@dxos/react-ui";
1692
+ var buttonStyles = "min-bs-0 p-2";
1693
+ var tooltipProps = {
1694
+ side: "top",
1695
+ classNames: "z-10"
1696
+ };
1697
+ var ToolbarSeparator = () => /* @__PURE__ */ React8.createElement("div", {
1698
+ role: "separator",
1699
+ className: "grow"
1700
+ });
1701
+ var ToolbarButton = ({ icon, children, ...props }) => {
1702
+ return /* @__PURE__ */ React8.createElement(Tooltip.Root, null, /* @__PURE__ */ React8.createElement(Tooltip.Trigger, {
1703
+ asChild: true
1704
+ }, /* @__PURE__ */ React8.createElement(NaturalToolbar.Button, {
1705
+ variant: "ghost",
1706
+ ...props,
1707
+ classNames: buttonStyles
1708
+ }, /* @__PURE__ */ React8.createElement(Icon, {
1709
+ icon,
1710
+ size: 5
1711
+ }), /* @__PURE__ */ React8.createElement("span", {
1712
+ className: "sr-only"
1713
+ }, children))), /* @__PURE__ */ React8.createElement(Tooltip.Portal, null, /* @__PURE__ */ React8.createElement(Tooltip.Content, tooltipProps, children, /* @__PURE__ */ React8.createElement(Tooltip.Arrow, null))));
1714
+ };
1715
+
1716
+ // packages/ui/react-ui-table/src/components/Toolbar/Toolbar.tsx
1717
+ var [ToolbarContextProvider, useToolbarContext] = createContext("Toolbar");
1718
+ var ToolbarRoot = ({ classNames, children, onAction }) => {
1719
+ return /* @__PURE__ */ React9.createElement(ToolbarContextProvider, {
1720
+ onAction
1721
+ }, /* @__PURE__ */ React9.createElement(NaturalToolbar2.Root, {
1722
+ classNames: [
1723
+ "is-full shrink-0 overflow-x-auto overflow-y-hidden p-1 attention-surface",
1724
+ classNames
1725
+ ]
1726
+ }, children));
1727
+ };
1728
+ var Editing = () => {
1729
+ const { onAction } = useToolbarContext("Editing");
1730
+ const { t } = useTranslation4(translationKey);
1731
+ return /* @__PURE__ */ React9.createElement(React9.Fragment, null, /* @__PURE__ */ React9.createElement(ToolbarButton, {
1732
+ value: "add-row",
1733
+ icon: "ph--plus--regular",
1734
+ "data-testid": "table.toolbar.add-row",
1735
+ onClick: () => onAction?.({
1736
+ type: "add-row"
1737
+ })
1738
+ }, t("add row")));
1739
+ };
1740
+ var Actions = () => {
1741
+ const { onAction } = useToolbarContext("Actions");
1742
+ const { t } = useTranslation4(translationKey);
1743
+ return /* @__PURE__ */ React9.createElement(React9.Fragment, null, /* @__PURE__ */ React9.createElement(ToolbarButton, {
1744
+ value: "comment",
1745
+ icon: "ph--chat-text--regular",
1746
+ "data-testid": "table.toolbar.comment",
1747
+ onClick: () => onAction?.({
1748
+ type: "comment"
1749
+ })
1750
+ }, t("create comment")));
1751
+ };
1752
+ var Toolbar = {
1753
+ Root: ToolbarRoot,
1754
+ Editing,
1755
+ Actions,
1756
+ Separator: ToolbarSeparator
1584
1757
  };
1585
1758
 
1586
1759
  // packages/ui/react-ui-table/src/hooks/useTableModel.ts
1760
+ import { useEffect as useEffect2, useState as useState3 } from "react";
1587
1761
  var useTableModel = ({ objects, table, projection, ...props }) => {
1588
1762
  const [model, setModel] = useState3();
1589
1763
  useEffect2(() => {
@@ -1619,12 +1793,20 @@ var useTableModel = ({ objects, table, projection, ...props }) => {
1619
1793
  return model;
1620
1794
  };
1621
1795
  export {
1796
+ BUTTON_IDENTIFIERS,
1797
+ CONTROL_IDENTIFIERS,
1798
+ ModalController,
1622
1799
  Table,
1800
+ TableModel,
1801
+ TablePresentation,
1623
1802
  TableSchema,
1624
1803
  TableType,
1625
1804
  Toolbar,
1626
1805
  initializeTable,
1806
+ renderCheckbox,
1807
+ renderSwitch,
1627
1808
  tableButtons,
1809
+ tableControls,
1628
1810
  touch,
1629
1811
  translations_default as translations,
1630
1812
  useTableModel,