@dxos/plugin-sheet 0.8.4-main.7ace549 → 0.8.4-main.937b3ca

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 (199) hide show
  1. package/dist/lib/browser/SheetContainer-ESCXPI7Y.mjs +397 -0
  2. package/dist/lib/browser/SheetContainer-ESCXPI7Y.mjs.map +7 -0
  3. package/dist/lib/browser/{anchor-sort-OWOAGQM6.mjs → anchor-sort-JBRMW6OY.mjs} +7 -7
  4. package/dist/lib/browser/anchor-sort-JBRMW6OY.mjs.map +7 -0
  5. package/dist/lib/browser/chunk-2SAGT3BB.mjs +397 -0
  6. package/dist/lib/browser/chunk-2SAGT3BB.mjs.map +7 -0
  7. package/dist/lib/browser/{chunk-7VEWYJJN.mjs → chunk-IFLWVS2V.mjs} +5 -5
  8. package/dist/lib/browser/chunk-IFLWVS2V.mjs.map +7 -0
  9. package/dist/lib/browser/chunk-W6N44ONZ.mjs +1470 -0
  10. package/dist/lib/browser/chunk-W6N44ONZ.mjs.map +7 -0
  11. package/dist/lib/browser/compute-graph-registry-DL2PX7TF.mjs +21 -0
  12. package/dist/lib/browser/compute-graph-registry-DL2PX7TF.mjs.map +7 -0
  13. package/dist/lib/browser/index.mjs +66 -76
  14. package/dist/lib/browser/index.mjs.map +4 -4
  15. package/dist/lib/browser/markdown-BC4KBDUO.mjs +29 -0
  16. package/dist/lib/browser/markdown-BC4KBDUO.mjs.map +7 -0
  17. package/dist/lib/browser/meta.json +1 -1
  18. package/dist/lib/browser/operation-resolver-FJ4UWZUM.mjs +79 -0
  19. package/dist/lib/browser/operation-resolver-FJ4UWZUM.mjs.map +7 -0
  20. package/dist/lib/browser/{react-surface-VPLFBQSV.mjs → react-surface-5BXM6TJ3.mjs} +16 -19
  21. package/dist/lib/browser/react-surface-5BXM6TJ3.mjs.map +7 -0
  22. package/dist/lib/browser/types/index.mjs +5 -2
  23. package/dist/lib/node-esm/SheetContainer-YVIDJKP4.mjs +398 -0
  24. package/dist/lib/node-esm/SheetContainer-YVIDJKP4.mjs.map +7 -0
  25. package/dist/lib/node-esm/{anchor-sort-FG3DS4HM.mjs → anchor-sort-C3XFPI6S.mjs} +7 -7
  26. package/dist/lib/node-esm/anchor-sort-C3XFPI6S.mjs.map +7 -0
  27. package/dist/lib/node-esm/chunk-IMWGSIDG.mjs +398 -0
  28. package/dist/lib/node-esm/chunk-IMWGSIDG.mjs.map +7 -0
  29. package/dist/lib/node-esm/{chunk-4QV4AGWK.mjs → chunk-PPOYR7DK.mjs} +5 -5
  30. package/dist/lib/node-esm/chunk-PPOYR7DK.mjs.map +7 -0
  31. package/dist/lib/node-esm/chunk-S7RYX7DG.mjs +1471 -0
  32. package/dist/lib/node-esm/chunk-S7RYX7DG.mjs.map +7 -0
  33. package/dist/lib/node-esm/compute-graph-registry-VXH55GDI.mjs +22 -0
  34. package/dist/lib/node-esm/compute-graph-registry-VXH55GDI.mjs.map +7 -0
  35. package/dist/lib/node-esm/index.mjs +66 -76
  36. package/dist/lib/node-esm/index.mjs.map +4 -4
  37. package/dist/lib/node-esm/markdown-6DGZCJRM.mjs +30 -0
  38. package/dist/lib/node-esm/markdown-6DGZCJRM.mjs.map +7 -0
  39. package/dist/lib/node-esm/meta.json +1 -1
  40. package/dist/lib/node-esm/operation-resolver-OGXEUWHA.mjs +80 -0
  41. package/dist/lib/node-esm/operation-resolver-OGXEUWHA.mjs.map +7 -0
  42. package/dist/lib/node-esm/{react-surface-YLTZQVNL.mjs → react-surface-RLHC6B77.mjs} +16 -19
  43. package/dist/lib/node-esm/react-surface-RLHC6B77.mjs.map +7 -0
  44. package/dist/lib/node-esm/types/index.mjs +5 -2
  45. package/dist/types/src/SheetPlugin.d.ts +2 -1
  46. package/dist/types/src/SheetPlugin.d.ts.map +1 -1
  47. package/dist/types/src/capabilities/anchor-sort/anchor-sort.d.ts +5 -0
  48. package/dist/types/src/capabilities/anchor-sort/anchor-sort.d.ts.map +1 -0
  49. package/dist/types/src/capabilities/anchor-sort/index.d.ts +3 -0
  50. package/dist/types/src/capabilities/anchor-sort/index.d.ts.map +1 -0
  51. package/dist/types/src/capabilities/compute-graph-registry/compute-graph-registry.d.ts +5 -0
  52. package/dist/types/src/capabilities/compute-graph-registry/compute-graph-registry.d.ts.map +1 -0
  53. package/dist/types/src/capabilities/compute-graph-registry/index.d.ts +3 -0
  54. package/dist/types/src/capabilities/compute-graph-registry/index.d.ts.map +1 -0
  55. package/dist/types/src/capabilities/index.d.ts +5 -6
  56. package/dist/types/src/capabilities/index.d.ts.map +1 -1
  57. package/dist/types/src/capabilities/markdown/index.d.ts +3 -0
  58. package/dist/types/src/capabilities/markdown/index.d.ts.map +1 -0
  59. package/dist/types/src/capabilities/markdown/markdown.d.ts +5 -0
  60. package/dist/types/src/capabilities/markdown/markdown.d.ts.map +1 -0
  61. package/dist/types/src/capabilities/operation-resolver/index.d.ts +3 -0
  62. package/dist/types/src/capabilities/operation-resolver/index.d.ts.map +1 -0
  63. package/dist/types/src/capabilities/operation-resolver/operation-resolver.d.ts +5 -0
  64. package/dist/types/src/capabilities/operation-resolver/operation-resolver.d.ts.map +1 -0
  65. package/dist/types/src/capabilities/react-surface/index.d.ts +3 -0
  66. package/dist/types/src/capabilities/react-surface/index.d.ts.map +1 -0
  67. package/dist/types/src/capabilities/react-surface/react-surface.d.ts +5 -0
  68. package/dist/types/src/capabilities/react-surface/react-surface.d.ts.map +1 -0
  69. package/dist/types/src/components/GridSheet/GridSheet.d.ts.map +1 -1
  70. package/dist/types/src/components/GridSheet/GridSheet.stories.d.ts.map +1 -1
  71. package/dist/types/src/components/GridSheet/SheetCellEditor.stories.d.ts +1 -1
  72. package/dist/types/src/components/GridSheet/SheetCellEditor.stories.d.ts.map +1 -1
  73. package/dist/types/src/components/RangeList/RangeList.d.ts.map +1 -1
  74. package/dist/types/src/components/SheetContainer/SheetContainer.d.ts +4 -5
  75. package/dist/types/src/components/SheetContainer/SheetContainer.d.ts.map +1 -1
  76. package/dist/types/src/components/SheetContainer/SheetContainer.stories.d.ts +2 -1
  77. package/dist/types/src/components/SheetContainer/SheetContainer.stories.d.ts.map +1 -1
  78. package/dist/types/src/components/SheetToolbar/SheetToolbar.d.ts.map +1 -1
  79. package/dist/types/src/components/SheetToolbar/align.d.ts +12 -19
  80. package/dist/types/src/components/SheetToolbar/align.d.ts.map +1 -1
  81. package/dist/types/src/components/SheetToolbar/style.d.ts +12 -18
  82. package/dist/types/src/components/SheetToolbar/style.d.ts.map +1 -1
  83. package/dist/types/src/components/SheetToolbar/useToolbarState.d.ts +14 -1
  84. package/dist/types/src/components/SheetToolbar/useToolbarState.d.ts.map +1 -1
  85. package/dist/types/src/components/index.d.ts +1 -1
  86. package/dist/types/src/components/index.d.ts.map +1 -1
  87. package/dist/types/src/extensions/compute.stories.d.ts.map +1 -1
  88. package/dist/types/src/extensions/editor/sheet-extension.d.ts.map +1 -1
  89. package/dist/types/src/index.d.ts +1 -1
  90. package/dist/types/src/index.d.ts.map +1 -1
  91. package/dist/types/src/integrations/thread-ranges.d.ts.map +1 -1
  92. package/dist/types/src/meta.d.ts +2 -2
  93. package/dist/types/src/meta.d.ts.map +1 -1
  94. package/dist/types/src/model/sheet-model.d.ts.map +1 -1
  95. package/dist/types/src/testing/testing.d.ts +7 -7
  96. package/dist/types/src/types/Sheet.d.ts +32 -26
  97. package/dist/types/src/types/Sheet.d.ts.map +1 -1
  98. package/dist/types/src/types/capabilities.d.ts +6 -0
  99. package/dist/types/src/types/capabilities.d.ts.map +1 -0
  100. package/dist/types/src/types/index.d.ts +1 -0
  101. package/dist/types/src/types/index.d.ts.map +1 -1
  102. package/dist/types/src/types/types.d.ts +91 -65
  103. package/dist/types/src/types/types.d.ts.map +1 -1
  104. package/dist/types/tsconfig.tsbuildinfo +1 -1
  105. package/package.json +75 -70
  106. package/src/SheetPlugin.tsx +42 -58
  107. package/src/capabilities/anchor-sort/anchor-sort.ts +26 -0
  108. package/src/capabilities/anchor-sort/index.ts +7 -0
  109. package/src/capabilities/compute-graph-registry/compute-graph-registry.ts +27 -0
  110. package/src/capabilities/compute-graph-registry/index.ts +7 -0
  111. package/src/capabilities/index.ts +5 -9
  112. package/src/capabilities/markdown/index.ts +7 -0
  113. package/src/capabilities/markdown/markdown.ts +30 -0
  114. package/src/capabilities/operation-resolver/index.ts +7 -0
  115. package/src/capabilities/operation-resolver/operation-resolver.ts +77 -0
  116. package/src/capabilities/react-surface/index.ts +7 -0
  117. package/src/capabilities/react-surface/react-surface.tsx +43 -0
  118. package/src/components/ComputeGraph/compute-graph.stories.tsx +1 -1
  119. package/src/components/GridSheet/GridSheet.stories.tsx +2 -2
  120. package/src/components/GridSheet/GridSheet.tsx +14 -19
  121. package/src/components/GridSheet/SheetCellEditor.stories.tsx +6 -3
  122. package/src/components/GridSheet/util.ts +1 -1
  123. package/src/components/RangeList/RangeList.tsx +5 -2
  124. package/src/components/SheetContainer/SheetContainer.stories.tsx +41 -21
  125. package/src/components/SheetContainer/SheetContainer.tsx +27 -20
  126. package/src/components/SheetContext/SheetContext.tsx +4 -4
  127. package/src/components/SheetToolbar/SheetToolbar.tsx +29 -18
  128. package/src/components/SheetToolbar/align.ts +41 -16
  129. package/src/components/SheetToolbar/style.ts +45 -15
  130. package/src/components/SheetToolbar/useToolbarState.ts +22 -5
  131. package/src/extensions/compute.stories.tsx +15 -6
  132. package/src/extensions/compute.ts +1 -1
  133. package/src/extensions/editor/sheet-extension.ts +7 -4
  134. package/src/index.ts +1 -1
  135. package/src/integrations/thread-ranges.ts +36 -40
  136. package/src/meta.ts +2 -2
  137. package/src/model/sheet-model.ts +67 -37
  138. package/src/playwright/playwright.config.ts +1 -1
  139. package/src/playwright/sheet.spec.ts +1 -0
  140. package/src/sanity.test.ts +1 -1
  141. package/src/types/Sheet.ts +16 -13
  142. package/src/{capabilities → types}/capabilities.ts +2 -2
  143. package/src/types/index.ts +1 -0
  144. package/src/types/types.ts +81 -37
  145. package/dist/lib/browser/SheetContainer-WDKJPYCB.mjs +0 -349
  146. package/dist/lib/browser/SheetContainer-WDKJPYCB.mjs.map +0 -7
  147. package/dist/lib/browser/anchor-sort-OWOAGQM6.mjs.map +0 -7
  148. package/dist/lib/browser/chunk-6ILNTWSF.mjs +0 -852
  149. package/dist/lib/browser/chunk-6ILNTWSF.mjs.map +0 -7
  150. package/dist/lib/browser/chunk-73AV3NH6.mjs +0 -15
  151. package/dist/lib/browser/chunk-73AV3NH6.mjs.map +0 -7
  152. package/dist/lib/browser/chunk-7VEWYJJN.mjs.map +0 -7
  153. package/dist/lib/browser/chunk-FWFAAGXL.mjs +0 -28
  154. package/dist/lib/browser/chunk-FWFAAGXL.mjs.map +0 -7
  155. package/dist/lib/browser/chunk-GBK6OLCY.mjs +0 -907
  156. package/dist/lib/browser/chunk-GBK6OLCY.mjs.map +0 -7
  157. package/dist/lib/browser/compute-graph-registry-AP5RA7W3.mjs +0 -21
  158. package/dist/lib/browser/compute-graph-registry-AP5RA7W3.mjs.map +0 -7
  159. package/dist/lib/browser/intent-resolver-OMHQGXFL.mjs +0 -56
  160. package/dist/lib/browser/intent-resolver-OMHQGXFL.mjs.map +0 -7
  161. package/dist/lib/browser/markdown-B6VKYY2S.mjs +0 -26
  162. package/dist/lib/browser/markdown-B6VKYY2S.mjs.map +0 -7
  163. package/dist/lib/browser/react-surface-VPLFBQSV.mjs.map +0 -7
  164. package/dist/lib/node-esm/SheetContainer-62MZAU6Q.mjs +0 -350
  165. package/dist/lib/node-esm/SheetContainer-62MZAU6Q.mjs.map +0 -7
  166. package/dist/lib/node-esm/anchor-sort-FG3DS4HM.mjs.map +0 -7
  167. package/dist/lib/node-esm/chunk-44YTKTMP.mjs +0 -16
  168. package/dist/lib/node-esm/chunk-44YTKTMP.mjs.map +0 -7
  169. package/dist/lib/node-esm/chunk-4QV4AGWK.mjs.map +0 -7
  170. package/dist/lib/node-esm/chunk-HILDMVPL.mjs +0 -29
  171. package/dist/lib/node-esm/chunk-HILDMVPL.mjs.map +0 -7
  172. package/dist/lib/node-esm/chunk-KSHCRK5J.mjs +0 -908
  173. package/dist/lib/node-esm/chunk-KSHCRK5J.mjs.map +0 -7
  174. package/dist/lib/node-esm/chunk-QI3PNRCD.mjs +0 -853
  175. package/dist/lib/node-esm/chunk-QI3PNRCD.mjs.map +0 -7
  176. package/dist/lib/node-esm/compute-graph-registry-UMQ5UYCL.mjs +0 -22
  177. package/dist/lib/node-esm/compute-graph-registry-UMQ5UYCL.mjs.map +0 -7
  178. package/dist/lib/node-esm/intent-resolver-DHEHYV3B.mjs +0 -57
  179. package/dist/lib/node-esm/intent-resolver-DHEHYV3B.mjs.map +0 -7
  180. package/dist/lib/node-esm/markdown-VKY7HXU2.mjs +0 -27
  181. package/dist/lib/node-esm/markdown-VKY7HXU2.mjs.map +0 -7
  182. package/dist/lib/node-esm/react-surface-YLTZQVNL.mjs.map +0 -7
  183. package/dist/types/src/capabilities/anchor-sort.d.ts +0 -4
  184. package/dist/types/src/capabilities/anchor-sort.d.ts.map +0 -1
  185. package/dist/types/src/capabilities/capabilities.d.ts +0 -5
  186. package/dist/types/src/capabilities/capabilities.d.ts.map +0 -1
  187. package/dist/types/src/capabilities/compute-graph-registry.d.ts +0 -4
  188. package/dist/types/src/capabilities/compute-graph-registry.d.ts.map +0 -1
  189. package/dist/types/src/capabilities/intent-resolver.d.ts +0 -4
  190. package/dist/types/src/capabilities/intent-resolver.d.ts.map +0 -1
  191. package/dist/types/src/capabilities/markdown.d.ts +0 -4
  192. package/dist/types/src/capabilities/markdown.d.ts.map +0 -1
  193. package/dist/types/src/capabilities/react-surface.d.ts +0 -4
  194. package/dist/types/src/capabilities/react-surface.d.ts.map +0 -1
  195. package/src/capabilities/anchor-sort.ts +0 -21
  196. package/src/capabilities/compute-graph-registry.ts +0 -23
  197. package/src/capabilities/intent-resolver.ts +0 -38
  198. package/src/capabilities/markdown.ts +0 -23
  199. package/src/capabilities/react-surface.tsx +0 -41
@@ -0,0 +1,1470 @@
1
+ import {
2
+ rangeExtension,
3
+ sheetExtension
4
+ } from "./chunk-IFLWVS2V.mjs";
5
+ import {
6
+ DEFAULT_COLS,
7
+ DEFAULT_ROWS,
8
+ MAX_COLS,
9
+ MAX_ROWS,
10
+ ReadonlyException,
11
+ SheetOperation,
12
+ Sheet_exports,
13
+ addressFromIndex,
14
+ addressToIndex,
15
+ cellClassNameForRange,
16
+ initialize,
17
+ insertIndices,
18
+ mapFormulaIndicesToRefs,
19
+ mapFormulaRefsToIndices,
20
+ meta,
21
+ rangeFromIndex
22
+ } from "./chunk-2SAGT3BB.mjs";
23
+
24
+ // src/components/ComputeGraph/ComputeGraphContextProvider.tsx
25
+ import React, { createContext, useContext } from "react";
26
+ import { raise } from "@dxos/debug";
27
+ import { useAsyncState } from "@dxos/react-hooks";
28
+ var ComputeGraphContext = /* @__PURE__ */ createContext(void 0);
29
+ var ComputeGraphContextProvider = ({ registry, children }) => {
30
+ return /* @__PURE__ */ React.createElement(ComputeGraphContext.Provider, {
31
+ value: {
32
+ registry
33
+ }
34
+ }, children);
35
+ };
36
+ var useComputeGraph = (space) => {
37
+ const { registry } = useContext(ComputeGraphContext) ?? raise(new Error("Missing ComputeGraphContext"));
38
+ const [graph] = useAsyncState(async () => {
39
+ if (space) {
40
+ const graph2 = registry.getOrCreateGraph(space);
41
+ await graph2.open();
42
+ return graph2;
43
+ }
44
+ }, [
45
+ space,
46
+ registry
47
+ ]);
48
+ return graph;
49
+ };
50
+
51
+ // src/components/RangeList/RangeList.tsx
52
+ import * as Schema from "effect/Schema";
53
+ import React2, { useCallback } from "react";
54
+ import { rangeToA1Notation } from "@dxos/compute";
55
+ import { Obj } from "@dxos/echo";
56
+ import { Callout, useTranslation } from "@dxos/react-ui";
57
+ import { List } from "@dxos/react-ui-list";
58
+ import { ghostHover } from "@dxos/ui-theme";
59
+ var RangeList = ({ sheet }) => {
60
+ const { t } = useTranslation(meta.id);
61
+ const handleSelectRange = (range) => {
62
+ };
63
+ const handleDeleteRange = useCallback((range) => {
64
+ const index = sheet.ranges.findIndex((sheetRange) => sheetRange === range);
65
+ Obj.change(sheet, (s) => {
66
+ s.ranges.splice(index, 1);
67
+ });
68
+ }, [
69
+ sheet
70
+ ]);
71
+ return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("h2", {
72
+ className: "mbs-cardSpacingBlock mbe-labelSpacingBlock text-sm font-semibold"
73
+ }, t("range list heading")), sheet.ranges.length < 1 ? /* @__PURE__ */ React2.createElement(Callout.Root, null, /* @__PURE__ */ React2.createElement(Callout.Title, null, t("no ranges message"))) : /* @__PURE__ */ React2.createElement(List.Root, {
74
+ items: sheet.ranges,
75
+ isItem: Schema.is(Sheet_exports.Range)
76
+ }, ({ items: ranges }) => ranges.map((range, i) => /* @__PURE__ */ React2.createElement(List.Item, {
77
+ key: i,
78
+ item: range,
79
+ classNames: [
80
+ "p-2",
81
+ ghostHover
82
+ ]
83
+ }, /* @__PURE__ */ React2.createElement(List.ItemDragHandle, null), /* @__PURE__ */ React2.createElement(List.ItemTitle, {
84
+ onClick: () => handleSelectRange(range)
85
+ }, t("range title", {
86
+ position: rangeToA1Notation(rangeFromIndex(sheet, range.range)),
87
+ key: t(`range key ${range.key} label`),
88
+ value: t(`range value ${range.value} label`)
89
+ })), /* @__PURE__ */ React2.createElement(List.ItemDeleteButton, {
90
+ onClick: () => handleDeleteRange(range)
91
+ })))));
92
+ };
93
+
94
+ // src/components/index.ts
95
+ import { lazy } from "react";
96
+
97
+ // src/components/GridSheet/GridSheet.tsx
98
+ import React4, { useCallback as useCallback4, useMemo as useMemo2, useRef, useState as useState4 } from "react";
99
+ import { useOperationInvoker as useOperationInvoker2 } from "@dxos/app-framework/react";
100
+ import { rangeToA1Notation as rangeToA1Notation2 } from "@dxos/compute";
101
+ import { defaultColSize, defaultRowSize } from "@dxos/lit-grid";
102
+ import { DropdownMenu, Icon, useTranslation as useTranslation2 } from "@dxos/react-ui";
103
+ import { useAttention } from "@dxos/react-ui-attention";
104
+ import { Grid as Grid2, GridCellEditor, closestCell, editorKeys, parseCellIndex } from "@dxos/react-ui-grid";
105
+
106
+ // src/integrations/thread-ranges.ts
107
+ import * as Effect from "effect/Effect";
108
+ import { useCallback as useCallback2, useEffect, useMemo } from "react";
109
+ import { Common } from "@dxos/app-framework";
110
+ import { useOperationInvoker, useOperationResolver } from "@dxos/app-framework/react";
111
+ import { debounce } from "@dxos/async";
112
+ import { inRange } from "@dxos/compute";
113
+ import { Obj as Obj2, Relation } from "@dxos/echo";
114
+ import { OperationResolver } from "@dxos/operation";
115
+ import { ATTENDABLE_PATH_SEPARATOR, DeckOperation } from "@dxos/plugin-deck/types";
116
+ import { ThreadOperation } from "@dxos/plugin-thread/types";
117
+ import { Filter, Query, useQuery } from "@dxos/react-client/echo";
118
+ import { AnchoredTo, Thread } from "@dxos/types";
119
+ var parseThreadAnchorAsCellRange = (cursor) => {
120
+ const coords = cursor.split(",");
121
+ if (coords.length !== 4) {
122
+ return null;
123
+ } else {
124
+ const [fromCol, fromRow, toCol, toRow] = coords;
125
+ return {
126
+ from: {
127
+ col: parseInt(fromCol),
128
+ row: parseInt(fromRow)
129
+ },
130
+ to: {
131
+ col: parseInt(toCol),
132
+ row: parseInt(toRow)
133
+ }
134
+ };
135
+ }
136
+ };
137
+ var useUpdateFocusedCellOnThreadSelection = (grid) => {
138
+ const { model, setActiveRefs } = useSheetContext();
139
+ const sheetId = Obj2.getDXN(model.sheet).toString();
140
+ const scrollIntoViewHandler = useMemo(() => OperationResolver.make({
141
+ operation: Common.LayoutOperation.ScrollIntoView,
142
+ position: "hoist",
143
+ filter: (input) => input.subject === sheetId && !!input.cursor,
144
+ handler: (input) => Effect.sync(() => {
145
+ const { cursor, ref } = input;
146
+ if (cursor) {
147
+ setActiveRefs(ref);
148
+ const range = parseThreadAnchorAsCellRange(cursor);
149
+ range && grid?.setFocus({
150
+ ...range.to,
151
+ plane: "grid"
152
+ }, true);
153
+ }
154
+ })
155
+ }), [
156
+ sheetId,
157
+ setActiveRefs,
158
+ grid
159
+ ]);
160
+ useOperationResolver(meta.id, scrollIntoViewHandler);
161
+ };
162
+ var useSelectThreadOnCellFocus = () => {
163
+ const { model, cursor } = useSheetContext();
164
+ const { invokePromise } = useOperationInvoker();
165
+ const db = Obj2.getDatabase(model.sheet);
166
+ const anchors = useQuery(db, Query.select(Filter.id(model.sheet.id)).targetOf(AnchoredTo.AnchoredTo));
167
+ const selectClosestThread = useCallback2((cellAddress) => {
168
+ if (!cellAddress) {
169
+ return;
170
+ }
171
+ const closestThread = anchors.find((anchor) => {
172
+ const source = Relation.getSource(anchor);
173
+ if (anchor.anchor && Obj2.instanceOf(Thread.Thread, source)) {
174
+ const range = parseThreadAnchorAsCellRange(anchor.anchor);
175
+ return range ? inRange(range, cellAddress) : false;
176
+ } else {
177
+ return false;
178
+ }
179
+ });
180
+ if (closestThread) {
181
+ const primary = Obj2.getDXN(model.sheet).toString();
182
+ void (async () => {
183
+ await invokePromise(ThreadOperation.Select, {
184
+ current: Relation.getDXN(closestThread).toString()
185
+ });
186
+ await invokePromise(DeckOperation.ChangeCompanion, {
187
+ primary,
188
+ companion: `${primary}${ATTENDABLE_PATH_SEPARATOR}comments`
189
+ });
190
+ })();
191
+ }
192
+ }, [
193
+ invokePromise,
194
+ anchors
195
+ ]);
196
+ const debounced = useMemo(() => {
197
+ return debounce((cellCoords) => requestAnimationFrame(() => selectClosestThread(cellCoords)), 50);
198
+ }, [
199
+ selectClosestThread
200
+ ]);
201
+ useEffect(() => {
202
+ if (!cursor) {
203
+ return;
204
+ }
205
+ debounced(cursor);
206
+ }, [
207
+ cursor,
208
+ debounced
209
+ ]);
210
+ };
211
+
212
+ // src/components/SheetContext/SheetContext.tsx
213
+ import React3, { createContext as createContext2, useCallback as useCallback3, useContext as useContext2, useState as useState2 } from "react";
214
+ import { Obj as Obj4 } from "@dxos/echo";
215
+ import { invariant as invariant2 } from "@dxos/invariant";
216
+ import { Grid, useGridContext } from "@dxos/react-ui-grid";
217
+
218
+ // src/model/sheet-model.ts
219
+ import { Event } from "@dxos/async";
220
+ import { DetailedCellError, ExportedCellChange, addressFromA1Notation, addressToA1Notation, createSheetName, isFormula } from "@dxos/compute";
221
+ import { Resource } from "@dxos/context";
222
+ import { Obj as Obj3 } from "@dxos/echo";
223
+ import { Format, TypeEnum } from "@dxos/echo/internal";
224
+ import { invariant } from "@dxos/invariant";
225
+ import { PublicKey } from "@dxos/keys";
226
+ import { log } from "@dxos/log";
227
+ var __dxlog_file = "/__w/dxos/dxos/packages/plugins/plugin-sheet/src/model/sheet-model.ts";
228
+ var typeMap = {
229
+ BOOLEAN: {
230
+ type: TypeEnum.Boolean
231
+ },
232
+ NUMBER_RAW: {
233
+ type: TypeEnum.Number
234
+ },
235
+ NUMBER_PERCENT: {
236
+ type: TypeEnum.Number,
237
+ format: Format.TypeFormat.Percent
238
+ },
239
+ NUMBER_CURRENCY: {
240
+ type: TypeEnum.Number,
241
+ format: Format.TypeFormat.Currency
242
+ },
243
+ NUMBER_DATETIME: {
244
+ type: TypeEnum.String,
245
+ format: Format.TypeFormat.DateTime
246
+ },
247
+ NUMBER_DATE: {
248
+ type: TypeEnum.String,
249
+ format: Format.TypeFormat.Date
250
+ },
251
+ NUMBER_TIME: {
252
+ type: TypeEnum.String,
253
+ format: Format.TypeFormat.Time
254
+ }
255
+ };
256
+ var getTopLeft = (range) => {
257
+ const to = range.to ?? range.from;
258
+ return {
259
+ row: Math.min(range.from.row, to.row),
260
+ col: Math.min(range.from.col, to.col)
261
+ };
262
+ };
263
+ var toSimpleCellAddress = (sheet, cell) => ({
264
+ sheet,
265
+ row: cell.row,
266
+ col: cell.col
267
+ });
268
+ var toModelRange = (sheet, range) => ({
269
+ start: toSimpleCellAddress(sheet, range.from),
270
+ end: toSimpleCellAddress(sheet, range.to ?? range.from)
271
+ });
272
+ var SheetModel = class extends Resource {
273
+ _graph;
274
+ _sheet;
275
+ _options;
276
+ id = `model-${PublicKey.random().truncate()}`;
277
+ // Wraps compute node.
278
+ update = new Event();
279
+ _node;
280
+ constructor(_graph, _sheet, _options = {}) {
281
+ super(), this._graph = _graph, this._sheet = _sheet, this._options = _options;
282
+ }
283
+ get graph() {
284
+ return this._graph;
285
+ }
286
+ get sheet() {
287
+ return this._sheet;
288
+ }
289
+ get readonly() {
290
+ return this._options.readonly;
291
+ }
292
+ get bounds() {
293
+ return {
294
+ rows: this._sheet.rows.length,
295
+ columns: this._sheet.columns.length
296
+ };
297
+ }
298
+ /**
299
+ * Initialize sheet and engine.
300
+ */
301
+ async _open() {
302
+ log("initialize", {
303
+ id: this.id
304
+ }, {
305
+ F: __dxlog_file,
306
+ L: 124,
307
+ S: this,
308
+ C: (f, a) => f(...a)
309
+ });
310
+ Obj3.change(this._sheet, (s) => {
311
+ initialize(s);
312
+ });
313
+ this._graph.update.on((event) => {
314
+ if (event.type === "functionsUpdated") {
315
+ this.reset();
316
+ }
317
+ });
318
+ this._node = this._graph.getOrCreateNode(createSheetName({
319
+ type: Obj3.getTypename(this._sheet),
320
+ id: this._sheet.id
321
+ }));
322
+ await this._node.open();
323
+ const unsubscribe = this._node.update.on((event) => this.update.emit(event));
324
+ this._ctx.onDispose(unsubscribe);
325
+ this.reset();
326
+ }
327
+ /**
328
+ * Update engine.
329
+ * NOTE: This resets the undo history.
330
+ * @deprecated
331
+ */
332
+ reset() {
333
+ invariant(this._node, void 0, {
334
+ F: __dxlog_file,
335
+ L: 154,
336
+ S: this,
337
+ A: [
338
+ "this._node",
339
+ ""
340
+ ]
341
+ });
342
+ this._node.graph.hf.clearSheet(this._node.sheetId);
343
+ Object.entries(this._sheet.cells).forEach(([key, { value }]) => {
344
+ invariant(this._node, void 0, {
345
+ F: __dxlog_file,
346
+ L: 157,
347
+ S: this,
348
+ A: [
349
+ "this._node",
350
+ ""
351
+ ]
352
+ });
353
+ const { col, row } = addressFromIndex(this._sheet, key);
354
+ if (isFormula(value)) {
355
+ const binding = this._graph.mapFunctionBindingFromId(mapFormulaIndicesToRefs(this._sheet, value));
356
+ if (binding) {
357
+ value = this._graph.mapFormulaToNative(binding);
358
+ } else {
359
+ value = "";
360
+ }
361
+ }
362
+ this._node.graph.hf.setCellContents({
363
+ sheet: this._node.sheetId,
364
+ row,
365
+ col
366
+ }, value);
367
+ });
368
+ }
369
+ /**
370
+ * Recalculate formulas.
371
+ * NOTE: This resets the undo history.
372
+ * https://hyperformula.handsontable.com/guide/volatile-functions.html#volatile-actions
373
+ * @deprecated
374
+ */
375
+ // TODO(burdon): Remove.
376
+ recalculate() {
377
+ this._node?.graph.hf.rebuildAndRecalculate();
378
+ }
379
+ insertRows(i, n = 1) {
380
+ let idx = [];
381
+ Obj3.change(this._sheet, (s) => {
382
+ idx = insertIndices(s.rows, i, n, MAX_ROWS);
383
+ });
384
+ this.reset();
385
+ return idx;
386
+ }
387
+ insertColumns(i, n = 1) {
388
+ let idx = [];
389
+ Obj3.change(this._sheet, (s) => {
390
+ idx = insertIndices(s.columns, i, n, MAX_COLS);
391
+ });
392
+ this.reset();
393
+ return idx;
394
+ }
395
+ dropRow(rowIndex) {
396
+ const range = {
397
+ from: addressFromIndex(this._sheet, `${this._sheet.columns[0]}@${rowIndex}`),
398
+ to: addressFromIndex(this._sheet, `${this._sheet.columns[this._sheet.columns.length - 1]}@${rowIndex}`)
399
+ };
400
+ const values = this.getCellValues(range).flat();
401
+ const index = this._sheet.rows.indexOf(rowIndex);
402
+ this.clear(range);
403
+ Obj3.change(this._sheet, (s) => {
404
+ s.rows.splice(index, 1);
405
+ delete s.rowMeta[rowIndex];
406
+ });
407
+ this.reset();
408
+ return {
409
+ axis: "row",
410
+ index,
411
+ axisIndex: rowIndex,
412
+ axisMeta: this._sheet.rowMeta[rowIndex],
413
+ values
414
+ };
415
+ }
416
+ dropColumn(colIndex) {
417
+ const range = {
418
+ from: addressFromIndex(this._sheet, `${colIndex}@${this._sheet.rows[0]}`),
419
+ to: addressFromIndex(this._sheet, `${colIndex}@${this._sheet.rows[this._sheet.rows.length - 1]}`)
420
+ };
421
+ const values = this.getCellValues(range).flat();
422
+ const index = this._sheet.columns.indexOf(colIndex);
423
+ this.clear(range);
424
+ Obj3.change(this._sheet, (s) => {
425
+ s.columns.splice(index, 1);
426
+ delete s.columnMeta[colIndex];
427
+ });
428
+ this.reset();
429
+ return {
430
+ axis: "col",
431
+ index,
432
+ axisIndex: colIndex,
433
+ axisMeta: this._sheet.rowMeta[colIndex],
434
+ values
435
+ };
436
+ }
437
+ restoreRow({ index, axisIndex, axisMeta, values }) {
438
+ Obj3.change(this._sheet, (s) => {
439
+ s.rows.splice(index, 0, axisIndex);
440
+ values.forEach((value, col) => {
441
+ if (value) {
442
+ s.cells[`${s.columns[col]}@${axisIndex}`] = {
443
+ value
444
+ };
445
+ }
446
+ });
447
+ if (axisMeta) {
448
+ s.rowMeta[axisIndex] = axisMeta;
449
+ }
450
+ });
451
+ this.reset();
452
+ }
453
+ restoreColumn({ index, axisIndex, axisMeta, values }) {
454
+ Obj3.change(this._sheet, (s) => {
455
+ s.columns.splice(index, 0, axisIndex);
456
+ values.forEach((value, row) => {
457
+ if (value) {
458
+ s.cells[`${axisIndex}@${s.rows[row]}`] = {
459
+ value
460
+ };
461
+ }
462
+ });
463
+ if (axisMeta) {
464
+ s.columnMeta[axisIndex] = axisMeta;
465
+ }
466
+ });
467
+ this.reset();
468
+ }
469
+ //
470
+ // Undoable actions.
471
+ // TODO(burdon): Group undoable methods; consistently update hf/sheet.
472
+ //
473
+ /**
474
+ * Clear range of values.
475
+ */
476
+ clear(range) {
477
+ invariant(this._node, void 0, {
478
+ F: __dxlog_file,
479
+ L: 274,
480
+ S: this,
481
+ A: [
482
+ "this._node",
483
+ ""
484
+ ]
485
+ });
486
+ const topLeft = getTopLeft(range);
487
+ const values = this._iterRange(range, () => null);
488
+ this._node.graph.hf.setCellContents(toSimpleCellAddress(this._node.sheetId, topLeft), values);
489
+ Obj3.change(this._sheet, (s) => {
490
+ this._iterRange(range, (cell) => {
491
+ const idx = addressToIndex(this._sheet, cell);
492
+ delete s.cells[idx];
493
+ });
494
+ });
495
+ }
496
+ cut(range) {
497
+ invariant(this._node, void 0, {
498
+ F: __dxlog_file,
499
+ L: 287,
500
+ S: this,
501
+ A: [
502
+ "this._node",
503
+ ""
504
+ ]
505
+ });
506
+ this._node.graph.hf.cut(toModelRange(this._node.sheetId, range));
507
+ Obj3.change(this._sheet, (s) => {
508
+ this._iterRange(range, (cell) => {
509
+ const idx = addressToIndex(this._sheet, cell);
510
+ delete s.cells[idx];
511
+ });
512
+ });
513
+ }
514
+ copy(range) {
515
+ invariant(this._node, void 0, {
516
+ F: __dxlog_file,
517
+ L: 298,
518
+ S: this,
519
+ A: [
520
+ "this._node",
521
+ ""
522
+ ]
523
+ });
524
+ this._node.graph.hf.copy(toModelRange(this._node.sheetId, range));
525
+ }
526
+ paste(cell) {
527
+ invariant(this._node, void 0, {
528
+ F: __dxlog_file,
529
+ L: 303,
530
+ S: this,
531
+ A: [
532
+ "this._node",
533
+ ""
534
+ ]
535
+ });
536
+ if (!this._node.graph.hf.isClipboardEmpty()) {
537
+ const changes = this._node.graph.hf.paste(toSimpleCellAddress(this._node.sheetId, cell));
538
+ Obj3.change(this._sheet, (s) => {
539
+ for (const change of changes) {
540
+ if (change instanceof ExportedCellChange) {
541
+ const { address, newValue } = change;
542
+ const idx = addressToIndex(this._sheet, {
543
+ row: address.row,
544
+ col: address.col
545
+ });
546
+ s.cells[idx] = {
547
+ value: newValue
548
+ };
549
+ }
550
+ }
551
+ });
552
+ }
553
+ }
554
+ // TODO(burdon): Display undo/redo state.
555
+ undo() {
556
+ invariant(this._node, void 0, {
557
+ F: __dxlog_file,
558
+ L: 320,
559
+ S: this,
560
+ A: [
561
+ "this._node",
562
+ ""
563
+ ]
564
+ });
565
+ if (this._node.graph.hf.isThereSomethingToUndo()) {
566
+ this._node.graph.hf.undo();
567
+ }
568
+ }
569
+ redo() {
570
+ invariant(this._node, void 0, {
571
+ F: __dxlog_file,
572
+ L: 328,
573
+ S: this,
574
+ A: [
575
+ "this._node",
576
+ ""
577
+ ]
578
+ });
579
+ if (this._node.graph.hf.isThereSomethingToRedo()) {
580
+ this._node.graph.hf.redo();
581
+ }
582
+ }
583
+ /**
584
+ * Get value from sheet.
585
+ */
586
+ getCellValue(cell) {
587
+ const idx = addressToIndex(this._sheet, cell);
588
+ return this._sheet.cells[idx]?.value ?? null;
589
+ }
590
+ /**
591
+ * Get value as a string for editing.
592
+ */
593
+ getCellText(cell) {
594
+ const value = this.getCellValue(cell);
595
+ if (value == null) {
596
+ return void 0;
597
+ }
598
+ if (isFormula(value)) {
599
+ return this._graph.mapFunctionBindingFromId(mapFormulaIndicesToRefs(this._sheet, value));
600
+ } else {
601
+ return String(value);
602
+ }
603
+ }
604
+ /**
605
+ * Get array of raw values from sheet.
606
+ */
607
+ getCellValues(range) {
608
+ return this._iterRange(range, (cell) => this.getCellValue(cell));
609
+ }
610
+ /**
611
+ * Gets the regular or computed value from the engine.
612
+ */
613
+ getValue(cell) {
614
+ invariant(this._node, void 0, {
615
+ F: __dxlog_file,
616
+ L: 371,
617
+ S: this,
618
+ A: [
619
+ "this._node",
620
+ ""
621
+ ]
622
+ });
623
+ const address = toSimpleCellAddress(this._node.sheetId, cell);
624
+ const value = this._node.graph.hf.getCellValue(address);
625
+ if (value instanceof DetailedCellError) {
626
+ log.warn("cell error", {
627
+ cell,
628
+ error: value
629
+ }, {
630
+ F: __dxlog_file,
631
+ L: 376,
632
+ S: this,
633
+ C: (f, a) => f(...a)
634
+ });
635
+ return value.toString();
636
+ }
637
+ return value;
638
+ }
639
+ /**
640
+ * Get value type.
641
+ */
642
+ getValueDescription(cell) {
643
+ invariant(this._node, void 0, {
644
+ F: __dxlog_file,
645
+ L: 387,
646
+ S: this,
647
+ A: [
648
+ "this._node",
649
+ ""
650
+ ]
651
+ });
652
+ const addr = toSimpleCellAddress(this._node.sheetId, cell);
653
+ const type = this._node.graph.hf.getCellValueDetailedType(addr);
654
+ return typeMap[type];
655
+ }
656
+ /**
657
+ * Sets the value, updating the sheet and engine.
658
+ */
659
+ setValue(cell, value) {
660
+ invariant(this._node, void 0, {
661
+ F: __dxlog_file,
662
+ L: 397,
663
+ S: this,
664
+ A: [
665
+ "this._node",
666
+ ""
667
+ ]
668
+ });
669
+ if (this._options.readonly) {
670
+ throw new ReadonlyException();
671
+ }
672
+ let refresh = false;
673
+ if (cell.row >= this._sheet.rows.length) {
674
+ Obj3.change(this._sheet, (s) => {
675
+ insertIndices(s.rows, cell.row, 1, MAX_ROWS);
676
+ });
677
+ refresh = true;
678
+ }
679
+ if (cell.col >= this._sheet.columns.length) {
680
+ Obj3.change(this._sheet, (s) => {
681
+ insertIndices(s.columns, cell.col, 1, MAX_COLS);
682
+ });
683
+ refresh = true;
684
+ }
685
+ if (refresh) {
686
+ this.reset();
687
+ }
688
+ this._node.graph.hf.setCellContents({
689
+ sheet: this._node.sheetId,
690
+ row: cell.row,
691
+ col: cell.col
692
+ }, [
693
+ [
694
+ isFormula(value) ? this._graph.mapFormulaToNative(value) : value
695
+ ]
696
+ ]);
697
+ const idx = addressToIndex(this._sheet, cell);
698
+ if (value === void 0 || value === null) {
699
+ Obj3.change(this._sheet, (s) => {
700
+ delete s.cells[idx];
701
+ });
702
+ } else {
703
+ if (isFormula(value)) {
704
+ value = this._graph.mapFunctionBindingToId(mapFormulaRefsToIndices(this._sheet, value));
705
+ }
706
+ Obj3.change(this._sheet, (s) => {
707
+ s.cells[idx] = {
708
+ value
709
+ };
710
+ });
711
+ }
712
+ }
713
+ /**
714
+ * Sets values from a simple map.
715
+ */
716
+ setValues(values) {
717
+ Object.entries(values).forEach(([key, { value }]) => {
718
+ this.setValue(addressFromA1Notation(key), value);
719
+ });
720
+ }
721
+ /**
722
+ * Iterate range.
723
+ */
724
+ _iterRange(range, cb) {
725
+ const to = range.to ?? range.from;
726
+ const rowRange = [
727
+ Math.min(range.from.row, to.row),
728
+ Math.max(range.from.row, to.row)
729
+ ];
730
+ const columnRange = [
731
+ Math.min(range.from.col, to.col),
732
+ Math.max(range.from.col, to.col)
733
+ ];
734
+ const rows = [];
735
+ for (let row = rowRange[0]; row <= rowRange[1]; row++) {
736
+ const rowCells = [];
737
+ for (let column = columnRange[0]; column <= columnRange[1]; column++) {
738
+ const value = cb({
739
+ row,
740
+ col: column
741
+ });
742
+ if (value !== void 0) {
743
+ rowCells.push(value);
744
+ }
745
+ }
746
+ rows.push(rowCells);
747
+ }
748
+ return rows;
749
+ }
750
+ // TODO(burdon): Delete index.
751
+ _deleteIndices(indices, i, n) {
752
+ throw new Error("Not implemented");
753
+ }
754
+ // TODO(burdon): Move. Cannot use fractional without changing. Switch back to using unique IDs?
755
+ _moveIndices(indices, i, j, n) {
756
+ throw new Error("Not implemented");
757
+ }
758
+ /**
759
+ * Map from indices to A1 notation.
760
+ */
761
+ mapFormulaIndicesToRefs(formula) {
762
+ invariant(isFormula(formula), void 0, {
763
+ F: __dxlog_file,
764
+ L: 490,
765
+ S: this,
766
+ A: [
767
+ "isFormula(formula)",
768
+ ""
769
+ ]
770
+ });
771
+ return formula.replace(/([a-zA-Z0-9]+)@([a-zA-Z0-9]+)/g, (idx) => {
772
+ return addressToA1Notation(addressFromIndex(this._sheet, idx));
773
+ });
774
+ }
775
+ //
776
+ // Values
777
+ //
778
+ /**
779
+ * https://hyperformula.handsontable.com/guide/date-and-time-handling.html#example
780
+ * https://hyperformula.handsontable.com/api/interfaces/configparams.html#nulldate
781
+ * NOTE: TODAY() is number of FULL days since nullDate. It will typically be -1 days from NOW().
782
+ */
783
+ toLocalDate(num) {
784
+ const { year, month, day, hours, minutes, seconds } = this.toDateTime(num);
785
+ return new Date(year, month - 1, day, hours, minutes, seconds);
786
+ }
787
+ toDateTime(num) {
788
+ invariant(this._node, void 0, {
789
+ F: __dxlog_file,
790
+ L: 511,
791
+ S: this,
792
+ A: [
793
+ "this._node",
794
+ ""
795
+ ]
796
+ });
797
+ return this._node.graph.hf.numberToDateTime(num);
798
+ }
799
+ toDate(num) {
800
+ invariant(this._node, void 0, {
801
+ F: __dxlog_file,
802
+ L: 516,
803
+ S: this,
804
+ A: [
805
+ "this._node",
806
+ ""
807
+ ]
808
+ });
809
+ return this._node.graph.hf.numberToDate(num);
810
+ }
811
+ toTime(num) {
812
+ invariant(this._node, void 0, {
813
+ F: __dxlog_file,
814
+ L: 521,
815
+ S: this,
816
+ A: [
817
+ "this._node",
818
+ ""
819
+ ]
820
+ });
821
+ return this._node.graph.hf.numberToTime(num);
822
+ }
823
+ };
824
+
825
+ // src/model/useSheetModel.ts
826
+ import { useEffect as useEffect2, useState } from "react";
827
+ var useSheetModel = (graph, sheet, { readonly } = {}) => {
828
+ const [model, setModel] = useState();
829
+ useEffect2(() => {
830
+ if (!graph || !sheet) {
831
+ return;
832
+ }
833
+ let model2;
834
+ const t = setTimeout(async () => {
835
+ model2 = new SheetModel(graph, sheet, {
836
+ readonly
837
+ });
838
+ await model2.open();
839
+ setModel(model2);
840
+ });
841
+ return () => {
842
+ clearTimeout(t);
843
+ void model2?.close();
844
+ };
845
+ }, [
846
+ graph,
847
+ sheet,
848
+ readonly
849
+ ]);
850
+ return model;
851
+ };
852
+
853
+ // src/components/SheetContext/SheetContext.tsx
854
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/plugins/plugin-sheet/src/components/SheetContext/SheetContext.tsx";
855
+ var SheetContext = /* @__PURE__ */ createContext2(void 0);
856
+ var useSheetContext = () => {
857
+ const context = useContext2(SheetContext);
858
+ invariant2(context, void 0, {
859
+ F: __dxlog_file2,
860
+ L: 54,
861
+ S: void 0,
862
+ A: [
863
+ "context",
864
+ ""
865
+ ]
866
+ });
867
+ return context;
868
+ };
869
+ var SheetProviderImpl = ({ __gridScope, children, ignoreAttention, model, onInfo }) => {
870
+ const { id, editing, setEditing } = useGridContext("SheetProvider", __gridScope);
871
+ const [cursor, setCursorInternal] = useState2();
872
+ const [range, setRangeInternal] = useState2();
873
+ const [cursorFallbackRange, setCursorFallbackRange] = useState2();
874
+ const [activeRefs, setActiveRefs] = useState2("");
875
+ const setCursor = useCallback3((nextCursor) => {
876
+ setCursorInternal(nextCursor);
877
+ setCursorFallbackRange(range?.to ? range : nextCursor ? {
878
+ from: nextCursor,
879
+ to: nextCursor
880
+ } : void 0);
881
+ }, [
882
+ range
883
+ ]);
884
+ const setRange = useCallback3((nextRange) => {
885
+ setRangeInternal(nextRange);
886
+ setCursorFallbackRange(nextRange?.to ? nextRange : cursor ? {
887
+ from: cursor,
888
+ to: cursor
889
+ } : void 0);
890
+ }, [
891
+ cursor
892
+ ]);
893
+ return /* @__PURE__ */ React3.createElement(SheetContext.Provider, {
894
+ value: {
895
+ id,
896
+ model,
897
+ editing,
898
+ setEditing,
899
+ cursor,
900
+ setCursor,
901
+ range,
902
+ setRange,
903
+ cursorFallbackRange,
904
+ activeRefs,
905
+ setActiveRefs,
906
+ // TODO(burdon): Change to event.
907
+ onInfo,
908
+ ignoreAttention
909
+ }
910
+ }, children);
911
+ };
912
+ var SheetProvider = ({ children, graph, sheet, readonly, ignoreAttention, onInfo }) => {
913
+ const model = useSheetModel(graph, sheet, {
914
+ readonly
915
+ });
916
+ return !model ? null : /* @__PURE__ */ React3.createElement(Grid.Root, {
917
+ id: Obj4.getDXN(sheet).toString()
918
+ }, /* @__PURE__ */ React3.createElement(SheetProviderImpl, {
919
+ model,
920
+ onInfo,
921
+ ignoreAttention
922
+ }, children));
923
+ };
924
+
925
+ // src/components/GridSheet/util.ts
926
+ import { useEffect as useEffect3, useState as useState3 } from "react";
927
+ import { inRange as inRange2 } from "@dxos/compute";
928
+ import { createDocAccessor } from "@dxos/echo-db";
929
+ import { cellClassesForFieldType, parseValue } from "@dxos/react-ui-form";
930
+ import { colToA1Notation, commentedClassName, rowToA1Notation } from "@dxos/react-ui-grid";
931
+ import { mx } from "@dxos/ui-theme";
932
+ var createDxGridColumns = (model) => {
933
+ return model.sheet.columns.reduce((acc, columnId, numericIndex) => {
934
+ if (model.sheet.columnMeta[columnId] && model.sheet.columnMeta[columnId].size) {
935
+ acc.grid[numericIndex] = {
936
+ size: model.sheet.columnMeta[columnId].size,
937
+ resizeable: true
938
+ };
939
+ }
940
+ return acc;
941
+ }, {
942
+ grid: {}
943
+ });
944
+ };
945
+ var createDxGridRows = (model) => {
946
+ return model.sheet.rows.reduce((acc, rowId, numericIndex) => {
947
+ if (model.sheet.rowMeta[rowId] && model.sheet.rowMeta[rowId].size) {
948
+ acc.grid[numericIndex] = {
949
+ size: model.sheet.rowMeta[rowId].size,
950
+ resizeable: true
951
+ };
952
+ }
953
+ return acc;
954
+ }, {
955
+ grid: {}
956
+ });
957
+ };
958
+ var projectCellProps = (model, col, row) => {
959
+ const address = {
960
+ col,
961
+ row
962
+ };
963
+ const rawValue = model.getValue(address);
964
+ const ranges = model.sheet.ranges?.filter(({ range }) => inRange2(rangeFromIndex(model.sheet, range), address));
965
+ const threadRefs = void 0;
966
+ const description = model.getValueDescription(address);
967
+ const type = description?.type;
968
+ const format = description?.format;
969
+ const classNames = ranges?.map(cellClassNameForRange).reverse();
970
+ return {
971
+ value: parseValue({
972
+ type,
973
+ format,
974
+ value: rawValue
975
+ }),
976
+ className: mx(cellClassesForFieldType({
977
+ type,
978
+ format
979
+ }), threadRefs && commentedClassName, classNames),
980
+ dataRefs: threadRefs
981
+ };
982
+ };
983
+ var gridCellGetter = (model) => {
984
+ const cachedGridCells = {};
985
+ return (nextBounds) => {
986
+ [
987
+ ...Array(nextBounds.end.col - nextBounds.start.col)
988
+ ].forEach((_, c0) => {
989
+ return [
990
+ ...Array(nextBounds.end.row - nextBounds.start.row)
991
+ ].forEach((_2, r0) => {
992
+ const col = nextBounds.start.col + c0;
993
+ const row = nextBounds.start.row + r0;
994
+ cachedGridCells[`${col},${row}`] = projectCellProps(model, col, row);
995
+ });
996
+ });
997
+ return cachedGridCells;
998
+ };
999
+ };
1000
+ var rowLabelCell = (row) => ({
1001
+ value: rowToA1Notation(row),
1002
+ className: "!bg-toolbarSurface text-subdued text-end pie-1",
1003
+ resizeHandle: "row"
1004
+ });
1005
+ var colLabelCell = (col) => ({
1006
+ value: colToA1Notation(col),
1007
+ className: "!bg-toolbarSurface text-subdued",
1008
+ resizeHandle: "col"
1009
+ });
1010
+ var cellGetter = (model) => {
1011
+ const getGridCells = gridCellGetter(model);
1012
+ return (nextBounds, plane) => {
1013
+ switch (plane) {
1014
+ case "grid":
1015
+ return getGridCells(nextBounds);
1016
+ case "fixedStartStart": {
1017
+ return {
1018
+ "0,0": {
1019
+ className: "!bg-toolbarSurface"
1020
+ }
1021
+ };
1022
+ }
1023
+ case "frozenColsStart":
1024
+ return [
1025
+ ...Array(nextBounds.end.row - nextBounds.start.row)
1026
+ ].reduce((acc, _, r0) => {
1027
+ const r = nextBounds.start.row + r0;
1028
+ acc[`0,${r}`] = rowLabelCell(r);
1029
+ return acc;
1030
+ }, {});
1031
+ case "frozenRowsStart":
1032
+ return [
1033
+ ...Array(nextBounds.end.col - nextBounds.start.col)
1034
+ ].reduce((acc, _, c0) => {
1035
+ const c = nextBounds.start.col + c0;
1036
+ acc[`${c},0`] = colLabelCell(c);
1037
+ return acc;
1038
+ }, {});
1039
+ default:
1040
+ return {};
1041
+ }
1042
+ };
1043
+ };
1044
+ var useSheetModelDxGridProps = (dxGrid, model) => {
1045
+ const [columns, setColumns] = useState3(createDxGridColumns(model));
1046
+ const [rows, setRows] = useState3(createDxGridRows(model));
1047
+ useEffect3(() => {
1048
+ const cellsAccessor = createDocAccessor(model.sheet, [
1049
+ "cells"
1050
+ ]);
1051
+ if (dxGrid) {
1052
+ dxGrid.getCells = cellGetter(model);
1053
+ }
1054
+ const handleCellsUpdate = () => {
1055
+ dxGrid?.requestUpdate("initialCells");
1056
+ };
1057
+ cellsAccessor.handle.addListener("change", handleCellsUpdate);
1058
+ const unsubscribe = model.graph.update.on(handleCellsUpdate);
1059
+ return () => {
1060
+ cellsAccessor.handle.removeListener("change", handleCellsUpdate);
1061
+ unsubscribe();
1062
+ };
1063
+ }, [
1064
+ model,
1065
+ dxGrid
1066
+ ]);
1067
+ useEffect3(() => {
1068
+ const columnMetaAccessor = createDocAccessor(model.sheet, [
1069
+ "columnMeta"
1070
+ ]);
1071
+ const rowMetaAccessor = createDocAccessor(model.sheet, [
1072
+ "rowMeta"
1073
+ ]);
1074
+ const handleColumnMetaUpdate = () => {
1075
+ setColumns(createDxGridColumns(model));
1076
+ };
1077
+ const handleRowMetaUpdate = () => {
1078
+ setRows(createDxGridRows(model));
1079
+ };
1080
+ columnMetaAccessor.handle.addListener("change", handleColumnMetaUpdate);
1081
+ rowMetaAccessor.handle.addListener("change", handleRowMetaUpdate);
1082
+ return () => {
1083
+ columnMetaAccessor.handle.removeListener("change", handleColumnMetaUpdate);
1084
+ rowMetaAccessor.handle.removeListener("change", handleRowMetaUpdate);
1085
+ };
1086
+ }, [
1087
+ model,
1088
+ dxGrid
1089
+ ]);
1090
+ return {
1091
+ columns,
1092
+ rows
1093
+ };
1094
+ };
1095
+
1096
+ // src/components/GridSheet/GridSheet.tsx
1097
+ var inertPosition = {
1098
+ plane: "grid",
1099
+ col: 0,
1100
+ row: 0
1101
+ };
1102
+ var initialCells = {
1103
+ grid: {},
1104
+ frozenColsStart: [
1105
+ ...Array(64)
1106
+ ].reduce((acc, _, i) => {
1107
+ acc[`0,${i}`] = rowLabelCell(i);
1108
+ return acc;
1109
+ }, {}),
1110
+ frozenRowsStart: [
1111
+ ...Array(12)
1112
+ ].reduce((acc, _, i) => {
1113
+ acc[`${i},0`] = colLabelCell(i);
1114
+ return acc;
1115
+ }, {})
1116
+ };
1117
+ var frozen = {
1118
+ frozenColsStart: 1,
1119
+ frozenRowsStart: 1
1120
+ };
1121
+ var sheetColDefault = {
1122
+ frozenColsStart: {
1123
+ size: 48,
1124
+ readonly: true,
1125
+ focusUnfurl: false
1126
+ },
1127
+ grid: {
1128
+ size: defaultColSize,
1129
+ resizeable: true
1130
+ }
1131
+ };
1132
+ var sheetRowDefault = {
1133
+ frozenRowsStart: {
1134
+ size: defaultRowSize,
1135
+ readonly: true,
1136
+ focusUnfurl: false
1137
+ },
1138
+ grid: {
1139
+ size: defaultRowSize,
1140
+ resizeable: true
1141
+ }
1142
+ };
1143
+ var GridSheet = () => {
1144
+ const { t } = useTranslation2(meta.id);
1145
+ const { id, model, editing, setCursor, setRange, cursor, cursorFallbackRange, activeRefs, ignoreAttention } = useSheetContext();
1146
+ const [dxGrid, setDxGrid] = useState4(null);
1147
+ const [extraplanarFocus, setExtraplanarFocus] = useState4(null);
1148
+ const { invokePromise } = useOperationInvoker2();
1149
+ const rangeController = useRef(null);
1150
+ const { hasAttention } = useAttention(id);
1151
+ const handleFocus = useCallback4((event) => {
1152
+ if (!editing) {
1153
+ const cell = closestCell(event.target);
1154
+ if (cell) {
1155
+ if (cell.plane === "grid") {
1156
+ setCursor({
1157
+ col: cell.col,
1158
+ row: cell.row
1159
+ });
1160
+ setExtraplanarFocus(null);
1161
+ } else {
1162
+ setExtraplanarFocus(cell);
1163
+ }
1164
+ } else {
1165
+ setExtraplanarFocus(null);
1166
+ }
1167
+ }
1168
+ }, [
1169
+ editing
1170
+ ]);
1171
+ const handleClose = useCallback4((_value, event) => {
1172
+ if (event) {
1173
+ const { key, shift } = event;
1174
+ const axis = [
1175
+ "Enter",
1176
+ "ArrowUp",
1177
+ "ArrowDown"
1178
+ ].includes(key) ? "row" : [
1179
+ "Tab",
1180
+ "ArrowLeft",
1181
+ "ArrowRight"
1182
+ ].includes(key) ? "col" : void 0;
1183
+ const delta = key.startsWith("Arrow") ? [
1184
+ "ArrowUp",
1185
+ "ArrowLeft"
1186
+ ].includes(key) ? -1 : 1 : shift ? -1 : 1;
1187
+ dxGrid?.refocus(axis, delta);
1188
+ }
1189
+ }, [
1190
+ model,
1191
+ editing,
1192
+ dxGrid
1193
+ ]);
1194
+ const handleBlur = useCallback4((value) => {
1195
+ if (value !== void 0) {
1196
+ model.setValue(parseCellIndex(editing.index), value);
1197
+ }
1198
+ }, [
1199
+ model,
1200
+ editing
1201
+ ]);
1202
+ const handleAxisResize = useCallback4(({ axis, size, index: numericIndex }) => {
1203
+ if (axis === "row") {
1204
+ const rowId = model.sheet.rows[parseInt(numericIndex)];
1205
+ model.sheet.rowMeta[rowId] ??= {};
1206
+ model.sheet.rowMeta[rowId].size = size;
1207
+ } else {
1208
+ const columnId = model.sheet.columns[parseInt(numericIndex)];
1209
+ model.sheet.columnMeta[columnId] ??= {};
1210
+ model.sheet.columnMeta[columnId].size = size;
1211
+ }
1212
+ }, [
1213
+ model
1214
+ ]);
1215
+ const handleSelect = useCallback4(({ minCol, maxCol, minRow, maxRow }) => {
1216
+ const range = {
1217
+ from: {
1218
+ col: minCol,
1219
+ row: minRow
1220
+ }
1221
+ };
1222
+ if (minCol !== maxCol || minRow !== maxRow) {
1223
+ range.to = {
1224
+ col: maxCol,
1225
+ row: maxRow
1226
+ };
1227
+ }
1228
+ if (editing) {
1229
+ rangeController.current?.setRange(rangeToA1Notation2(range));
1230
+ } else {
1231
+ setRange(range.to ? range : void 0);
1232
+ }
1233
+ }, [
1234
+ editing
1235
+ ]);
1236
+ const handleWheel = useCallback4((event) => {
1237
+ if (!ignoreAttention && !hasAttention) {
1238
+ event.stopPropagation();
1239
+ }
1240
+ }, [
1241
+ hasAttention,
1242
+ ignoreAttention
1243
+ ]);
1244
+ const selectEntireAxis = useCallback4((pos) => {
1245
+ switch (pos.plane) {
1246
+ case "frozenRowsStart":
1247
+ return dxGrid?.setSelection({
1248
+ start: {
1249
+ col: pos.col,
1250
+ row: 0,
1251
+ plane: "grid"
1252
+ },
1253
+ end: {
1254
+ col: pos.col,
1255
+ row: model.sheet.rows.length - 1,
1256
+ plane: "grid"
1257
+ }
1258
+ });
1259
+ case "frozenColsStart":
1260
+ return dxGrid?.setSelection({
1261
+ start: {
1262
+ row: pos.row,
1263
+ col: 0,
1264
+ plane: "grid"
1265
+ },
1266
+ end: {
1267
+ row: pos.row,
1268
+ col: model.sheet.columns.length - 1,
1269
+ plane: "grid"
1270
+ }
1271
+ });
1272
+ }
1273
+ }, [
1274
+ dxGrid,
1275
+ model.sheet
1276
+ ]);
1277
+ const handleClick = useCallback4((event) => {
1278
+ const cell = closestCell(event.target);
1279
+ if (cell) {
1280
+ selectEntireAxis(cell);
1281
+ }
1282
+ }, [
1283
+ selectEntireAxis
1284
+ ]);
1285
+ const handleKeyDown = useCallback4((event) => {
1286
+ switch (event.key) {
1287
+ case "Backspace":
1288
+ case "Delete":
1289
+ event.preventDefault();
1290
+ return cursorFallbackRange && model.clear(cursorFallbackRange);
1291
+ case "Enter":
1292
+ case "Space":
1293
+ if (dxGrid && extraplanarFocus) {
1294
+ switch (extraplanarFocus.plane) {
1295
+ case "frozenRowsStart":
1296
+ case "frozenColsStart":
1297
+ event.preventDefault();
1298
+ return selectEntireAxis(extraplanarFocus);
1299
+ }
1300
+ }
1301
+ }
1302
+ if (event.metaKey || event.ctrlKey) {
1303
+ switch (event.key) {
1304
+ case "x":
1305
+ case "X":
1306
+ event.preventDefault();
1307
+ return cursorFallbackRange && model.cut(cursorFallbackRange);
1308
+ case "c":
1309
+ case "C":
1310
+ event.preventDefault();
1311
+ return cursorFallbackRange && model.copy(cursorFallbackRange);
1312
+ case "v":
1313
+ case "V":
1314
+ event.preventDefault();
1315
+ return cursor && model.paste(cursor);
1316
+ case "z":
1317
+ event.preventDefault();
1318
+ return event.shiftKey ? model.redo() : model.undo();
1319
+ case "Z":
1320
+ case "y":
1321
+ event.preventDefault();
1322
+ return model.redo();
1323
+ }
1324
+ }
1325
+ }, [
1326
+ cursorFallbackRange,
1327
+ model,
1328
+ cursor,
1329
+ extraplanarFocus,
1330
+ selectEntireAxis
1331
+ ]);
1332
+ const contextMenuAnchorRef = useRef(null);
1333
+ const [contextMenuOpen, setContextMenuOpen] = useState4(null);
1334
+ const contextMenuAxis = contextMenuOpen?.plane.startsWith("frozenRows") ? "col" : "row";
1335
+ const handleContextMenu = useCallback4((event) => {
1336
+ const cell = closestCell(event.target);
1337
+ if (cell && cell.plane.startsWith("frozen")) {
1338
+ event.preventDefault();
1339
+ contextMenuAnchorRef.current = event.target;
1340
+ setContextMenuOpen(cell);
1341
+ }
1342
+ }, []);
1343
+ const handleAxisMenuAction = useCallback4((operation) => {
1344
+ switch (operation) {
1345
+ case "insert-before":
1346
+ case "insert-after":
1347
+ return invokePromise(SheetOperation.InsertAxis, {
1348
+ model,
1349
+ axis: contextMenuAxis,
1350
+ index: contextMenuOpen[contextMenuAxis] + (operation === "insert-before" ? 0 : 1)
1351
+ });
1352
+ case "drop":
1353
+ return invokePromise(SheetOperation.DropAxis, {
1354
+ model,
1355
+ axis: contextMenuAxis,
1356
+ axisIndex: model.sheet[contextMenuAxis === "row" ? "rows" : "columns"][contextMenuOpen[contextMenuAxis]]
1357
+ });
1358
+ }
1359
+ }, [
1360
+ contextMenuAxis,
1361
+ contextMenuOpen,
1362
+ model,
1363
+ invokePromise
1364
+ ]);
1365
+ const { columns, rows } = useSheetModelDxGridProps(dxGrid, model);
1366
+ const extensions = useMemo2(() => [
1367
+ editorKeys({
1368
+ onClose: handleClose,
1369
+ ...editing?.initialContent && {
1370
+ onNav: handleClose
1371
+ }
1372
+ }),
1373
+ sheetExtension({
1374
+ functions: model.graph.getFunctions()
1375
+ }),
1376
+ rangeExtension({
1377
+ onInit: (fn) => rangeController.current = fn,
1378
+ onStateChange: (state) => {
1379
+ if (dxGrid) {
1380
+ dxGrid.mode = typeof state.activeRange === "undefined" ? "edit" : "edit-select";
1381
+ }
1382
+ }
1383
+ })
1384
+ ], [
1385
+ model,
1386
+ handleClose,
1387
+ editing
1388
+ ]);
1389
+ const getCellContent = useCallback4((index) => {
1390
+ return model.getCellText(parseCellIndex(index));
1391
+ }, [
1392
+ model
1393
+ ]);
1394
+ useUpdateFocusedCellOnThreadSelection(dxGrid);
1395
+ useSelectThreadOnCellFocus();
1396
+ return (
1397
+ // TODO(thure): Why are Table’s and Sheet’s editor boxes off by 1px?
1398
+ /* @__PURE__ */ React4.createElement("div", {
1399
+ role: "none",
1400
+ className: "relative min-bs-0 [&_.cm-editor]:!border-lb [&_.cm-editor]:!border-transparent"
1401
+ }, /* @__PURE__ */ React4.createElement(GridCellEditor, {
1402
+ getCellContent,
1403
+ extensions,
1404
+ onBlur: handleBlur
1405
+ }), /* @__PURE__ */ React4.createElement(Grid2.Content, {
1406
+ initialCells,
1407
+ limitColumns: DEFAULT_COLS,
1408
+ limitRows: DEFAULT_ROWS,
1409
+ columns,
1410
+ rows,
1411
+ // TODO(burdon): `col` vs. `column`?
1412
+ columnDefault: sheetColDefault,
1413
+ rowDefault: sheetRowDefault,
1414
+ frozen,
1415
+ onAxisResize: handleAxisResize,
1416
+ onSelect: handleSelect,
1417
+ onFocus: handleFocus,
1418
+ onWheelCapture: handleWheel,
1419
+ onKeyDown: handleKeyDown,
1420
+ onContextMenu: handleContextMenu,
1421
+ onClick: handleClick,
1422
+ overscroll: "trap",
1423
+ className: "[--dx-grid-base:var(--baseSurface)] [&_.dx-grid]:absolute [&_.dx-grid]:inset-0",
1424
+ activeRefs,
1425
+ ref: setDxGrid
1426
+ }), /* @__PURE__ */ React4.createElement(DropdownMenu.Root, {
1427
+ modal: false,
1428
+ open: !!contextMenuOpen,
1429
+ onOpenChange: (nextOpen) => setContextMenuOpen(nextOpen ? inertPosition : null)
1430
+ }, /* @__PURE__ */ React4.createElement(DropdownMenu.VirtualTrigger, {
1431
+ virtualRef: contextMenuAnchorRef
1432
+ }), /* @__PURE__ */ React4.createElement(DropdownMenu.Content, {
1433
+ side: contextMenuAxis === "col" ? "bottom" : "right",
1434
+ sideOffset: 4,
1435
+ collisionPadding: 8
1436
+ }, /* @__PURE__ */ React4.createElement(DropdownMenu.Viewport, null, /* @__PURE__ */ React4.createElement(DropdownMenu.Item, {
1437
+ onClick: () => handleAxisMenuAction("insert-before"),
1438
+ "data-testid": `grid.${contextMenuAxis}.insert-before`
1439
+ }, /* @__PURE__ */ React4.createElement(Icon, {
1440
+ size: 5,
1441
+ icon: contextMenuAxis === "col" ? "ph--columns-plus-left--regular" : "ph--rows-plus-top--regular"
1442
+ }), /* @__PURE__ */ React4.createElement("span", null, t(`add ${contextMenuAxis} before label`))), /* @__PURE__ */ React4.createElement(DropdownMenu.Item, {
1443
+ onClick: () => handleAxisMenuAction("insert-after"),
1444
+ "data-testid": `grid.${contextMenuAxis}.insert-after`
1445
+ }, /* @__PURE__ */ React4.createElement(Icon, {
1446
+ size: 5,
1447
+ icon: contextMenuAxis === "col" ? "ph--columns-plus-right--regular" : "ph--rows-plus-bottom--regular"
1448
+ }), /* @__PURE__ */ React4.createElement("span", null, t(`add ${contextMenuAxis} after label`))), /* @__PURE__ */ React4.createElement(DropdownMenu.Item, {
1449
+ onClick: () => handleAxisMenuAction("drop"),
1450
+ "data-testid": `grid.${contextMenuAxis}.drop`
1451
+ }, /* @__PURE__ */ React4.createElement(Icon, {
1452
+ size: 5,
1453
+ icon: "ph--backspace--regular"
1454
+ }), /* @__PURE__ */ React4.createElement("span", null, t(`delete ${contextMenuAxis} label`)))), /* @__PURE__ */ React4.createElement(DropdownMenu.Arrow, null))))
1455
+ );
1456
+ };
1457
+
1458
+ // src/components/index.ts
1459
+ var SheetContainer = lazy(() => import("./SheetContainer-ESCXPI7Y.mjs"));
1460
+
1461
+ export {
1462
+ ComputeGraphContextProvider,
1463
+ useComputeGraph,
1464
+ useSheetContext,
1465
+ SheetProvider,
1466
+ GridSheet,
1467
+ RangeList,
1468
+ SheetContainer
1469
+ };
1470
+ //# sourceMappingURL=chunk-W6N44ONZ.mjs.map