@dxos/plugin-sheet 0.6.11 → 0.6.12-main.15a606f

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 (260) hide show
  1. package/dist/lib/browser/SheetContainer-V4GCCZTX.mjs +261 -0
  2. package/dist/lib/browser/SheetContainer-V4GCCZTX.mjs.map +7 -0
  3. package/dist/lib/browser/{chunk-D5AGLXJP.mjs → chunk-6ZMQVB4Z.mjs} +359 -671
  4. package/dist/lib/browser/chunk-6ZMQVB4Z.mjs.map +7 -0
  5. package/dist/lib/browser/{chunk-JRL5LGCE.mjs → chunk-QILRZNE5.mjs} +2 -5
  6. package/dist/lib/browser/chunk-QILRZNE5.mjs.map +7 -0
  7. package/dist/lib/browser/{chunk-FUAGSXA4.mjs → chunk-T3NJFTD4.mjs} +8 -15
  8. package/dist/lib/browser/chunk-T3NJFTD4.mjs.map +7 -0
  9. package/dist/lib/browser/{SheetContainer-U4H5D34A.mjs → chunk-U2JHW3L6.mjs} +1020 -240
  10. package/dist/lib/browser/chunk-U2JHW3L6.mjs.map +7 -0
  11. package/dist/lib/browser/graph-T27BOBOV.mjs +21 -0
  12. package/dist/lib/browser/graph-T27BOBOV.mjs.map +7 -0
  13. package/dist/lib/browser/index.mjs +68 -56
  14. package/dist/lib/browser/index.mjs.map +3 -3
  15. package/dist/lib/browser/meta.json +1 -1
  16. package/dist/lib/browser/meta.mjs +1 -1
  17. package/dist/lib/browser/types.mjs +4 -6
  18. package/dist/lib/node/SheetContainer-3ZY7MPWJ.cjs +279 -0
  19. package/dist/lib/node/SheetContainer-3ZY7MPWJ.cjs.map +7 -0
  20. package/dist/lib/node/{chunk-BJ6ZD7MN.cjs → chunk-BNARJ5GM.cjs} +5 -18
  21. package/dist/lib/node/chunk-BNARJ5GM.cjs.map +7 -0
  22. package/dist/lib/node/{chunk-5KKJ4NPP.cjs → chunk-DD6FIXWC.cjs} +360 -667
  23. package/dist/lib/node/chunk-DD6FIXWC.cjs.map +7 -0
  24. package/dist/lib/node/{SheetContainer-AXQV3ZT5.cjs → chunk-OTTD7FBK.cjs} +1050 -279
  25. package/dist/lib/node/chunk-OTTD7FBK.cjs.map +7 -0
  26. package/dist/lib/node/{chunk-DSYKOI4E.cjs → chunk-Q3HBHPRL.cjs} +12 -20
  27. package/dist/lib/node/chunk-Q3HBHPRL.cjs.map +7 -0
  28. package/dist/lib/node/graph-SPKGX7W4.cjs +43 -0
  29. package/dist/lib/node/graph-SPKGX7W4.cjs.map +7 -0
  30. package/dist/lib/node/index.cjs +83 -64
  31. package/dist/lib/node/index.cjs.map +3 -3
  32. package/dist/lib/node/meta.cjs +3 -3
  33. package/dist/lib/node/meta.cjs.map +1 -1
  34. package/dist/lib/node/meta.json +1 -1
  35. package/dist/lib/node/types.cjs +10 -12
  36. package/dist/lib/node/types.cjs.map +2 -2
  37. package/dist/lib/node-esm/SheetContainer-PXSJX6XK.mjs +262 -0
  38. package/dist/lib/node-esm/SheetContainer-PXSJX6XK.mjs.map +7 -0
  39. package/dist/lib/node-esm/chunk-7HVSOTGA.mjs +2553 -0
  40. package/dist/lib/node-esm/chunk-7HVSOTGA.mjs.map +7 -0
  41. package/dist/lib/node-esm/chunk-BMNA27EX.mjs +76 -0
  42. package/dist/lib/node-esm/chunk-BMNA27EX.mjs.map +7 -0
  43. package/dist/lib/node-esm/chunk-D6KU5MI7.mjs +2925 -0
  44. package/dist/lib/node-esm/chunk-D6KU5MI7.mjs.map +7 -0
  45. package/dist/lib/node-esm/chunk-IU2L277A.mjs +17 -0
  46. package/dist/lib/node-esm/chunk-IU2L277A.mjs.map +7 -0
  47. package/dist/lib/node-esm/graph-U67IO4UC.mjs +22 -0
  48. package/dist/lib/node-esm/graph-U67IO4UC.mjs.map +7 -0
  49. package/dist/lib/node-esm/index.mjs +261 -0
  50. package/dist/lib/node-esm/index.mjs.map +7 -0
  51. package/dist/lib/node-esm/meta.json +1 -0
  52. package/dist/lib/node-esm/meta.mjs +10 -0
  53. package/dist/lib/node-esm/meta.mjs.map +7 -0
  54. package/dist/lib/node-esm/types.mjs +21 -0
  55. package/dist/lib/node-esm/types.mjs.map +7 -0
  56. package/dist/types/src/SheetPlugin.d.ts.map +1 -1
  57. package/dist/types/src/components/CellEditor/CellEditor.d.ts +23 -3
  58. package/dist/types/src/components/CellEditor/CellEditor.d.ts.map +1 -1
  59. package/dist/types/src/components/CellEditor/CellEditor.stories.d.ts +2 -2
  60. package/dist/types/src/components/CellEditor/CellEditor.stories.d.ts.map +1 -1
  61. package/dist/types/src/components/CellEditor/extension.d.ts +1 -1
  62. package/dist/types/src/components/CellEditor/extension.d.ts.map +1 -1
  63. package/dist/types/src/components/ComputeGraph/ComputeGraphContextProvider.d.ts +11 -0
  64. package/dist/types/src/components/ComputeGraph/ComputeGraphContextProvider.d.ts.map +1 -0
  65. package/dist/types/src/components/ComputeGraph/index.d.ts +1 -3
  66. package/dist/types/src/components/ComputeGraph/index.d.ts.map +1 -1
  67. package/dist/types/src/components/GridSheet/GridSheet.d.ts +10 -0
  68. package/dist/types/src/components/GridSheet/GridSheet.d.ts.map +1 -0
  69. package/dist/types/src/components/GridSheet/GridSheet.stories.d.ts +9 -0
  70. package/dist/types/src/components/GridSheet/GridSheet.stories.d.ts.map +1 -0
  71. package/dist/types/src/components/GridSheet/util.d.ts +6 -0
  72. package/dist/types/src/components/GridSheet/util.d.ts.map +1 -0
  73. package/dist/types/src/components/Sheet/Sheet.d.ts +1 -1
  74. package/dist/types/src/components/Sheet/Sheet.d.ts.map +1 -1
  75. package/dist/types/src/components/Sheet/Sheet.stories.d.ts +5 -6
  76. package/dist/types/src/components/Sheet/Sheet.stories.d.ts.map +1 -1
  77. package/dist/types/src/components/Sheet/decorations.d.ts +24 -0
  78. package/dist/types/src/components/Sheet/decorations.d.ts.map +1 -0
  79. package/dist/types/src/components/Sheet/grid.d.ts +2 -2
  80. package/dist/types/src/components/Sheet/grid.d.ts.map +1 -1
  81. package/dist/types/src/components/Sheet/nav.d.ts +3 -3
  82. package/dist/types/src/components/Sheet/nav.d.ts.map +1 -1
  83. package/dist/types/src/components/Sheet/sheet-context.d.ts +6 -5
  84. package/dist/types/src/components/Sheet/sheet-context.d.ts.map +1 -1
  85. package/dist/types/src/components/Sheet/threads.d.ts +2 -0
  86. package/dist/types/src/components/Sheet/threads.d.ts.map +1 -0
  87. package/dist/types/src/components/SheetContainer.d.ts +2 -3
  88. package/dist/types/src/components/SheetContainer.d.ts.map +1 -1
  89. package/dist/types/src/components/Toolbar/Toolbar.d.ts +19 -3
  90. package/dist/types/src/components/Toolbar/Toolbar.d.ts.map +1 -1
  91. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts +18 -13
  92. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts.map +1 -1
  93. package/dist/types/src/components/index.d.ts +2 -2
  94. package/dist/types/src/components/index.d.ts.map +1 -1
  95. package/dist/types/src/defs/index.d.ts +3 -0
  96. package/dist/types/src/defs/index.d.ts.map +1 -0
  97. package/dist/types/src/{model → defs}/types.d.ts +8 -3
  98. package/dist/types/src/defs/types.d.ts.map +1 -0
  99. package/dist/types/src/defs/types.test.d.ts.map +1 -0
  100. package/dist/types/src/defs/util.d.ts +43 -0
  101. package/dist/types/src/defs/util.d.ts.map +1 -0
  102. package/dist/types/src/extensions/compute.d.ts +5 -0
  103. package/dist/types/src/extensions/compute.d.ts.map +1 -0
  104. package/dist/types/src/extensions/compute.stories.d.ts +26 -0
  105. package/dist/types/src/extensions/compute.stories.d.ts.map +1 -0
  106. package/dist/types/src/extensions/index.d.ts +2 -0
  107. package/dist/types/src/extensions/index.d.ts.map +1 -0
  108. package/dist/types/src/{components/ComputeGraph → graph}/async-function.d.ts +1 -1
  109. package/dist/types/src/graph/async-function.d.ts.map +1 -0
  110. package/dist/types/src/graph/compute-graph.browser.test.d.ts +2 -0
  111. package/dist/types/src/graph/compute-graph.browser.test.d.ts.map +1 -0
  112. package/dist/types/src/graph/compute-graph.d.ts +81 -0
  113. package/dist/types/src/graph/compute-graph.d.ts.map +1 -0
  114. package/dist/types/src/graph/compute-graph.stories.d.ts +10 -0
  115. package/dist/types/src/graph/compute-graph.stories.d.ts.map +1 -0
  116. package/dist/types/src/graph/compute-node.d.ts +19 -0
  117. package/dist/types/src/graph/compute-node.d.ts.map +1 -0
  118. package/dist/types/src/{components/ComputeGraph/custom.d.ts → graph/custom-function.d.ts} +1 -1
  119. package/dist/types/src/graph/custom-function.d.ts.map +1 -0
  120. package/dist/types/src/graph/edge-function.d.ts.map +1 -0
  121. package/dist/types/src/{model/functions.d.ts → graph/function-defs.d.ts} +1 -1
  122. package/dist/types/src/graph/function-defs.d.ts.map +1 -0
  123. package/dist/types/src/graph/hyperformula.test.d.ts +2 -0
  124. package/dist/types/src/graph/hyperformula.test.d.ts.map +1 -0
  125. package/dist/types/src/graph/index.d.ts +4 -0
  126. package/dist/types/src/graph/index.d.ts.map +1 -0
  127. package/dist/types/src/graph/util.d.ts +2 -0
  128. package/dist/types/src/graph/util.d.ts.map +1 -0
  129. package/dist/types/src/hooks/hooks.stories.d.ts +11 -0
  130. package/dist/types/src/hooks/hooks.stories.d.ts.map +1 -0
  131. package/dist/types/src/hooks/index.d.ts +4 -0
  132. package/dist/types/src/hooks/index.d.ts.map +1 -0
  133. package/dist/types/src/hooks/useComputeGraph.d.ts +7 -0
  134. package/dist/types/src/hooks/useComputeGraph.d.ts.map +1 -0
  135. package/dist/types/src/hooks/useFormattingModel.d.ts +3 -0
  136. package/dist/types/src/hooks/useFormattingModel.d.ts.map +1 -0
  137. package/dist/types/src/hooks/useSheetModel.d.ts +8 -0
  138. package/dist/types/src/hooks/useSheetModel.d.ts.map +1 -0
  139. package/dist/types/src/meta.d.ts +1 -4
  140. package/dist/types/src/meta.d.ts.map +1 -1
  141. package/dist/types/src/model/formatting-model.d.ts +16 -0
  142. package/dist/types/src/model/formatting-model.d.ts.map +1 -0
  143. package/dist/types/src/model/index.d.ts +2 -3
  144. package/dist/types/src/model/index.d.ts.map +1 -1
  145. package/dist/types/src/model/{model.d.ts → sheet-model.d.ts} +9 -64
  146. package/dist/types/src/model/sheet-model.d.ts.map +1 -0
  147. package/dist/types/src/sanity.test.d.ts +2 -0
  148. package/dist/types/src/sanity.test.d.ts.map +1 -0
  149. package/dist/types/src/testing/index.d.ts +2 -0
  150. package/dist/types/src/testing/index.d.ts.map +1 -0
  151. package/dist/types/src/testing/testing.d.ts +9 -0
  152. package/dist/types/src/testing/testing.d.ts.map +1 -0
  153. package/dist/types/src/translations.d.ts +17 -12
  154. package/dist/types/src/translations.d.ts.map +1 -1
  155. package/dist/types/src/types.d.ts +83 -3
  156. package/dist/types/src/types.d.ts.map +1 -1
  157. package/dist/vendor/hyperformula.mjs +37145 -0
  158. package/package.json +48 -41
  159. package/src/SheetPlugin.tsx +43 -70
  160. package/src/components/CellEditor/CellEditor.stories.tsx +4 -3
  161. package/src/components/CellEditor/CellEditor.tsx +59 -9
  162. package/src/components/CellEditor/extension.test.ts +4 -5
  163. package/src/components/CellEditor/extension.ts +1 -3
  164. package/src/components/ComputeGraph/ComputeGraphContextProvider.tsx +20 -0
  165. package/src/components/ComputeGraph/index.ts +1 -3
  166. package/src/components/GridSheet/GridSheet.stories.tsx +35 -0
  167. package/src/components/GridSheet/GridSheet.tsx +153 -0
  168. package/src/components/GridSheet/util.ts +89 -0
  169. package/src/components/Sheet/Sheet.stories.tsx +45 -82
  170. package/src/components/Sheet/Sheet.tsx +57 -18
  171. package/src/components/Sheet/decorations.ts +62 -0
  172. package/src/components/Sheet/grid.ts +3 -3
  173. package/src/components/Sheet/nav.ts +19 -19
  174. package/src/components/Sheet/sheet-context.tsx +16 -78
  175. package/src/components/Sheet/threads.tsx +205 -0
  176. package/src/components/SheetContainer.tsx +73 -19
  177. package/src/components/Toolbar/Toolbar.tsx +53 -12
  178. package/src/components/index.ts +1 -0
  179. package/src/defs/index.ts +6 -0
  180. package/src/{model → defs}/types.test.ts +8 -9
  181. package/src/{model → defs}/types.ts +23 -14
  182. package/src/defs/util.ts +135 -0
  183. package/src/extensions/compute.stories.tsx +151 -0
  184. package/src/extensions/compute.ts +98 -0
  185. package/src/extensions/index.ts +5 -0
  186. package/src/{components/ComputeGraph → graph}/async-function.ts +3 -1
  187. package/src/graph/compute-graph.browser.test.ts +104 -0
  188. package/src/graph/compute-graph.stories.tsx +92 -0
  189. package/src/graph/compute-graph.ts +290 -0
  190. package/src/graph/compute-node.ts +51 -0
  191. package/src/{components/ComputeGraph/custom.ts → graph/custom-function.ts} +2 -6
  192. package/src/{components/ComputeGraph → graph}/edge-function.ts +2 -1
  193. package/src/graph/hyperformula.test.ts +15 -0
  194. package/src/graph/index.ts +7 -0
  195. package/src/graph/util.ts +8 -0
  196. package/src/hooks/hooks.stories.tsx +50 -0
  197. package/src/hooks/index.ts +7 -0
  198. package/src/hooks/useComputeGraph.ts +20 -0
  199. package/src/hooks/useFormattingModel.ts +11 -0
  200. package/src/hooks/useSheetModel.ts +43 -0
  201. package/src/meta.tsx +1 -5
  202. package/src/{components/Sheet/formatting.ts → model/formatting-model.ts} +20 -13
  203. package/src/model/index.ts +2 -3
  204. package/src/model/sheet-model.ts +399 -0
  205. package/src/sanity.test.ts +40 -0
  206. package/src/testing/index.ts +5 -0
  207. package/src/testing/testing.tsx +66 -0
  208. package/src/translations.ts +6 -1
  209. package/src/types.ts +30 -5
  210. package/dist/lib/browser/SheetContainer-U4H5D34A.mjs.map +0 -7
  211. package/dist/lib/browser/chunk-APHOLYUB.mjs +0 -175
  212. package/dist/lib/browser/chunk-APHOLYUB.mjs.map +0 -7
  213. package/dist/lib/browser/chunk-D5AGLXJP.mjs.map +0 -7
  214. package/dist/lib/browser/chunk-FUAGSXA4.mjs.map +0 -7
  215. package/dist/lib/browser/chunk-JRL5LGCE.mjs.map +0 -7
  216. package/dist/lib/browser/chunk-NU4PBN33.mjs +0 -8
  217. package/dist/lib/browser/chunk-NU4PBN33.mjs.map +0 -7
  218. package/dist/lib/browser/testing.mjs +0 -92
  219. package/dist/lib/browser/testing.mjs.map +0 -7
  220. package/dist/lib/node/SheetContainer-AXQV3ZT5.cjs.map +0 -7
  221. package/dist/lib/node/chunk-5KKJ4NPP.cjs.map +0 -7
  222. package/dist/lib/node/chunk-BJ6ZD7MN.cjs.map +0 -7
  223. package/dist/lib/node/chunk-CN3RPESU.cjs +0 -202
  224. package/dist/lib/node/chunk-CN3RPESU.cjs.map +0 -7
  225. package/dist/lib/node/chunk-DSYKOI4E.cjs.map +0 -7
  226. package/dist/lib/node/chunk-PYXHNAAK.cjs +0 -40
  227. package/dist/lib/node/chunk-PYXHNAAK.cjs.map +0 -7
  228. package/dist/lib/node/testing.cjs +0 -111
  229. package/dist/lib/node/testing.cjs.map +0 -7
  230. package/dist/types/src/components/ComputeGraph/async-function.d.ts.map +0 -1
  231. package/dist/types/src/components/ComputeGraph/custom.d.ts.map +0 -1
  232. package/dist/types/src/components/ComputeGraph/edge-function.d.ts.map +0 -1
  233. package/dist/types/src/components/ComputeGraph/graph-context.d.ts +0 -12
  234. package/dist/types/src/components/ComputeGraph/graph-context.d.ts.map +0 -1
  235. package/dist/types/src/components/ComputeGraph/graph.browser.test.d.ts +0 -2
  236. package/dist/types/src/components/ComputeGraph/graph.browser.test.d.ts.map +0 -1
  237. package/dist/types/src/components/ComputeGraph/graph.d.ts +0 -26
  238. package/dist/types/src/components/ComputeGraph/graph.d.ts.map +0 -1
  239. package/dist/types/src/components/Sheet/formatting.d.ts +0 -14
  240. package/dist/types/src/components/Sheet/formatting.d.ts.map +0 -1
  241. package/dist/types/src/model/functions.d.ts.map +0 -1
  242. package/dist/types/src/model/model.browser.test.d.ts +0 -2
  243. package/dist/types/src/model/model.browser.test.d.ts.map +0 -1
  244. package/dist/types/src/model/model.d.ts.map +0 -1
  245. package/dist/types/src/model/types.d.ts.map +0 -1
  246. package/dist/types/src/model/types.test.d.ts.map +0 -1
  247. package/dist/types/src/model/util.d.ts +0 -15
  248. package/dist/types/src/model/util.d.ts.map +0 -1
  249. package/dist/types/src/testing.d.ts +0 -9
  250. package/dist/types/src/testing.d.ts.map +0 -1
  251. package/src/components/ComputeGraph/graph-context.tsx +0 -50
  252. package/src/components/ComputeGraph/graph.browser.test.ts +0 -50
  253. package/src/components/ComputeGraph/graph.ts +0 -62
  254. package/src/model/model.browser.test.ts +0 -100
  255. package/src/model/model.ts +0 -550
  256. package/src/model/util.ts +0 -36
  257. package/src/testing.ts +0 -50
  258. /package/dist/types/src/{model → defs}/types.test.d.ts +0 -0
  259. /package/dist/types/src/{components/ComputeGraph → graph}/edge-function.d.ts +0 -0
  260. /package/src/{model/functions.ts → graph/function-defs.ts} +0 -0
@@ -0,0 +1,2553 @@
1
+ import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
+ import {
3
+ SheetType,
4
+ ValueTypeEnum
5
+ } from "./chunk-BMNA27EX.mjs";
6
+ import {
7
+ SHEET_PLUGIN
8
+ } from "./chunk-IU2L277A.mjs";
9
+ import {
10
+ createSheetName
11
+ } from "./chunk-D6KU5MI7.mjs";
12
+
13
+ // packages/plugins/plugin-sheet/src/components/Sheet/Sheet.tsx
14
+ import { DndContext, DragOverlay, KeyboardSensor, MouseSensor, TouchSensor, useDraggable, useDroppable, useSensor, useSensors } from "@dnd-kit/core";
15
+ import { restrictToHorizontalAxis, restrictToVerticalAxis } from "@dnd-kit/modifiers";
16
+ import { getEventCoordinates, useCombinedRefs } from "@dnd-kit/utilities";
17
+ import { Function as FunctionIcon } from "@phosphor-icons/react";
18
+ import { Resizable } from "re-resizable";
19
+ import React6, { forwardRef, useEffect as useEffect4, useImperativeHandle, useMemo as useMemo4, useRef, useState as useState5 } from "react";
20
+ import { createPortal } from "react-dom";
21
+ import { useResizeDetector } from "react-resize-detector";
22
+ import { debounce as debounce2 } from "@dxos/async";
23
+ import { fullyQualifiedId as fullyQualifiedId2, createDocAccessor } from "@dxos/client/echo";
24
+ import { log as log2 } from "@dxos/log";
25
+ import { createAttendableAttributes, useHasAttention } from "@dxos/react-ui-attention";
26
+ import { mx as mx2 } from "@dxos/react-ui-theme";
27
+
28
+ // packages/plugins/plugin-sheet/src/components/Sheet/grid.ts
29
+ import { useEffect, useState } from "react";
30
+
31
+ // packages/plugins/plugin-sheet/src/defs/types.ts
32
+ import { invariant } from "@dxos/invariant";
33
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/plugin-sheet/src/defs/types.ts";
34
+ var DEFAULT_ROWS = 50;
35
+ var DEFAULT_COLUMNS = 26;
36
+ var MAX_ROWS = 500;
37
+ var MAX_COLUMNS = 26 * 2;
38
+ var posEquals = (a, b) => {
39
+ return a?.col === b?.col && a?.row === b?.row;
40
+ };
41
+ var columnLetter = (col) => {
42
+ invariant(col < MAX_COLUMNS, `Invalid column: ${col}`, {
43
+ F: __dxlog_file,
44
+ L: 26,
45
+ S: void 0,
46
+ A: [
47
+ "col < MAX_COLUMNS",
48
+ "`Invalid column: ${col}`"
49
+ ]
50
+ });
51
+ return (col >= 26 ? String.fromCharCode("A".charCodeAt(0) + Math.floor(col / 26) - 1) : "") + String.fromCharCode("A".charCodeAt(0) + col % 26);
52
+ };
53
+ var addressToA1Notation = ({ col, row }) => {
54
+ return `${columnLetter(col)}${row + 1}`;
55
+ };
56
+ var addressFromA1Notation = (ref) => {
57
+ const match = ref.match(/([A-Z]+)(\d+)/);
58
+ invariant(match, `Invalid notation: ${ref}`, {
59
+ F: __dxlog_file,
60
+ L: 39,
61
+ S: void 0,
62
+ A: [
63
+ "match",
64
+ "`Invalid notation: ${ref}`"
65
+ ]
66
+ });
67
+ return {
68
+ row: parseInt(match[2], 10) - 1,
69
+ col: match[1].split("").reduce((acc, c) => acc * 26 + c.charCodeAt(0) - "A".charCodeAt(0) + 1, 0) - 1
70
+ };
71
+ };
72
+ var rangeToA1Notation = (range) => {
73
+ return [
74
+ range?.from && addressToA1Notation(range?.from),
75
+ range?.to && addressToA1Notation(range?.to)
76
+ ].filter(Boolean).join(":");
77
+ };
78
+ var inRange = (range, cell) => {
79
+ if (!range) {
80
+ return false;
81
+ }
82
+ const { from, to } = range;
83
+ if (from && posEquals(from, cell) || to && posEquals(to, cell)) {
84
+ return true;
85
+ }
86
+ if (!from || !to) {
87
+ return false;
88
+ }
89
+ const { col: c1, row: r1 } = from;
90
+ const { col: c2, row: r2 } = to;
91
+ const cMin = Math.min(c1, c2);
92
+ const cMax = Math.max(c1, c2);
93
+ const rMin = Math.min(r1, r2);
94
+ const rMax = Math.max(r1, r2);
95
+ const { col, row } = cell;
96
+ return col >= cMin && col <= cMax && row >= rMin && row <= rMax;
97
+ };
98
+
99
+ // packages/plugins/plugin-sheet/src/defs/util.ts
100
+ import { randomBytes } from "@dxos/crypto";
101
+ import { create } from "@dxos/echo-schema";
102
+ var ApiError = class extends Error {
103
+ };
104
+ var ReadonlyException = class extends ApiError {
105
+ };
106
+ var RangeException = class extends ApiError {
107
+ constructor(n) {
108
+ super();
109
+ }
110
+ };
111
+ var createIndex = (length = 8) => {
112
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
113
+ const charactersLength = characters.length;
114
+ const randomBuffer = randomBytes(length);
115
+ return Array.from(randomBuffer, (byte) => characters[byte % charactersLength]).join("");
116
+ };
117
+ var createIndices = (length) => Array.from({
118
+ length
119
+ }).map(() => createIndex());
120
+ var insertIndices = (indices, i, n, max) => {
121
+ if (i + n > max) {
122
+ throw new RangeException(i + n);
123
+ }
124
+ const idx = createIndices(n);
125
+ indices.splice(i, 0, ...idx);
126
+ };
127
+ var initialize = (sheet, { rows = DEFAULT_ROWS, columns = DEFAULT_COLUMNS } = {}) => {
128
+ if (!sheet.rows.length) {
129
+ insertIndices(sheet.rows, 0, rows, MAX_ROWS);
130
+ }
131
+ if (!sheet.columns.length) {
132
+ insertIndices(sheet.columns, 0, columns, MAX_COLUMNS);
133
+ }
134
+ };
135
+ var createSheet = ({ title, ...size } = {}) => {
136
+ const sheet = create(SheetType, {
137
+ title,
138
+ cells: {},
139
+ rows: [],
140
+ columns: [],
141
+ rowMeta: {},
142
+ columnMeta: {},
143
+ formatting: {}
144
+ });
145
+ initialize(sheet, size);
146
+ return sheet;
147
+ };
148
+ var addressToIndex = (sheet, cell) => {
149
+ return `${sheet.columns[cell.col]}@${sheet.rows[cell.row]}`;
150
+ };
151
+ var addressFromIndex = (sheet, idx) => {
152
+ const [column, row] = idx.split("@");
153
+ return {
154
+ col: sheet.columns.indexOf(column),
155
+ row: sheet.rows.indexOf(row)
156
+ };
157
+ };
158
+ var rangeFromIndex = (sheet, idx) => {
159
+ const [from, to] = idx.split(":").map((index) => addressFromIndex(sheet, index));
160
+ return {
161
+ from,
162
+ to
163
+ };
164
+ };
165
+ var closest = (cursor, cells) => {
166
+ let closestCell;
167
+ let closestDistance = Number.MAX_SAFE_INTEGER;
168
+ for (const cell of cells) {
169
+ const distance = Math.abs(cell.row - cursor.row) + Math.abs(cell.col - cursor.col);
170
+ if (distance < closestDistance) {
171
+ closestCell = cell;
172
+ closestDistance = distance;
173
+ }
174
+ }
175
+ return closestCell;
176
+ };
177
+ var compareIndexPositions = (sheet, indexA, indexB) => {
178
+ const { row: rowA, col: columnA } = addressFromIndex(sheet, indexA);
179
+ const { row: rowB, col: columnB } = addressFromIndex(sheet, indexB);
180
+ if (rowA !== rowB) {
181
+ return rowA - rowB;
182
+ } else {
183
+ return columnA - columnB;
184
+ }
185
+ };
186
+
187
+ // packages/plugins/plugin-sheet/src/components/Sheet/grid.ts
188
+ var axisWidth = "calc(var(--rail-size)-2px)";
189
+ var axisHeight = 34;
190
+ var minWidth = 40;
191
+ var maxWidth = 800;
192
+ var minHeight = axisHeight;
193
+ var maxHeight = 400;
194
+ var defaultWidth = 200;
195
+ var defaultHeight = minHeight;
196
+ var CELL_DATA_KEY = "cell";
197
+ var useGridLayout = ({ scroller, size, rows, columns, rowSizes, columnSizes }) => {
198
+ const [rowPositions, setRowPositions] = useState([]);
199
+ useEffect(() => {
200
+ if (!rowSizes) {
201
+ return;
202
+ }
203
+ let y = 0;
204
+ setRowPositions(rows.map((idx, i) => {
205
+ const height2 = rowSizes?.[idx] ?? defaultHeight;
206
+ const top = y;
207
+ y += height2 - 1;
208
+ return {
209
+ row: i,
210
+ top,
211
+ height: height2
212
+ };
213
+ }));
214
+ }, [
215
+ rows,
216
+ rowSizes
217
+ ]);
218
+ const [columnPositions, setColumnPositions] = useState([]);
219
+ useEffect(() => {
220
+ if (!columns) {
221
+ return;
222
+ }
223
+ let x = 0;
224
+ setColumnPositions(columns.map((idx, i) => {
225
+ const width2 = columnSizes?.[idx] ?? defaultWidth;
226
+ const left = x;
227
+ x += width2 - 1;
228
+ return {
229
+ col: i,
230
+ left,
231
+ width: width2
232
+ };
233
+ }));
234
+ }, [
235
+ columns,
236
+ columnSizes
237
+ ]);
238
+ const height = rowPositions.length ? rowPositions[rowPositions.length - 1].top + rowPositions[rowPositions.length - 1].height : 0;
239
+ const width = columnPositions.length ? columnPositions[columnPositions.length - 1].left + columnPositions[columnPositions.length - 1].width : 0;
240
+ const [{ rowRange, columnRange }, setWindow] = useState({
241
+ rowRange: [],
242
+ columnRange: []
243
+ });
244
+ useEffect(() => {
245
+ const handleScroll = () => {
246
+ if (!scroller) {
247
+ return;
248
+ }
249
+ const { scrollLeft: left, scrollTop: top, clientWidth: width2, clientHeight: height2 } = scroller;
250
+ let rowStart = 0;
251
+ let rowEnd = 0;
252
+ for (let i = 0; i < rowPositions.length; i++) {
253
+ const row = rowPositions[i];
254
+ if (row.top <= top) {
255
+ rowStart = i;
256
+ }
257
+ if (row.top + row.height >= top + height2) {
258
+ rowEnd = i;
259
+ break;
260
+ }
261
+ }
262
+ let columnStart = 0;
263
+ let columnEnd = 0;
264
+ for (let i = 0; i < columnPositions.length; i++) {
265
+ const column = columnPositions[i];
266
+ if (column.left <= left) {
267
+ columnStart = i;
268
+ }
269
+ if (column.left + column.width >= left + width2) {
270
+ columnEnd = i;
271
+ break;
272
+ }
273
+ }
274
+ const overscan = 5;
275
+ setWindow({
276
+ rowRange: rowPositions.slice(Math.max(0, rowStart - overscan), Math.min(rowPositions.length, rowEnd + overscan)),
277
+ columnRange: columnPositions.slice(Math.max(0, columnStart - overscan), Math.min(columnPositions.length, columnEnd + overscan))
278
+ });
279
+ };
280
+ scroller?.addEventListener("scroll", handleScroll);
281
+ handleScroll();
282
+ return () => {
283
+ scroller?.removeEventListener("scroll", handleScroll);
284
+ };
285
+ }, [
286
+ size.width,
287
+ size.height,
288
+ rowPositions,
289
+ columnPositions
290
+ ]);
291
+ return {
292
+ width,
293
+ height,
294
+ rowRange,
295
+ columnRange
296
+ };
297
+ };
298
+ var getCellAtPointer = (event) => {
299
+ const element = document.elementFromPoint(event.clientX, event.clientY);
300
+ const root = element?.closest(`[data-${CELL_DATA_KEY}]`);
301
+ if (root) {
302
+ const value = root.dataset[CELL_DATA_KEY];
303
+ if (value) {
304
+ return addressFromA1Notation(value);
305
+ }
306
+ }
307
+ };
308
+ var getCellElement = (root, cell) => {
309
+ const pos = addressToA1Notation(cell);
310
+ return root.querySelector(`[data-${CELL_DATA_KEY}="${pos}"]`);
311
+ };
312
+
313
+ // packages/plugins/plugin-sheet/src/components/Sheet/nav.ts
314
+ import { useState as useState2 } from "react";
315
+ var handleNav = (ev, cursor, range, size) => {
316
+ if (cursor && ev.shiftKey) {
317
+ const opposite = range?.to ?? {
318
+ ...cursor
319
+ };
320
+ switch (ev.key) {
321
+ case "ArrowUp": {
322
+ if (opposite.row > 0) {
323
+ opposite.row -= 1;
324
+ }
325
+ break;
326
+ }
327
+ case "ArrowDown": {
328
+ if (opposite.row < size.numRows - 1) {
329
+ opposite.row += 1;
330
+ }
331
+ break;
332
+ }
333
+ case "ArrowLeft": {
334
+ if (opposite.col > 0) {
335
+ opposite.col -= 1;
336
+ }
337
+ break;
338
+ }
339
+ case "ArrowRight": {
340
+ if (opposite.col < size.numCols - 1) {
341
+ opposite.col += 1;
342
+ }
343
+ break;
344
+ }
345
+ }
346
+ return {
347
+ cursor,
348
+ range: {
349
+ from: cursor,
350
+ to: opposite
351
+ }
352
+ };
353
+ }
354
+ const next = handleArrowNav(ev, cursor, size);
355
+ return {
356
+ cursor: next
357
+ };
358
+ };
359
+ var handleArrowNav = (ev, cursor, { numRows, numCols }) => {
360
+ switch (ev.key) {
361
+ case "ArrowUp":
362
+ if (cursor === void 0) {
363
+ return {
364
+ row: 0,
365
+ col: 0
366
+ };
367
+ } else if (cursor.row > 0) {
368
+ return {
369
+ row: ev.metaKey ? 0 : cursor.row - 1,
370
+ col: cursor.col
371
+ };
372
+ }
373
+ break;
374
+ case "ArrowDown":
375
+ if (cursor === void 0) {
376
+ return {
377
+ row: 0,
378
+ col: 0
379
+ };
380
+ } else if (cursor.row < numRows - 1) {
381
+ return {
382
+ row: ev.metaKey ? numRows - 1 : cursor.row + 1,
383
+ col: cursor.col
384
+ };
385
+ }
386
+ break;
387
+ case "ArrowLeft":
388
+ if (cursor === void 0) {
389
+ return {
390
+ row: 0,
391
+ col: 0
392
+ };
393
+ } else if (cursor.col > 0) {
394
+ return {
395
+ row: cursor.row,
396
+ col: ev.metaKey ? 0 : cursor.col - 1
397
+ };
398
+ }
399
+ break;
400
+ case "ArrowRight":
401
+ if (cursor === void 0) {
402
+ return {
403
+ row: 0,
404
+ col: 0
405
+ };
406
+ } else if (cursor.col < numCols - 1) {
407
+ return {
408
+ row: cursor.row,
409
+ col: ev.metaKey ? numCols - 1 : cursor.col + 1
410
+ };
411
+ }
412
+ break;
413
+ case "Home":
414
+ return {
415
+ row: 0,
416
+ col: 0
417
+ };
418
+ case "End":
419
+ return {
420
+ row: numRows - 1,
421
+ col: numCols - 1
422
+ };
423
+ }
424
+ };
425
+ var useRangeSelect = (cb) => {
426
+ const [from, setFrom] = useState2();
427
+ const [to, setTo] = useState2();
428
+ const onMouseDown = (ev) => {
429
+ const current = getCellAtPointer(ev);
430
+ setFrom(current);
431
+ if (current) {
432
+ setTimeout(() => cb("start", {
433
+ from: current
434
+ }));
435
+ }
436
+ };
437
+ const onMouseMove = (ev) => {
438
+ if (from) {
439
+ let current = getCellAtPointer(ev);
440
+ if (posEquals(current, from)) {
441
+ current = void 0;
442
+ }
443
+ setTo(current);
444
+ setTimeout(() => cb("move", {
445
+ from,
446
+ to: current
447
+ }));
448
+ }
449
+ };
450
+ const onMouseUp = (ev) => {
451
+ if (from) {
452
+ let current = getCellAtPointer(ev);
453
+ if (posEquals(current, from)) {
454
+ current = void 0;
455
+ }
456
+ setFrom(void 0);
457
+ setTo(void 0);
458
+ setTimeout(() => cb("end", current ? {
459
+ from,
460
+ to: current
461
+ } : void 0));
462
+ }
463
+ };
464
+ return {
465
+ range: from ? {
466
+ from,
467
+ to
468
+ } : void 0,
469
+ handlers: {
470
+ onMouseDown,
471
+ onMouseMove,
472
+ onMouseUp
473
+ }
474
+ };
475
+ };
476
+
477
+ // packages/plugins/plugin-sheet/src/components/Sheet/sheet-context.tsx
478
+ import React3, { createContext as createContext2, useContext as useContext2, useMemo as useMemo2, useState as useState4 } from "react";
479
+ import { invariant as invariant3 } from "@dxos/invariant";
480
+
481
+ // packages/plugins/plugin-sheet/src/components/Sheet/decorations.ts
482
+ import { create as create2 } from "@dxos/echo-schema";
483
+ var createDecorations = () => {
484
+ const { decorations } = create2({
485
+ decorations: {}
486
+ });
487
+ const addDecoration = (cellIndex, decorator) => {
488
+ decorations[cellIndex] = [
489
+ ...decorations[cellIndex] || [],
490
+ decorator
491
+ ];
492
+ };
493
+ const removeDecoration = (cellIndex, type) => {
494
+ if (type) {
495
+ decorations[cellIndex] = (decorations[cellIndex] || []).filter((d) => d.type !== type);
496
+ } else {
497
+ delete decorations[cellIndex];
498
+ }
499
+ };
500
+ const getDecorationsForCell = (cellIndex) => {
501
+ return decorations[cellIndex];
502
+ };
503
+ const getAllDecorations = () => {
504
+ const result = [];
505
+ for (const decoratorArray of Object.values(decorations)) {
506
+ for (const decorator of decoratorArray) {
507
+ result.push(decorator);
508
+ }
509
+ }
510
+ return result;
511
+ };
512
+ return {
513
+ addDecoration,
514
+ removeDecoration,
515
+ getDecorationsForCell,
516
+ getAllDecorations
517
+ };
518
+ };
519
+
520
+ // packages/plugins/plugin-sheet/src/hooks/useComputeGraph.ts
521
+ import { useContext } from "react";
522
+ import { raise } from "@dxos/debug";
523
+ import { useAsyncState } from "@dxos/react-hooks";
524
+
525
+ // packages/plugins/plugin-sheet/src/components/index.ts
526
+ import React2 from "react";
527
+
528
+ // packages/plugins/plugin-sheet/src/components/ComputeGraph/ComputeGraphContextProvider.tsx
529
+ import React, { createContext } from "react";
530
+ var ComputeGraphContext = /* @__PURE__ */ createContext(void 0);
531
+ var ComputeGraphContextProvider = ({ registry, children }) => {
532
+ return /* @__PURE__ */ React.createElement(ComputeGraphContext.Provider, {
533
+ value: {
534
+ registry
535
+ }
536
+ }, children);
537
+ };
538
+
539
+ // packages/plugins/plugin-sheet/src/components/index.ts
540
+ var SheetContainer = React2.lazy(() => import("./SheetContainer-PXSJX6XK.mjs"));
541
+
542
+ // packages/plugins/plugin-sheet/src/hooks/useComputeGraph.ts
543
+ var useComputeGraph = (space) => {
544
+ const { registry } = useContext(ComputeGraphContext) ?? raise(new Error("Missing ComputeGraphContext"));
545
+ return useAsyncState(async () => space && registry.getOrCreateGraph(space), [
546
+ space,
547
+ registry
548
+ ]);
549
+ };
550
+
551
+ // packages/plugins/plugin-sheet/src/hooks/useFormattingModel.ts
552
+ import { useMemo } from "react";
553
+
554
+ // packages/plugins/plugin-sheet/src/model/formatting-model.ts
555
+ var FormattingModel = class {
556
+ constructor(_model) {
557
+ this._model = _model;
558
+ }
559
+ /**
560
+ * Get formatted string value and className for cell.
561
+ */
562
+ getFormatting(cell) {
563
+ const value = this._model.getValue(cell);
564
+ if (value === void 0 || value === null) {
565
+ return {};
566
+ }
567
+ const locales = void 0;
568
+ const idx = addressToIndex(this._model.sheet, cell);
569
+ let formatting = this._model.sheet.formatting?.[idx] ?? {};
570
+ const classNames = [
571
+ ...formatting?.classNames ?? []
572
+ ];
573
+ for (const [idx2, _formatting] of Object.entries(this._model.sheet.formatting)) {
574
+ const range = rangeFromIndex(this._model.sheet, idx2);
575
+ if (inRange(range, cell)) {
576
+ if (_formatting.classNames) {
577
+ classNames.push(..._formatting.classNames);
578
+ }
579
+ if (_formatting.type) {
580
+ formatting = _formatting;
581
+ }
582
+ }
583
+ }
584
+ const defaultNumber = "justify-end font-mono";
585
+ const type = formatting?.type ?? this._model.getValueType(cell);
586
+ switch (type) {
587
+ case ValueTypeEnum.Boolean: {
588
+ return {
589
+ value: value.toLocaleString().toUpperCase(),
590
+ classNames: [
591
+ ...classNames,
592
+ value ? "!text-greenText" : "!text-orangeText"
593
+ ]
594
+ };
595
+ }
596
+ //
597
+ // Numbers.
598
+ //
599
+ case ValueTypeEnum.Number: {
600
+ return {
601
+ value: value.toLocaleString(locales),
602
+ classNames: [
603
+ ...classNames,
604
+ defaultNumber
605
+ ]
606
+ };
607
+ }
608
+ case ValueTypeEnum.Percent: {
609
+ return {
610
+ value: value * 100 + "%",
611
+ classNames: [
612
+ ...classNames,
613
+ defaultNumber
614
+ ]
615
+ };
616
+ }
617
+ case ValueTypeEnum.Currency: {
618
+ return {
619
+ value: value.toLocaleString(locales, {
620
+ style: "currency",
621
+ currency: "USD",
622
+ minimumFractionDigits: 2,
623
+ maximumFractionDigits: 2
624
+ }),
625
+ classNames: [
626
+ ...classNames,
627
+ defaultNumber
628
+ ]
629
+ };
630
+ }
631
+ //
632
+ // Dates.
633
+ //
634
+ case ValueTypeEnum.DateTime: {
635
+ const date = this._model.toLocalDate(value);
636
+ return {
637
+ value: date.toLocaleString(locales),
638
+ classNames
639
+ };
640
+ }
641
+ case ValueTypeEnum.Date: {
642
+ const date = this._model.toLocalDate(value);
643
+ return {
644
+ value: date.toLocaleDateString(locales),
645
+ classNames
646
+ };
647
+ }
648
+ case ValueTypeEnum.Time: {
649
+ const date = this._model.toLocalDate(value);
650
+ return {
651
+ value: date.toLocaleTimeString(locales),
652
+ classNames
653
+ };
654
+ }
655
+ default: {
656
+ return {
657
+ value: String(value),
658
+ classNames
659
+ };
660
+ }
661
+ }
662
+ }
663
+ };
664
+
665
+ // packages/plugins/plugin-sheet/src/model/sheet-model.ts
666
+ import { Event } from "@dxos/async";
667
+ import { Resource } from "@dxos/context";
668
+ import { invariant as invariant2 } from "@dxos/invariant";
669
+ import { PublicKey } from "@dxos/keys";
670
+ import { log } from "@dxos/log";
671
+ import { DetailedCellError, ExportedCellChange } from "#hyperformula";
672
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/plugins/plugin-sheet/src/model/sheet-model.ts";
673
+ var typeMap = {
674
+ BOOLEAN: ValueTypeEnum.Boolean,
675
+ NUMBER_RAW: ValueTypeEnum.Number,
676
+ NUMBER_PERCENT: ValueTypeEnum.Percent,
677
+ NUMBER_CURRENCY: ValueTypeEnum.Currency,
678
+ NUMBER_DATETIME: ValueTypeEnum.DateTime,
679
+ NUMBER_DATE: ValueTypeEnum.Date,
680
+ NUMBER_TIME: ValueTypeEnum.Time
681
+ };
682
+ var getTopLeft = (range) => {
683
+ const to = range.to ?? range.from;
684
+ return {
685
+ row: Math.min(range.from.row, to.row),
686
+ col: Math.min(range.from.col, to.col)
687
+ };
688
+ };
689
+ var toSimpleCellAddress = (sheet, cell) => ({
690
+ sheet,
691
+ row: cell.row,
692
+ col: cell.col
693
+ });
694
+ var toModelRange = (sheet, range) => ({
695
+ start: toSimpleCellAddress(sheet, range.from),
696
+ end: toSimpleCellAddress(sheet, range.to ?? range.from)
697
+ });
698
+ var SheetModel = class extends Resource {
699
+ constructor(_graph, _sheet, _options = {}) {
700
+ super();
701
+ this._graph = _graph;
702
+ this._sheet = _sheet;
703
+ this._options = _options;
704
+ this.id = `model-${PublicKey.random().truncate()}`;
705
+ this.update = new Event();
706
+ this._node = this._graph.getOrCreateNode(createSheetName(this._sheet.id));
707
+ this.reset();
708
+ }
709
+ get graph() {
710
+ return this._graph;
711
+ }
712
+ get sheet() {
713
+ return this._sheet;
714
+ }
715
+ get readonly() {
716
+ return this._options.readonly;
717
+ }
718
+ get bounds() {
719
+ return {
720
+ rows: this._sheet.rows.length,
721
+ columns: this._sheet.columns.length
722
+ };
723
+ }
724
+ /**
725
+ * Initialize sheet and engine.
726
+ */
727
+ async _open() {
728
+ log("initialize", {
729
+ id: this.id
730
+ }, {
731
+ F: __dxlog_file2,
732
+ L: 105,
733
+ S: this,
734
+ C: (f, a) => f(...a)
735
+ });
736
+ initialize(this._sheet);
737
+ this.reset();
738
+ const unsubscribe = this._graph.update.on(() => this.update.emit());
739
+ this._ctx.onDispose(unsubscribe);
740
+ }
741
+ /**
742
+ * Update engine.
743
+ * NOTE: This resets the undo history.
744
+ * @deprecated
745
+ */
746
+ reset() {
747
+ this._node.hf.clearSheet(this._node.sheetId);
748
+ Object.entries(this._sheet.cells).forEach(([key, { value }]) => {
749
+ const { col, row } = addressFromIndex(this._sheet, key);
750
+ if (typeof value === "string" && value.charAt(0) === "=") {
751
+ value = this._graph.mapFormulaToNative(this._graph.mapFunctionBindingFromId(this.mapFormulaIndicesToRefs(value)));
752
+ }
753
+ this._node.hf.setCellContents({
754
+ sheet: this._node.sheetId,
755
+ row,
756
+ col
757
+ }, value);
758
+ });
759
+ }
760
+ /**
761
+ * Recalculate formulas.
762
+ * NOTE: This resets the undo history.
763
+ * https://hyperformula.handsontable.com/guide/volatile-functions.html#volatile-actions
764
+ * @deprecated
765
+ */
766
+ // TODO(burdon): Remove.
767
+ recalculate() {
768
+ this._node.hf.rebuildAndRecalculate();
769
+ }
770
+ insertRows(i, n = 1) {
771
+ insertIndices(this._sheet.rows, i, n, MAX_ROWS);
772
+ this.reset();
773
+ }
774
+ insertColumns(i, n = 1) {
775
+ insertIndices(this._sheet.columns, i, n, MAX_COLUMNS);
776
+ this.reset();
777
+ }
778
+ //
779
+ // Undoable actions.
780
+ // TODO(burdon): Group undoable methods; consistently update hf/sheet.
781
+ //
782
+ /**
783
+ * Clear range of values.
784
+ */
785
+ clear(range) {
786
+ const topLeft = getTopLeft(range);
787
+ const values = this._iterRange(range, () => null);
788
+ this._node.hf.setCellContents(toSimpleCellAddress(this._node.sheetId, topLeft), values);
789
+ this._iterRange(range, (cell) => {
790
+ const idx = addressToIndex(this._sheet, cell);
791
+ delete this._sheet.cells[idx];
792
+ });
793
+ }
794
+ cut(range) {
795
+ this._node.hf.cut(toModelRange(this._node.sheetId, range));
796
+ this._iterRange(range, (cell) => {
797
+ const idx = addressToIndex(this._sheet, cell);
798
+ delete this._sheet.cells[idx];
799
+ });
800
+ }
801
+ copy(range) {
802
+ this._node.hf.copy(toModelRange(this._node.sheetId, range));
803
+ }
804
+ paste(cell) {
805
+ if (!this._node.hf.isClipboardEmpty()) {
806
+ const changes = this._node.hf.paste(toSimpleCellAddress(this._node.sheetId, cell));
807
+ for (const change of changes) {
808
+ if (change instanceof ExportedCellChange) {
809
+ const { address, newValue } = change;
810
+ const idx = addressToIndex(this._sheet, {
811
+ row: address.row,
812
+ col: address.col
813
+ });
814
+ this._sheet.cells[idx] = {
815
+ value: newValue
816
+ };
817
+ }
818
+ }
819
+ }
820
+ }
821
+ // TODO(burdon): Display undo/redo state.
822
+ undo() {
823
+ if (this._node.hf.isThereSomethingToUndo()) {
824
+ this._node.hf.undo();
825
+ this.update.emit();
826
+ }
827
+ }
828
+ redo() {
829
+ if (this._node.hf.isThereSomethingToRedo()) {
830
+ this._node.hf.redo();
831
+ this.update.emit();
832
+ }
833
+ }
834
+ /**
835
+ * Get value from sheet.
836
+ */
837
+ getCellValue(cell) {
838
+ const idx = addressToIndex(this._sheet, cell);
839
+ return this._sheet.cells[idx]?.value ?? null;
840
+ }
841
+ /**
842
+ * Get value as a string for editing.
843
+ */
844
+ getCellText(cell) {
845
+ const value = this.getCellValue(cell);
846
+ if (value == null) {
847
+ return void 0;
848
+ }
849
+ if (typeof value === "string" && value.charAt(0) === "=") {
850
+ return this._graph.mapFunctionBindingFromId(this.mapFormulaIndicesToRefs(value));
851
+ } else {
852
+ return String(value);
853
+ }
854
+ }
855
+ /**
856
+ * Get array of raw values from sheet.
857
+ */
858
+ getCellValues(range) {
859
+ return this._iterRange(range, (cell) => this.getCellValue(cell));
860
+ }
861
+ /**
862
+ * Gets the regular or computed value from the engine.
863
+ */
864
+ getValue(cell) {
865
+ const value = this._node.hf.getCellValue(toSimpleCellAddress(this._node.sheetId, cell));
866
+ if (value instanceof DetailedCellError) {
867
+ return value.toString();
868
+ }
869
+ return value;
870
+ }
871
+ /**
872
+ * Get value type.
873
+ */
874
+ getValueType(cell) {
875
+ const addr = toSimpleCellAddress(this._node.sheetId, cell);
876
+ const type = this._node.hf.getCellValueDetailedType(addr);
877
+ return typeMap[type];
878
+ }
879
+ /**
880
+ * Sets the value, updating the sheet and engine.
881
+ */
882
+ setValue(cell, value) {
883
+ if (this._options.readonly) {
884
+ throw new ReadonlyException();
885
+ }
886
+ let refresh = false;
887
+ if (cell.row >= this._sheet.rows.length) {
888
+ insertIndices(this._sheet.rows, cell.row, 1, MAX_ROWS);
889
+ refresh = true;
890
+ }
891
+ if (cell.col >= this._sheet.columns.length) {
892
+ insertIndices(this._sheet.columns, cell.col, 1, MAX_COLUMNS);
893
+ refresh = true;
894
+ }
895
+ if (refresh) {
896
+ this.reset();
897
+ }
898
+ this._node.hf.setCellContents({
899
+ sheet: this._node.sheetId,
900
+ row: cell.row,
901
+ col: cell.col
902
+ }, [
903
+ [
904
+ typeof value === "string" && value.charAt(0) === "=" ? this._graph.mapFormulaToNative(value) : value
905
+ ]
906
+ ]);
907
+ const idx = addressToIndex(this._sheet, cell);
908
+ if (value === void 0 || value === null) {
909
+ delete this._sheet.cells[idx];
910
+ } else {
911
+ if (typeof value === "string" && value.charAt(0) === "=") {
912
+ value = this._graph.mapFunctionBindingToId(this.mapFormulaRefsToIndices(value));
913
+ }
914
+ this._sheet.cells[idx] = {
915
+ value
916
+ };
917
+ }
918
+ }
919
+ /**
920
+ * Sets values from a simple map.
921
+ */
922
+ setValues(values) {
923
+ Object.entries(values).forEach(([key, { value }]) => {
924
+ this.setValue(addressFromA1Notation(key), value);
925
+ });
926
+ }
927
+ /**
928
+ * Iterate range.
929
+ */
930
+ _iterRange(range, cb) {
931
+ const to = range.to ?? range.from;
932
+ const rowRange = [
933
+ Math.min(range.from.row, to.row),
934
+ Math.max(range.from.row, to.row)
935
+ ];
936
+ const columnRange = [
937
+ Math.min(range.from.col, to.col),
938
+ Math.max(range.from.col, to.col)
939
+ ];
940
+ const rows = [];
941
+ for (let row = rowRange[0]; row <= rowRange[1]; row++) {
942
+ const rowCells = [];
943
+ for (let column = columnRange[0]; column <= columnRange[1]; column++) {
944
+ const value = cb({
945
+ row,
946
+ col: column
947
+ });
948
+ if (value !== void 0) {
949
+ rowCells.push(value);
950
+ }
951
+ }
952
+ rows.push(rowCells);
953
+ }
954
+ return rows;
955
+ }
956
+ // TODO(burdon): Delete index.
957
+ _deleteIndices(indices, i, n) {
958
+ throw new Error("Not implemented");
959
+ }
960
+ // TODO(burdon): Move. Cannot use fractional without changing. Switch back to using unique IDs?
961
+ _moveIndices(indices, i, j, n) {
962
+ throw new Error("Not implemented");
963
+ }
964
+ //
965
+ // Indices.
966
+ //
967
+ /**
968
+ * Map from A1 notation to indices.
969
+ */
970
+ mapFormulaRefsToIndices(formula) {
971
+ invariant2(formula.charAt(0) === "=", void 0, {
972
+ F: __dxlog_file2,
973
+ L: 358,
974
+ S: this,
975
+ A: [
976
+ "formula.charAt(0) === '='",
977
+ ""
978
+ ]
979
+ });
980
+ return formula.replace(/([a-zA-Z]+)([0-9]+)/g, (match) => {
981
+ return addressToIndex(this._sheet, addressFromA1Notation(match));
982
+ });
983
+ }
984
+ /**
985
+ * Map from indices to A1 notation.
986
+ */
987
+ mapFormulaIndicesToRefs(formula) {
988
+ invariant2(formula.charAt(0) === "=", void 0, {
989
+ F: __dxlog_file2,
990
+ L: 368,
991
+ S: this,
992
+ A: [
993
+ "formula.charAt(0) === '='",
994
+ ""
995
+ ]
996
+ });
997
+ return formula.replace(/([a-zA-Z0-9]+)@([a-zA-Z0-9]+)/g, (idx) => {
998
+ return addressToA1Notation(addressFromIndex(this._sheet, idx));
999
+ });
1000
+ }
1001
+ //
1002
+ // Values
1003
+ //
1004
+ /**
1005
+ * https://hyperformula.handsontable.com/guide/date-and-time-handling.html#example
1006
+ * https://hyperformula.handsontable.com/api/interfaces/configparams.html#nulldate
1007
+ * NOTE: TODAY() is number of FULL days since nullDate. It will typically be -1 days from NOW().
1008
+ */
1009
+ toLocalDate(num) {
1010
+ const { year, month, day, hours, minutes, seconds } = this.toDateTime(num);
1011
+ return new Date(year, month - 1, day, hours, minutes, seconds);
1012
+ }
1013
+ toDateTime(num) {
1014
+ return this._node.hf.numberToDateTime(num);
1015
+ }
1016
+ toDate(num) {
1017
+ return this._node.hf.numberToDate(num);
1018
+ }
1019
+ toTime(num) {
1020
+ return this._node.hf.numberToTime(num);
1021
+ }
1022
+ };
1023
+
1024
+ // packages/plugins/plugin-sheet/src/hooks/useFormattingModel.ts
1025
+ var useFormattingModel = (model) => {
1026
+ return useMemo(() => model && new FormattingModel(model), [
1027
+ model
1028
+ ]);
1029
+ };
1030
+
1031
+ // packages/plugins/plugin-sheet/src/hooks/useSheetModel.ts
1032
+ import { useEffect as useEffect2, useState as useState3 } from "react";
1033
+ var useSheetModel = (space, sheet, { readonly } = {}) => {
1034
+ const graph = useComputeGraph(space);
1035
+ const [model, setModel] = useState3();
1036
+ useEffect2(() => {
1037
+ if (!space || !graph || !sheet) {
1038
+ return;
1039
+ }
1040
+ let model2;
1041
+ const t = setTimeout(async () => {
1042
+ model2 = new SheetModel(graph, sheet, {
1043
+ readonly
1044
+ });
1045
+ await model2.open();
1046
+ setModel(model2);
1047
+ });
1048
+ return () => {
1049
+ clearTimeout(t);
1050
+ void model2?.close();
1051
+ };
1052
+ }, [
1053
+ space,
1054
+ sheet,
1055
+ graph,
1056
+ readonly
1057
+ ]);
1058
+ return model;
1059
+ };
1060
+
1061
+ // packages/plugins/plugin-sheet/src/components/Sheet/sheet-context.tsx
1062
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/plugins/plugin-sheet/src/components/Sheet/sheet-context.tsx";
1063
+ var SheetContext = /* @__PURE__ */ createContext2(null);
1064
+ var useSheetContext = () => {
1065
+ const context = useContext2(SheetContext);
1066
+ invariant3(context, void 0, {
1067
+ F: __dxlog_file3,
1068
+ L: 43,
1069
+ S: void 0,
1070
+ A: [
1071
+ "context",
1072
+ ""
1073
+ ]
1074
+ });
1075
+ return context;
1076
+ };
1077
+ var SheetContextProvider = ({ children, sheet, space, readonly, onInfo }) => {
1078
+ const model = useSheetModel(space, sheet, {
1079
+ readonly
1080
+ });
1081
+ const formatting = useFormattingModel(model);
1082
+ const [cursor, setCursor] = useState4();
1083
+ const [range, setRange] = useState4();
1084
+ const [editing, setEditing] = useState4(false);
1085
+ const decorations = useMemo2(() => createDecorations(), []);
1086
+ return !model || !formatting ? null : /* @__PURE__ */ React3.createElement(SheetContext.Provider, {
1087
+ value: {
1088
+ model,
1089
+ formatting,
1090
+ cursor,
1091
+ setCursor,
1092
+ range,
1093
+ setRange,
1094
+ editing,
1095
+ setEditing,
1096
+ // TODO(burdon): Change to event.
1097
+ onInfo,
1098
+ decorations
1099
+ }
1100
+ }, children);
1101
+ };
1102
+
1103
+ // packages/plugins/plugin-sheet/src/components/Sheet/threads.tsx
1104
+ import { effect } from "@preact/signals-core";
1105
+ import React4, { useCallback, useEffect as useEffect3, useMemo as useMemo3 } from "react";
1106
+ import { LayoutAction, useIntentDispatcher, useIntentResolver } from "@dxos/app-framework";
1107
+ import { debounce } from "@dxos/async";
1108
+ import { fullyQualifiedId } from "@dxos/react-client/echo";
1109
+ import { Icon, useTranslation } from "@dxos/react-ui";
1110
+ var CommentIndicator = () => {
1111
+ return /* @__PURE__ */ React4.createElement("div", {
1112
+ role: "none",
1113
+ className: "absolute top-0 right-0 w-0 h-0 border-t-8 border-l-8 border-t-cmCommentSurface border-l-transparent"
1114
+ });
1115
+ };
1116
+ var ThreadedCellWrapper = ({ children }) => {
1117
+ const dispatch = useIntentDispatcher();
1118
+ const [isHovered, setIsHovered] = React4.useState(false);
1119
+ const { t } = useTranslation(SHEET_PLUGIN);
1120
+ const handleClick = React4.useCallback((_event) => {
1121
+ void dispatch({
1122
+ action: LayoutAction.SET_LAYOUT,
1123
+ data: {
1124
+ element: "complementary",
1125
+ state: true
1126
+ }
1127
+ });
1128
+ }, [
1129
+ dispatch
1130
+ ]);
1131
+ return /* @__PURE__ */ React4.createElement("div", {
1132
+ role: "none",
1133
+ className: "relative h-full is-full",
1134
+ onMouseEnter: () => {
1135
+ setIsHovered(true);
1136
+ },
1137
+ onMouseLeave: () => {
1138
+ setIsHovered(false);
1139
+ }
1140
+ }, /* @__PURE__ */ React4.createElement(CommentIndicator, null), isHovered && /* @__PURE__ */ React4.createElement("div", {
1141
+ className: "absolute inset-0 flex items-center justify-end pr-1"
1142
+ }, /* @__PURE__ */ React4.createElement("button", {
1143
+ className: "ch-button text-xs min-bs-0 p-1",
1144
+ onClick: handleClick,
1145
+ "aria-label": t("open comment for sheet cell")
1146
+ }, /* @__PURE__ */ React4.createElement(Icon, {
1147
+ icon: "ph--chat--regular",
1148
+ "aria-hidden": true
1149
+ }))), children);
1150
+ };
1151
+ var createThreadDecoration = (cellIndex, threadId, sheetId) => {
1152
+ return {
1153
+ type: "comment",
1154
+ cellIndex,
1155
+ decorate: (props) => /* @__PURE__ */ React4.createElement(ThreadedCellWrapper, props)
1156
+ };
1157
+ };
1158
+ var useUpdateCursorOnThreadSelection = () => {
1159
+ const { setCursor, model } = useSheetContext();
1160
+ const handleScrollIntoView = useCallback(({ action, data }) => {
1161
+ switch (action) {
1162
+ case LayoutAction.SCROLL_INTO_VIEW: {
1163
+ if (!data?.id || data?.cursor === void 0 || data?.id !== fullyQualifiedId(model.sheet)) {
1164
+ return;
1165
+ }
1166
+ const cellAddress = addressFromIndex(model.sheet, data.cursor);
1167
+ setCursor(cellAddress);
1168
+ }
1169
+ }
1170
+ }, [
1171
+ model.sheet,
1172
+ setCursor
1173
+ ]);
1174
+ useIntentResolver(SHEET_PLUGIN, handleScrollIntoView);
1175
+ };
1176
+ var useSelectThreadOnCursorChange = () => {
1177
+ const { cursor, model } = useSheetContext();
1178
+ const dispatch = useIntentDispatcher();
1179
+ const activeThreads = useMemo3(() => model.sheet.threads?.filter((thread) => !!thread && thread.status === "active") ?? [], [
1180
+ JSON.stringify(model.sheet.threads)
1181
+ ]);
1182
+ const activeThreadAddresses = useMemo3(() => activeThreads.map((thread) => thread.anchor).filter((anchor) => anchor !== void 0).map((anchor) => addressFromIndex(model.sheet, anchor)), [
1183
+ activeThreads,
1184
+ model.sheet
1185
+ ]);
1186
+ const selectClosestThread = useCallback((cellAddress) => {
1187
+ if (!cellAddress || !activeThreads) {
1188
+ return;
1189
+ }
1190
+ const closestThreadAnchor = closest(cellAddress, activeThreadAddresses);
1191
+ if (closestThreadAnchor) {
1192
+ const closestThread = activeThreads.find((thread) => thread && thread.anchor === addressToIndex(model.sheet, closestThreadAnchor));
1193
+ if (closestThread) {
1194
+ void dispatch([
1195
+ {
1196
+ action: "dxos.org/plugin/thread/action/select",
1197
+ data: {
1198
+ current: fullyQualifiedId(closestThread)
1199
+ }
1200
+ }
1201
+ ]);
1202
+ }
1203
+ }
1204
+ }, [
1205
+ dispatch,
1206
+ activeThreads,
1207
+ activeThreadAddresses,
1208
+ model.sheet
1209
+ ]);
1210
+ const debounced = useMemo3(() => {
1211
+ return debounce((cursor2) => requestAnimationFrame(() => selectClosestThread(cursor2)), 50);
1212
+ }, [
1213
+ selectClosestThread
1214
+ ]);
1215
+ useEffect3(() => {
1216
+ if (!cursor) {
1217
+ return;
1218
+ }
1219
+ debounced(cursor);
1220
+ }, [
1221
+ cursor,
1222
+ selectClosestThread
1223
+ ]);
1224
+ };
1225
+ var useThreadDecorations = () => {
1226
+ const { decorations, model } = useSheetContext();
1227
+ const sheet = useMemo3(() => model.sheet, [
1228
+ model.sheet
1229
+ ]);
1230
+ const sheetId = useMemo3(() => fullyQualifiedId(sheet), [
1231
+ sheet
1232
+ ]);
1233
+ useEffect3(() => {
1234
+ const unsubscribe = effect(() => {
1235
+ const activeThreadAnchors = /* @__PURE__ */ new Set();
1236
+ if (!sheet.threads) {
1237
+ return;
1238
+ }
1239
+ for (const thread of sheet.threads) {
1240
+ if (!thread || thread.anchor === void 0 || thread.status === "resolved") {
1241
+ continue;
1242
+ }
1243
+ activeThreadAnchors.add(thread.anchor);
1244
+ const index = thread.anchor;
1245
+ const existingDecorations = decorations.getDecorationsForCell(index);
1246
+ if (!existingDecorations || !existingDecorations.some((d) => d.type === "comment")) {
1247
+ decorations.addDecoration(index, createThreadDecoration(index, thread.id, sheetId));
1248
+ }
1249
+ }
1250
+ for (const decoration of decorations.getAllDecorations()) {
1251
+ if (decoration.type !== "comment") {
1252
+ continue;
1253
+ }
1254
+ if (!activeThreadAnchors.has(decoration.cellIndex)) {
1255
+ decorations.removeDecoration(decoration.cellIndex, "comment");
1256
+ }
1257
+ }
1258
+ });
1259
+ return () => unsubscribe();
1260
+ });
1261
+ };
1262
+ var useThreads = () => {
1263
+ useUpdateCursorOnThreadSelection();
1264
+ useSelectThreadOnCursorChange();
1265
+ useThreadDecorations();
1266
+ };
1267
+
1268
+ // packages/plugins/plugin-sheet/src/components/Sheet/util.ts
1269
+ var getRelativeClientRect = (root, element) => {
1270
+ const rootRect = root.getBoundingClientRect();
1271
+ const elementRect = element.getBoundingClientRect();
1272
+ return new DOMRect(elementRect.left - rootRect.left + root.scrollLeft, elementRect.top - rootRect.top + root.scrollTop, elementRect.width, elementRect.height);
1273
+ };
1274
+ var getRectUnion = (b1, b2) => {
1275
+ return {
1276
+ left: Math.min(b1.left, b2.left),
1277
+ top: Math.min(b1.top, b2.top),
1278
+ width: Math.abs(b1.left - b2.left) + (b1.left > b2.left ? b1.width : b2.width),
1279
+ height: Math.abs(b1.top - b2.top) + (b1.height > b2.height ? b1.height : b2.height)
1280
+ };
1281
+ };
1282
+ var scrollIntoView = (scrollContainer, el) => {
1283
+ el.scrollIntoView({
1284
+ block: "nearest",
1285
+ inline: "nearest"
1286
+ });
1287
+ const cellBounds = el.getBoundingClientRect();
1288
+ const scrollerBounds = scrollContainer.getBoundingClientRect();
1289
+ if (cellBounds.top < scrollerBounds.top) {
1290
+ scrollContainer.scrollTop -= scrollerBounds.top - cellBounds.top;
1291
+ } else if (cellBounds.bottom >= scrollerBounds.bottom - 1) {
1292
+ scrollContainer.scrollTop += 2 + scrollerBounds.bottom - cellBounds.bottom;
1293
+ }
1294
+ if (cellBounds.left < scrollerBounds.left) {
1295
+ scrollContainer.scrollLeft -= scrollerBounds.left - cellBounds.left;
1296
+ } else if (cellBounds.right >= scrollerBounds.right) {
1297
+ scrollContainer.scrollLeft += 2 + scrollerBounds.right - cellBounds.right;
1298
+ }
1299
+ };
1300
+
1301
+ // packages/plugins/plugin-sheet/src/components/CellEditor/CellEditor.tsx
1302
+ import { EditorView, keymap } from "@codemirror/view";
1303
+ import React5 from "react";
1304
+ import { useThemeContext } from "@dxos/react-ui";
1305
+ import { createBasicExtensions, createThemeExtensions, preventNewline, useTextEditor } from "@dxos/react-ui-editor";
1306
+ var editorKeys = ({ onNav, onClose }) => {
1307
+ return keymap.of([
1308
+ {
1309
+ key: "ArrowUp",
1310
+ run: (editor) => {
1311
+ const value = editor.state.doc.toString();
1312
+ onNav?.(value, {
1313
+ key: "ArrowUp"
1314
+ });
1315
+ return !!onNav;
1316
+ }
1317
+ },
1318
+ {
1319
+ key: "ArrowDown",
1320
+ run: (editor) => {
1321
+ const value = editor.state.doc.toString();
1322
+ onNav?.(value, {
1323
+ key: "ArrowDown"
1324
+ });
1325
+ return !!onNav;
1326
+ }
1327
+ },
1328
+ {
1329
+ key: "ArrowLeft",
1330
+ run: (editor) => {
1331
+ const value = editor.state.doc.toString();
1332
+ onNav?.(value, {
1333
+ key: "ArrowLeft"
1334
+ });
1335
+ return !!onNav;
1336
+ }
1337
+ },
1338
+ {
1339
+ key: "ArrowRight",
1340
+ run: (editor) => {
1341
+ const value = editor.state.doc.toString();
1342
+ onNav?.(value, {
1343
+ key: "ArrowRight"
1344
+ });
1345
+ return !!onNav;
1346
+ }
1347
+ },
1348
+ {
1349
+ key: "Enter",
1350
+ run: (editor) => {
1351
+ onClose(editor.state.doc.toString(), {
1352
+ key: "Enter"
1353
+ });
1354
+ return true;
1355
+ },
1356
+ shift: (editor) => {
1357
+ onClose(editor.state.doc.toString(), {
1358
+ key: "Enter",
1359
+ shift: true
1360
+ });
1361
+ return true;
1362
+ }
1363
+ },
1364
+ {
1365
+ key: "Tab",
1366
+ run: (editor) => {
1367
+ onClose(editor.state.doc.toString(), {
1368
+ key: "Tab"
1369
+ });
1370
+ return true;
1371
+ },
1372
+ shift: (editor) => {
1373
+ onClose(editor.state.doc.toString(), {
1374
+ key: "Tab",
1375
+ shift: true
1376
+ });
1377
+ return true;
1378
+ }
1379
+ },
1380
+ {
1381
+ key: "Escape",
1382
+ run: () => {
1383
+ onClose(void 0, {
1384
+ key: "Escape"
1385
+ });
1386
+ return true;
1387
+ }
1388
+ }
1389
+ ]);
1390
+ };
1391
+ var editorVariants = {
1392
+ // TODO(thure): remove when legacy is no longer used.
1393
+ legacy: {
1394
+ root: "flex w-full",
1395
+ editor: "flex w-full [&>.cm-scroller]:scrollbar-none",
1396
+ content: "!px-2 !py-1"
1397
+ },
1398
+ grid: {
1399
+ root: "absolute z-[1]",
1400
+ editor: "[&>.cm-scroller]:scrollbar-none tabular-nums",
1401
+ content: "!border !border-transparent !p-0.5"
1402
+ }
1403
+ };
1404
+ var CellEditor = ({ value, extension, autoFocus, onBlur, variant = "legacy", box, gridId }) => {
1405
+ const { themeMode } = useThemeContext();
1406
+ const { parentRef } = useTextEditor(() => {
1407
+ return {
1408
+ autoFocus,
1409
+ initialValue: value,
1410
+ selection: {
1411
+ anchor: value?.length ?? 0
1412
+ },
1413
+ extensions: [
1414
+ extension ?? [],
1415
+ preventNewline,
1416
+ EditorView.focusChangeEffect.of((_, focusing) => {
1417
+ if (!focusing) {
1418
+ onBlur?.({
1419
+ type: "blur"
1420
+ });
1421
+ }
1422
+ return null;
1423
+ }),
1424
+ createBasicExtensions({
1425
+ lineWrapping: false
1426
+ }),
1427
+ createThemeExtensions({
1428
+ themeMode,
1429
+ slots: {
1430
+ editor: {
1431
+ className: editorVariants[variant].editor
1432
+ },
1433
+ content: {
1434
+ className: editorVariants[variant].content
1435
+ }
1436
+ }
1437
+ })
1438
+ ]
1439
+ };
1440
+ }, [
1441
+ extension,
1442
+ autoFocus,
1443
+ value,
1444
+ variant,
1445
+ onBlur
1446
+ ]);
1447
+ return /* @__PURE__ */ React5.createElement("div", {
1448
+ ref: parentRef,
1449
+ className: editorVariants[variant].root,
1450
+ style: box,
1451
+ ...gridId && {
1452
+ "data-grid": gridId
1453
+ }
1454
+ });
1455
+ };
1456
+
1457
+ // packages/plugins/plugin-sheet/src/components/CellEditor/extension.ts
1458
+ import { acceptCompletion, autocompletion, completionStatus, startCompletion } from "@codemirror/autocomplete";
1459
+ import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
1460
+ import { Facet } from "@codemirror/state";
1461
+ import { ViewPlugin, keymap as keymap2 } from "@codemirror/view";
1462
+ import { tags } from "@lezer/highlight";
1463
+ import { spreadsheet } from "codemirror-lang-spreadsheet";
1464
+ import { mx } from "@dxos/react-ui-theme";
1465
+ var highlightStyles = HighlightStyle.define([
1466
+ // Function.
1467
+ {
1468
+ tag: tags.name,
1469
+ class: "text-accentText"
1470
+ },
1471
+ // Range.
1472
+ {
1473
+ tag: tags.tagName,
1474
+ class: "text-pinkText"
1475
+ },
1476
+ // Values.
1477
+ {
1478
+ tag: tags.number,
1479
+ class: "text-tealText"
1480
+ },
1481
+ {
1482
+ tag: tags.bool,
1483
+ class: "text-tealText"
1484
+ },
1485
+ {
1486
+ tag: tags.string,
1487
+ class: "text-tealText"
1488
+ },
1489
+ // Error.
1490
+ {
1491
+ tag: tags.invalid,
1492
+ class: "text-unAccent"
1493
+ }
1494
+ ]);
1495
+ var languageFacet = Facet.define();
1496
+ var sheetExtension = ({ functions = [] }) => {
1497
+ const { extension, language } = spreadsheet({
1498
+ idiom: "en-US",
1499
+ decimalSeparator: "."
1500
+ });
1501
+ const createCompletion = (name) => {
1502
+ const { section = "Custom", description, syntax } = functions.find((value) => value.name === name) ?? {};
1503
+ return {
1504
+ section,
1505
+ label: name,
1506
+ info: () => {
1507
+ if (!description && !syntax) {
1508
+ return null;
1509
+ }
1510
+ const root = document.createElement("div");
1511
+ root.className = "flex flex-col gap-2 text-sm";
1512
+ const title = document.createElement("h2");
1513
+ title.innerText = name;
1514
+ title.className = "text-lg font-mono text-accentText";
1515
+ root.appendChild(title);
1516
+ if (description) {
1517
+ const info = document.createElement("p");
1518
+ info.innerText = description;
1519
+ info.className = "text-subdued";
1520
+ root.appendChild(info);
1521
+ }
1522
+ if (syntax) {
1523
+ const detail = document.createElement("pre");
1524
+ detail.innerText = syntax;
1525
+ detail.className = "whitespace-pre-wrap text-greenText";
1526
+ root.appendChild(detail);
1527
+ }
1528
+ return root;
1529
+ },
1530
+ apply: (view, completion, from, to) => {
1531
+ const insertParens = to === view.state.doc.toString().length;
1532
+ view.dispatch(view.state.update({
1533
+ changes: {
1534
+ from,
1535
+ to,
1536
+ insert: completion.label + (insertParens ? "()" : "")
1537
+ },
1538
+ selection: {
1539
+ anchor: from + completion.label.length + 1
1540
+ }
1541
+ }));
1542
+ }
1543
+ };
1544
+ };
1545
+ return [
1546
+ extension,
1547
+ languageFacet.of(language),
1548
+ language.data.of({
1549
+ autocomplete: (context) => {
1550
+ if (context.state.doc.toString()[0] !== "=") {
1551
+ return null;
1552
+ }
1553
+ const match = context.matchBefore(/\w*/);
1554
+ if (!match || match.from === match.to) {
1555
+ return null;
1556
+ }
1557
+ const text = match.text.toUpperCase();
1558
+ if (!context.explicit && match.text.length < 2) {
1559
+ return null;
1560
+ }
1561
+ return {
1562
+ from: match.from,
1563
+ options: functions?.filter(({ name }) => name.startsWith(text)).map(({ name }) => createCompletion(name)) ?? []
1564
+ };
1565
+ }
1566
+ }),
1567
+ syntaxHighlighting(highlightStyles),
1568
+ autocompletion({
1569
+ aboveCursor: false,
1570
+ defaultKeymap: true,
1571
+ activateOnTyping: true,
1572
+ // NOTE: Useful for debugging.
1573
+ closeOnBlur: false,
1574
+ icons: false,
1575
+ tooltipClass: () => mx("!-left-[1px] !top-[33px] !-m-0 border !border-t-0 [&>ul]:!min-w-[198px]", "[&>ul>li[aria-selected]]:!bg-accentSurface", "border-separator")
1576
+ }),
1577
+ keymap2.of([
1578
+ {
1579
+ key: "Tab",
1580
+ run: (view) => {
1581
+ return completionStatus(view.state) === "active" ? acceptCompletion(view) : startCompletion(view);
1582
+ }
1583
+ }
1584
+ ])
1585
+ ];
1586
+ };
1587
+ var rangeExtension = (onInit) => {
1588
+ let view;
1589
+ let activeRange;
1590
+ const provider = (range) => {
1591
+ if (activeRange) {
1592
+ view.dispatch(view.state.update({
1593
+ changes: {
1594
+ ...activeRange,
1595
+ insert: range.toString()
1596
+ },
1597
+ selection: {
1598
+ anchor: activeRange.from + range.length
1599
+ }
1600
+ }));
1601
+ }
1602
+ view.focus();
1603
+ };
1604
+ return ViewPlugin.fromClass(class {
1605
+ constructor(_view) {
1606
+ view = _view;
1607
+ onInit(provider);
1608
+ }
1609
+ update(view2) {
1610
+ const { anchor } = view2.state.selection.ranges[0];
1611
+ activeRange = void 0;
1612
+ const [language] = view2.state.facet(languageFacet);
1613
+ const { topNode } = language.parser.parse(view2.state.doc.toString());
1614
+ visitTree(topNode, ({ type, from, to }) => {
1615
+ if (from <= anchor && to >= anchor) {
1616
+ switch (type.name) {
1617
+ case "Function": {
1618
+ activeRange = {
1619
+ from: to,
1620
+ to
1621
+ };
1622
+ break;
1623
+ }
1624
+ case "CloseParen": {
1625
+ activeRange = {
1626
+ from,
1627
+ to: from
1628
+ };
1629
+ break;
1630
+ }
1631
+ case "RangeToken":
1632
+ case "CellToken":
1633
+ activeRange = {
1634
+ from,
1635
+ to
1636
+ };
1637
+ return true;
1638
+ }
1639
+ }
1640
+ return false;
1641
+ });
1642
+ if (!activeRange && view2.state.doc.toString()[0] === "=") {
1643
+ activeRange = {
1644
+ from: 1,
1645
+ to: view2.state.doc.toString().length
1646
+ };
1647
+ }
1648
+ }
1649
+ });
1650
+ };
1651
+ var visitTree = (node, callback) => {
1652
+ if (callback(node)) {
1653
+ return true;
1654
+ }
1655
+ for (let child = node.firstChild; child !== null; child = child.nextSibling) {
1656
+ if (visitTree(child, callback)) {
1657
+ return true;
1658
+ }
1659
+ }
1660
+ return false;
1661
+ };
1662
+
1663
+ // packages/plugins/plugin-sheet/src/components/Sheet/Sheet.tsx
1664
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/plugins/plugin-sheet/src/components/Sheet/Sheet.tsx";
1665
+ var fragments = {
1666
+ axis: "bg-axisSurface text-axisText text-xs select-none",
1667
+ axisSelected: "bg-attention text-baseText",
1668
+ cell: "bg-gridCell",
1669
+ cellSelected: "bg-gridCellSelected text-baseText border !border-accentSurface"
1670
+ };
1671
+ var SheetRoot = ({ children, ...props }) => {
1672
+ return /* @__PURE__ */ React6.createElement(SheetContextProvider, props, children);
1673
+ };
1674
+ var SheetMain = /* @__PURE__ */ forwardRef(({ classNames, numRows, numCols }, forwardRef2) => {
1675
+ const { model, cursor, setCursor, setRange, setEditing } = useSheetContext();
1676
+ const { rowsRef, columnsRef, contentRef } = useScrollHandlers();
1677
+ useThreads();
1678
+ const [rows, setRows] = useState5([
1679
+ ...model.sheet.rows
1680
+ ]);
1681
+ const [columns, setColumns] = useState5([
1682
+ ...model.sheet.columns
1683
+ ]);
1684
+ useEffect4(() => {
1685
+ const rowsAccessor = createDocAccessor(model.sheet, [
1686
+ "rows"
1687
+ ]);
1688
+ const columnsAccessor = createDocAccessor(model.sheet, [
1689
+ "columns"
1690
+ ]);
1691
+ const handleUpdate = debounce2(() => {
1692
+ setRows([
1693
+ ...model.sheet.rows
1694
+ ]);
1695
+ setColumns([
1696
+ ...model.sheet.columns
1697
+ ]);
1698
+ }, 100);
1699
+ rowsAccessor.handle.addListener("change", handleUpdate);
1700
+ columnsAccessor.handle.addListener("change", handleUpdate);
1701
+ handleUpdate();
1702
+ return () => {
1703
+ rowsAccessor.handle.removeListener("change", handleUpdate);
1704
+ columnsAccessor.handle.removeListener("change", handleUpdate);
1705
+ };
1706
+ }, [
1707
+ model
1708
+ ]);
1709
+ useEffect4(() => {
1710
+ model.reset();
1711
+ }, [
1712
+ rows,
1713
+ columns
1714
+ ]);
1715
+ const handleMoveRows = (from, to, num = 1) => {
1716
+ const cursorIdx = cursor ? addressToIndex(model.sheet, cursor) : void 0;
1717
+ const [rows2] = model.sheet.rows.splice(from, num);
1718
+ model.sheet.rows.splice(to, 0, rows2);
1719
+ if (cursorIdx) {
1720
+ setCursor(addressFromIndex(model.sheet, cursorIdx));
1721
+ }
1722
+ setRows([
1723
+ ...model.sheet.rows
1724
+ ]);
1725
+ };
1726
+ const handleMoveColumns = (from, to, num = 1) => {
1727
+ const cursorIdx = cursor ? addressToIndex(model.sheet, cursor) : void 0;
1728
+ const columns2 = model.sheet.columns.splice(from, num);
1729
+ model.sheet.columns.splice(to, 0, ...columns2);
1730
+ if (cursorIdx) {
1731
+ setCursor(addressFromIndex(model.sheet, cursorIdx));
1732
+ }
1733
+ setColumns([
1734
+ ...model.sheet.columns
1735
+ ]);
1736
+ };
1737
+ const [rowSizes, setRowSizes] = useState5();
1738
+ const [columnSizes, setColumnSizes] = useState5();
1739
+ useEffect4(() => {
1740
+ const rowAccessor = createDocAccessor(model.sheet, [
1741
+ "rowMeta"
1742
+ ]);
1743
+ const columnAccessor = createDocAccessor(model.sheet, [
1744
+ "columnMeta"
1745
+ ]);
1746
+ const handleUpdate = debounce2(() => {
1747
+ const mapSizes = (values) => values.reduce((map, [idx, meta]) => {
1748
+ if (meta.size) {
1749
+ map[idx] = meta.size;
1750
+ }
1751
+ return map;
1752
+ }, {});
1753
+ setRowSizes(mapSizes(Object.entries(model.sheet.rowMeta)));
1754
+ setColumnSizes(mapSizes(Object.entries(model.sheet.columnMeta)));
1755
+ }, 100);
1756
+ rowAccessor.handle.addListener("change", handleUpdate);
1757
+ columnAccessor.handle.addListener("change", handleUpdate);
1758
+ handleUpdate();
1759
+ return () => {
1760
+ rowAccessor.handle.removeListener("change", handleUpdate);
1761
+ columnAccessor.handle.removeListener("change", handleUpdate);
1762
+ };
1763
+ }, [
1764
+ model
1765
+ ]);
1766
+ const handleResizeRow = (idx, size, save) => {
1767
+ if (save) {
1768
+ model.sheet.rowMeta[idx] ??= {};
1769
+ model.sheet.rowMeta[idx].size = size;
1770
+ } else {
1771
+ setRowSizes((sizes) => ({
1772
+ ...sizes,
1773
+ [idx]: size
1774
+ }));
1775
+ }
1776
+ };
1777
+ const handleResizeColumn = (idx, size, save) => {
1778
+ if (save) {
1779
+ model.sheet.columnMeta[idx] ??= {};
1780
+ model.sheet.columnMeta[idx].size = size;
1781
+ } else {
1782
+ setColumnSizes((sizes) => ({
1783
+ ...sizes,
1784
+ [idx]: size
1785
+ }));
1786
+ }
1787
+ };
1788
+ return /* @__PURE__ */ React6.createElement("div", {
1789
+ role: "none",
1790
+ className: mx2("grid grid-cols-[calc(var(--rail-size)-2px)_1fr] grid-rows-[32px_1fr_32px] bs-full is-full overflow-hidden", classNames)
1791
+ }, /* @__PURE__ */ React6.createElement(GridCorner, {
1792
+ onClick: () => {
1793
+ setCursor(void 0);
1794
+ setRange(void 0);
1795
+ setEditing(false);
1796
+ }
1797
+ }), /* @__PURE__ */ React6.createElement(SheetColumns, {
1798
+ ref: columnsRef,
1799
+ columns,
1800
+ sizes: columnSizes,
1801
+ selected: cursor?.col,
1802
+ onSelect: (col) => setCursor(cursor?.col === col ? void 0 : {
1803
+ row: -1,
1804
+ col
1805
+ }),
1806
+ onResize: handleResizeColumn,
1807
+ onMove: handleMoveColumns
1808
+ }), /* @__PURE__ */ React6.createElement(SheetRows, {
1809
+ ref: rowsRef,
1810
+ rows,
1811
+ sizes: rowSizes,
1812
+ selected: cursor?.row,
1813
+ onSelect: (row) => setCursor(cursor?.row === row ? void 0 : {
1814
+ row,
1815
+ col: -1
1816
+ }),
1817
+ onResize: handleResizeRow,
1818
+ onMove: handleMoveRows
1819
+ }), /* @__PURE__ */ React6.createElement(SheetGrid, {
1820
+ ref: contentRef,
1821
+ size: {
1822
+ numRows: numRows ?? rows.length,
1823
+ numCols: numCols ?? columns.length
1824
+ },
1825
+ rows,
1826
+ columns,
1827
+ rowSizes,
1828
+ columnSizes
1829
+ }), /* @__PURE__ */ React6.createElement(GridCorner, null), /* @__PURE__ */ React6.createElement(SheetStatusBar, null));
1830
+ });
1831
+ var useScrollHandlers = () => {
1832
+ const rowsRef = useRef(null);
1833
+ const columnsRef = useRef(null);
1834
+ const contentRef = useRef(null);
1835
+ useEffect4(() => {
1836
+ const handleRowsScroll = (ev) => {
1837
+ const { scrollTop } = ev.target;
1838
+ if (!rowsRef.current.dataset.locked) {
1839
+ contentRef.current.scrollTop = scrollTop;
1840
+ }
1841
+ };
1842
+ const handleColumnsScroll = (ev) => {
1843
+ const { scrollLeft } = ev.target;
1844
+ if (!columnsRef.current.dataset.locked) {
1845
+ contentRef.current.scrollLeft = scrollLeft;
1846
+ }
1847
+ };
1848
+ const handleContentScroll = (ev) => {
1849
+ const { scrollTop, scrollLeft } = ev.target;
1850
+ rowsRef.current.scrollTop = scrollTop;
1851
+ columnsRef.current.scrollLeft = scrollLeft;
1852
+ };
1853
+ const rows = rowsRef.current;
1854
+ const columns = columnsRef.current;
1855
+ const content = contentRef.current;
1856
+ rows.addEventListener("scroll", handleRowsScroll);
1857
+ columns.addEventListener("scroll", handleColumnsScroll);
1858
+ content.addEventListener("scroll", handleContentScroll);
1859
+ return () => {
1860
+ rows.removeEventListener("scroll", handleRowsScroll);
1861
+ columns.removeEventListener("scroll", handleColumnsScroll);
1862
+ content.removeEventListener("scroll", handleContentScroll);
1863
+ };
1864
+ }, []);
1865
+ return {
1866
+ rowsRef,
1867
+ columnsRef,
1868
+ contentRef
1869
+ };
1870
+ };
1871
+ var GridCorner = (props) => {
1872
+ return /* @__PURE__ */ React6.createElement("div", {
1873
+ className: fragments.axis,
1874
+ ...props
1875
+ });
1876
+ };
1877
+ var MovingOverlay = ({ label }) => {
1878
+ return /* @__PURE__ */ React6.createElement("div", {
1879
+ className: "flex w-full h-full justify-center items-center text-sm p-1 bg-gridOverlay cursor-pointer"
1880
+ }, label);
1881
+ };
1882
+ var mouseConstraints = {
1883
+ distance: 10
1884
+ };
1885
+ var touchConstraints = {
1886
+ delay: 250,
1887
+ tolerance: 5
1888
+ };
1889
+ var SheetRows = /* @__PURE__ */ forwardRef(({ rows, sizes, selected, onSelect, onResize, onMove }, forwardRef2) => {
1890
+ const mouseSensor = useSensor(MouseSensor, {
1891
+ activationConstraint: mouseConstraints
1892
+ });
1893
+ const touchSensor = useSensor(TouchSensor, {
1894
+ activationConstraint: touchConstraints
1895
+ });
1896
+ const keyboardSensor = useSensor(KeyboardSensor, {});
1897
+ const sensors = useSensors(mouseSensor, touchSensor, keyboardSensor);
1898
+ const [active, setActive] = useState5(null);
1899
+ const handleDragStart = ({ active: active2 }) => {
1900
+ setActive(active2);
1901
+ };
1902
+ const handleDragEnd = ({ over, active: active2 }) => {
1903
+ if (over && over.id !== active2.id) {
1904
+ setActive(null);
1905
+ onMove?.(active2.data.current.index, over.data.current.index);
1906
+ }
1907
+ };
1908
+ const snapToCenter = ({ activatorEvent, draggingNodeRect, transform }) => {
1909
+ if (draggingNodeRect && activatorEvent) {
1910
+ const activatorCoordinates = getEventCoordinates(activatorEvent);
1911
+ if (!activatorCoordinates) {
1912
+ return transform;
1913
+ }
1914
+ const offset = activatorCoordinates.y - draggingNodeRect.top;
1915
+ return {
1916
+ ...transform,
1917
+ y: transform.y + offset - draggingNodeRect.height / 2
1918
+ };
1919
+ }
1920
+ return transform;
1921
+ };
1922
+ return /* @__PURE__ */ React6.createElement("div", {
1923
+ className: "relative flex grow overflow-hidden"
1924
+ }, /* @__PURE__ */ React6.createElement("div", {
1925
+ className: mx2("z-20 absolute inset-0 border-y border-gridLine pointer-events-none"),
1926
+ style: {
1927
+ width: axisWidth
1928
+ }
1929
+ }), /* @__PURE__ */ React6.createElement("div", {
1930
+ ref: forwardRef2,
1931
+ role: "rowheader",
1932
+ className: "grow overflow-y-auto scrollbar-none"
1933
+ }, /* @__PURE__ */ React6.createElement(DndContext, {
1934
+ sensors,
1935
+ modifiers: [
1936
+ restrictToVerticalAxis,
1937
+ snapToCenter
1938
+ ],
1939
+ onDragStart: handleDragStart,
1940
+ onDragEnd: handleDragEnd
1941
+ }, /* @__PURE__ */ React6.createElement("div", {
1942
+ className: "flex flex-col",
1943
+ style: {
1944
+ width: axisWidth
1945
+ }
1946
+ }, rows.map((idx, index) => /* @__PURE__ */ React6.createElement(GridRowCell, {
1947
+ key: idx,
1948
+ idx,
1949
+ index,
1950
+ label: String(index + 1),
1951
+ size: sizes?.[idx] ?? defaultHeight,
1952
+ resize: index < rows.length - 1,
1953
+ selected: selected === index,
1954
+ onResize,
1955
+ onSelect
1956
+ }))), /* @__PURE__ */ createPortal(/* @__PURE__ */ React6.createElement(DragOverlay, null, active && /* @__PURE__ */ React6.createElement(MovingOverlay, {
1957
+ label: String(active.data.current.index + 1)
1958
+ })), document.body))));
1959
+ });
1960
+ var GridRowCell = ({ idx, index, label, size, resize, selected, onSelect, onResize }) => {
1961
+ const { setNodeRef: setDroppableNodeRef } = useDroppable({
1962
+ id: idx,
1963
+ data: {
1964
+ index
1965
+ }
1966
+ });
1967
+ const { setNodeRef: setDraggableNodeRef, attributes, listeners, isDragging, over } = useDraggable({
1968
+ id: idx,
1969
+ data: {
1970
+ index
1971
+ }
1972
+ });
1973
+ const setNodeRef = useCombinedRefs(setDroppableNodeRef, setDraggableNodeRef);
1974
+ const [initialSize, setInitialSize] = useState5(size);
1975
+ const [resizing, setResizing] = useState5(false);
1976
+ const scrollHandler = useRef();
1977
+ const handleResizeStart = (_ev, _dir, elementRef) => {
1978
+ const scrollContainer = elementRef.closest('[role="rowheader"]');
1979
+ const scrollTop = scrollContainer.scrollTop;
1980
+ scrollHandler.current = (ev) => ev.target.scrollTop = scrollTop;
1981
+ scrollContainer.addEventListener("scroll", scrollHandler.current);
1982
+ scrollContainer.dataset.locked = "true";
1983
+ setResizing(true);
1984
+ };
1985
+ const handleResize = (_ev, _dir, _elementRef, { height }) => {
1986
+ onResize?.(idx, initialSize + height);
1987
+ };
1988
+ const handleResizeStop = (_ev, _dir, elementRef, { height }) => {
1989
+ const scrollContainer = elementRef.closest('[role="rowheader"]');
1990
+ scrollContainer.removeEventListener("scroll", scrollHandler.current);
1991
+ delete scrollContainer.dataset.locked;
1992
+ scrollHandler.current = void 0;
1993
+ setInitialSize(initialSize + height);
1994
+ onResize?.(idx, initialSize + height, true);
1995
+ setResizing(false);
1996
+ };
1997
+ return /* @__PURE__ */ React6.createElement(Resizable, {
1998
+ enable: {
1999
+ bottom: resize
2000
+ },
2001
+ size: {
2002
+ height: size - 1
2003
+ },
2004
+ minHeight: minHeight - 1,
2005
+ maxHeight,
2006
+ onResizeStart: handleResizeStart,
2007
+ onResize: handleResize,
2008
+ onResizeStop: handleResizeStop
2009
+ }, /* @__PURE__ */ React6.createElement("div", {
2010
+ ref: setNodeRef,
2011
+ ...attributes,
2012
+ ...listeners,
2013
+ className: mx2("flex h-full items-center justify-center cursor-pointer", "border-t border-gridLine focus-visible:outline-none", fragments.axis, selected && fragments.axisSelected, isDragging && fragments.axisSelected),
2014
+ onClick: () => onSelect?.(index)
2015
+ }, /* @__PURE__ */ React6.createElement("span", {
2016
+ className: "flex w-full justify-center"
2017
+ }, label), over?.id === idx && !isDragging && /* @__PURE__ */ React6.createElement("div", {
2018
+ className: "z-20 absolute top-0 w-full min-h-[4px] border-b-4 border-accentSurface"
2019
+ }), resizing && /* @__PURE__ */ React6.createElement("div", {
2020
+ className: "z-20 absolute bottom-0 w-full min-h-[4px] border-b-4 border-accentSurface"
2021
+ })));
2022
+ };
2023
+ var SheetColumns = /* @__PURE__ */ forwardRef(({ columns, sizes, selected, onSelect, onResize, onMove }, forwardRef2) => {
2024
+ const mouseSensor = useSensor(MouseSensor, {
2025
+ activationConstraint: mouseConstraints
2026
+ });
2027
+ const touchSensor = useSensor(TouchSensor, {
2028
+ activationConstraint: touchConstraints
2029
+ });
2030
+ const keyboardSensor = useSensor(KeyboardSensor, {});
2031
+ const sensors = useSensors(mouseSensor, touchSensor, keyboardSensor);
2032
+ const [active, setActive] = useState5(null);
2033
+ const handleDragStart = ({ active: active2 }) => {
2034
+ setActive(active2);
2035
+ };
2036
+ const handleDragEnd = ({ active: active2, over }) => {
2037
+ if (over && over.id !== active2.id) {
2038
+ setActive(null);
2039
+ onMove?.(active2.data.current.index, over.data.current.index);
2040
+ }
2041
+ };
2042
+ const snapToCenter = ({ activatorEvent, draggingNodeRect, transform }) => {
2043
+ if (draggingNodeRect && activatorEvent) {
2044
+ const activatorCoordinates = getEventCoordinates(activatorEvent);
2045
+ if (!activatorCoordinates) {
2046
+ return transform;
2047
+ }
2048
+ const offset = activatorCoordinates.x - draggingNodeRect.left;
2049
+ return {
2050
+ ...transform,
2051
+ x: transform.x + offset - draggingNodeRect.width / 2
2052
+ };
2053
+ }
2054
+ return transform;
2055
+ };
2056
+ return /* @__PURE__ */ React6.createElement("div", {
2057
+ className: "relative flex grow overflow-hidden"
2058
+ }, /* @__PURE__ */ React6.createElement("div", {
2059
+ className: mx2("z-20 absolute inset-0 border-x border-gridLine pointer-events-none"),
2060
+ style: {
2061
+ height: axisHeight
2062
+ }
2063
+ }), /* @__PURE__ */ React6.createElement("div", {
2064
+ ref: forwardRef2,
2065
+ role: "columnheader",
2066
+ className: "grow overflow-x-auto scrollbar-none"
2067
+ }, /* @__PURE__ */ React6.createElement(DndContext, {
2068
+ autoScroll: {
2069
+ enabled: true
2070
+ },
2071
+ sensors,
2072
+ modifiers: [
2073
+ restrictToHorizontalAxis,
2074
+ snapToCenter
2075
+ ],
2076
+ onDragStart: handleDragStart,
2077
+ onDragEnd: handleDragEnd
2078
+ }, /* @__PURE__ */ React6.createElement("div", {
2079
+ className: "flex h-full",
2080
+ style: {
2081
+ height: axisHeight
2082
+ }
2083
+ }, columns.map((idx, index) => /* @__PURE__ */ React6.createElement(GridColumnCell, {
2084
+ key: idx,
2085
+ idx,
2086
+ index,
2087
+ label: columnLetter(index),
2088
+ size: sizes?.[idx] ?? defaultWidth,
2089
+ resize: index < columns.length - 1,
2090
+ selected: selected === index,
2091
+ onResize,
2092
+ onSelect
2093
+ }))), /* @__PURE__ */ createPortal(/* @__PURE__ */ React6.createElement(DragOverlay, null, active && /* @__PURE__ */ React6.createElement(MovingOverlay, {
2094
+ label: columnLetter(active.data.current.index)
2095
+ })), document.body))));
2096
+ });
2097
+ var GridColumnCell = ({ idx, index, label, size, resize, selected, onSelect, onResize }) => {
2098
+ const { setNodeRef: setDroppableNodeRef } = useDroppable({
2099
+ id: idx,
2100
+ data: {
2101
+ index
2102
+ }
2103
+ });
2104
+ const { setNodeRef: setDraggableNodeRef, attributes, listeners, over, isDragging } = useDraggable({
2105
+ id: idx,
2106
+ data: {
2107
+ index
2108
+ }
2109
+ });
2110
+ const setNodeRef = useCombinedRefs(setDroppableNodeRef, setDraggableNodeRef);
2111
+ const [initialSize, setInitialSize] = useState5(size);
2112
+ const [resizing, setResizing] = useState5(false);
2113
+ const scrollHandler = useRef();
2114
+ const handleResizeStart = (_ev, _dir, elementRef) => {
2115
+ const scrollContainer = elementRef.closest('[role="columnheader"]');
2116
+ const scrollLeft = scrollContainer.scrollLeft;
2117
+ scrollHandler.current = (ev) => ev.target.scrollLeft = scrollLeft;
2118
+ scrollContainer.addEventListener("scroll", scrollHandler.current);
2119
+ scrollContainer.dataset.locked = "true";
2120
+ setResizing(true);
2121
+ };
2122
+ const handleResize = (_ev, _dir, _elementRef, { width }) => {
2123
+ onResize?.(idx, initialSize + width);
2124
+ };
2125
+ const handleResizeStop = (_ev, _dir, elementRef, { width }) => {
2126
+ const scrollContainer = elementRef.closest('[role="columnheader"]');
2127
+ scrollContainer.removeEventListener("scroll", scrollHandler.current);
2128
+ delete scrollContainer.dataset.locked;
2129
+ scrollHandler.current = void 0;
2130
+ setInitialSize(initialSize + width);
2131
+ onResize?.(idx, initialSize + width, true);
2132
+ setResizing(false);
2133
+ };
2134
+ return /* @__PURE__ */ React6.createElement(Resizable, {
2135
+ enable: {
2136
+ right: resize
2137
+ },
2138
+ size: {
2139
+ width: size - 1
2140
+ },
2141
+ minWidth: minWidth - 1,
2142
+ maxWidth,
2143
+ onResizeStart: handleResizeStart,
2144
+ onResize: handleResize,
2145
+ onResizeStop: handleResizeStop
2146
+ }, /* @__PURE__ */ React6.createElement("div", {
2147
+ ref: setNodeRef,
2148
+ ...attributes,
2149
+ ...listeners,
2150
+ className: mx2("flex h-full items-center justify-center cursor-pointer", "border-l border-gridLine focus-visible:outline-none", fragments.axis, selected && fragments.axisSelected, isDragging && fragments.axisSelected),
2151
+ onClick: () => onSelect?.(index)
2152
+ }, /* @__PURE__ */ React6.createElement("span", {
2153
+ className: "flex w-full justify-center"
2154
+ }, label), over?.id === idx && !isDragging && /* @__PURE__ */ React6.createElement("div", {
2155
+ className: "z-20 absolute left-0 h-full min-w-[4px] border-l-4 border-accentSurface"
2156
+ }), resizing && /* @__PURE__ */ React6.createElement("div", {
2157
+ className: "z-20 absolute right-0 h-full min-h-[4px] border-l-4 border-accentSurface"
2158
+ })));
2159
+ };
2160
+ var SheetGrid = /* @__PURE__ */ forwardRef(({ size, rows, columns, rowSizes, columnSizes }, forwardRef2) => {
2161
+ const { ref: containerRef, width: containerWidth = 0, height: containerHeight = 0 } = useResizeDetector({
2162
+ refreshRate: 200
2163
+ });
2164
+ const scrollerRef = useRef(null);
2165
+ useImperativeHandle(forwardRef2, () => scrollerRef.current);
2166
+ const { model, cursor, range, editing, setCursor, setRange, setEditing, onInfo } = useSheetContext();
2167
+ const initialText = useRef();
2168
+ const quickEdit = useRef(false);
2169
+ const [, forceUpdate] = useState5({});
2170
+ useEffect4(() => {
2171
+ const unsubscribe = model.update.on(() => {
2172
+ log2("updated", {
2173
+ id: model.id
2174
+ }, {
2175
+ F: __dxlog_file4,
2176
+ L: 737,
2177
+ S: void 0,
2178
+ C: (f, a) => f(...a)
2179
+ });
2180
+ forceUpdate({});
2181
+ });
2182
+ return () => {
2183
+ unsubscribe();
2184
+ };
2185
+ }, [
2186
+ model
2187
+ ]);
2188
+ const inputRef = useRef(null);
2189
+ const handleKeyDown = (ev) => {
2190
+ const isMacOS = /Mac|iPhone|iPod|iPad/.test(navigator.userAgent);
2191
+ if (cursor && (isMacOS && ev.metaKey || ev.ctrlKey)) {
2192
+ switch (ev.key) {
2193
+ case "x": {
2194
+ model.cut(range ?? {
2195
+ from: cursor
2196
+ });
2197
+ return;
2198
+ }
2199
+ case "c": {
2200
+ model.copy(range ?? {
2201
+ from: cursor
2202
+ });
2203
+ return;
2204
+ }
2205
+ case "v": {
2206
+ model.paste(cursor);
2207
+ return;
2208
+ }
2209
+ case "z": {
2210
+ if (ev.shiftKey) {
2211
+ model.redo();
2212
+ } else {
2213
+ model.undo();
2214
+ }
2215
+ return;
2216
+ }
2217
+ }
2218
+ }
2219
+ switch (ev.key) {
2220
+ case "ArrowUp":
2221
+ case "ArrowDown":
2222
+ case "ArrowLeft":
2223
+ case "ArrowRight":
2224
+ case "Home":
2225
+ case "End": {
2226
+ const next = handleNav(ev, cursor, range, size);
2227
+ setRange(next.range);
2228
+ if (next.cursor) {
2229
+ setCursor(next.cursor);
2230
+ const element = getCellElement(scrollerRef.current, next.cursor);
2231
+ if (element) {
2232
+ scrollIntoView(scrollerRef.current, element);
2233
+ }
2234
+ }
2235
+ break;
2236
+ }
2237
+ case "Backspace": {
2238
+ if (cursor) {
2239
+ if (range) {
2240
+ model.clear(range);
2241
+ } else {
2242
+ model.setValue(cursor, null);
2243
+ }
2244
+ }
2245
+ break;
2246
+ }
2247
+ case "Escape": {
2248
+ setRange(void 0);
2249
+ break;
2250
+ }
2251
+ case "Enter": {
2252
+ ev.stopPropagation();
2253
+ if (cursor) {
2254
+ setEditing(true);
2255
+ }
2256
+ break;
2257
+ }
2258
+ case "?": {
2259
+ onInfo?.();
2260
+ break;
2261
+ }
2262
+ default: {
2263
+ if (ev.key.length === 1) {
2264
+ initialText.current = ev.key;
2265
+ quickEdit.current = true;
2266
+ setEditing(true);
2267
+ }
2268
+ }
2269
+ }
2270
+ };
2271
+ const { handlers } = useRangeSelect((event, range2) => {
2272
+ switch (event) {
2273
+ case "start": {
2274
+ setRange(void 0);
2275
+ break;
2276
+ }
2277
+ default: {
2278
+ setRange(range2);
2279
+ }
2280
+ }
2281
+ });
2282
+ const { width, height, rowRange, columnRange } = useGridLayout({
2283
+ scroller: scrollerRef.current,
2284
+ size: {
2285
+ width: containerWidth,
2286
+ height: containerHeight
2287
+ },
2288
+ rows,
2289
+ columns,
2290
+ rowSizes,
2291
+ columnSizes
2292
+ });
2293
+ const id = fullyQualifiedId2(model.sheet);
2294
+ const attendableAttrs = createAttendableAttributes(id);
2295
+ const hasAttention = useHasAttention(id);
2296
+ return /* @__PURE__ */ React6.createElement("div", {
2297
+ ref: containerRef,
2298
+ role: "grid",
2299
+ className: "relative flex grow overflow-hidden"
2300
+ }, /* @__PURE__ */ React6.createElement("div", {
2301
+ className: mx2("z-20 absolute inset-0 border border-gridLine pointer-events-none")
2302
+ }), /* @__PURE__ */ React6.createElement("div", {
2303
+ ref: scrollerRef,
2304
+ className: mx2("grow", hasAttention && "overflow-auto scrollbar-thin")
2305
+ }, /* @__PURE__ */ React6.createElement("div", {
2306
+ className: "relative select-none",
2307
+ style: {
2308
+ width,
2309
+ height
2310
+ },
2311
+ onClick: () => inputRef.current?.focus(),
2312
+ ...handlers
2313
+ }, scrollerRef.current && /* @__PURE__ */ React6.createElement(SelectionOverlay, {
2314
+ root: scrollerRef.current
2315
+ }), rowRange.map(({ row, top, height: height2 }) => {
2316
+ return columnRange.map(({ col, left, width: width2 }) => {
2317
+ const style = {
2318
+ position: "absolute",
2319
+ top,
2320
+ left,
2321
+ width: width2,
2322
+ height: height2
2323
+ };
2324
+ const cell = {
2325
+ row,
2326
+ col
2327
+ };
2328
+ const id2 = addressToA1Notation(cell);
2329
+ const idx = addressToIndex(model.sheet, cell);
2330
+ const active = posEquals(cursor, cell);
2331
+ if (active && editing) {
2332
+ const value = initialText.current ?? model.getCellText(cell) ?? "";
2333
+ const handleClose = (value2) => {
2334
+ initialText.current = void 0;
2335
+ quickEdit.current = false;
2336
+ if (value2 !== void 0) {
2337
+ model.setValue(cell, value2);
2338
+ const next = handleArrowNav({
2339
+ key: "ArrowDown",
2340
+ metaKey: false
2341
+ }, cursor, size);
2342
+ if (next) {
2343
+ setCursor(next);
2344
+ }
2345
+ }
2346
+ inputRef.current?.focus();
2347
+ setEditing(false);
2348
+ };
2349
+ const handleNav2 = (value2, { key }) => {
2350
+ initialText.current = void 0;
2351
+ model.setValue(cell, value2 ?? null);
2352
+ const next = handleArrowNav({
2353
+ key,
2354
+ metaKey: false
2355
+ }, cursor, size);
2356
+ if (next) {
2357
+ setCursor(next);
2358
+ }
2359
+ inputRef.current?.focus();
2360
+ setEditing(false);
2361
+ };
2362
+ return /* @__PURE__ */ React6.createElement(GridCellEditor, {
2363
+ key: idx,
2364
+ value,
2365
+ style,
2366
+ onNav: quickEdit.current ? handleNav2 : void 0,
2367
+ onClose: handleClose
2368
+ });
2369
+ }
2370
+ return /* @__PURE__ */ React6.createElement(SheetCell, {
2371
+ key: id2,
2372
+ id: id2,
2373
+ cell,
2374
+ active,
2375
+ style,
2376
+ onSelect: (cell2, edit) => {
2377
+ setEditing(edit);
2378
+ setCursor(cell2);
2379
+ }
2380
+ });
2381
+ });
2382
+ }))), /* @__PURE__ */ createPortal(/* @__PURE__ */ React6.createElement("input", {
2383
+ ref: inputRef,
2384
+ autoFocus: true,
2385
+ className: "absolute w-[1px] h-[1px] bg-transparent outline-none border-none caret-transparent",
2386
+ onKeyDown: handleKeyDown,
2387
+ ...attendableAttrs
2388
+ }), document.body));
2389
+ });
2390
+ var SelectionOverlay = ({ root }) => {
2391
+ const { range } = useSheetContext();
2392
+ if (!range) {
2393
+ return null;
2394
+ }
2395
+ const c1 = getCellElement(root, range.from);
2396
+ const c2 = range.to ? getCellElement(root, range.to) : c1;
2397
+ if (!c1 || !c2) {
2398
+ return null;
2399
+ }
2400
+ const b1 = getRelativeClientRect(root, c1);
2401
+ const b2 = getRelativeClientRect(root, c2);
2402
+ const bounds = getRectUnion(b1, b2);
2403
+ return /* @__PURE__ */ React6.createElement("div", {
2404
+ role: "none",
2405
+ style: bounds,
2406
+ className: "z-10 absolute pointer-events-none bg-gridSelectionOverlay border border-gridOverlay"
2407
+ });
2408
+ };
2409
+ var SheetCell = ({ id, cell, style, active, onSelect }) => {
2410
+ const { formatting, editing, setRange, decorations, model: { sheet } } = useSheetContext();
2411
+ const { value, classNames } = formatting.getFormatting(cell);
2412
+ const decorationsForCell = decorations.getDecorationsForCell(addressToIndex(sheet, cell)) ?? [];
2413
+ const decorationAddedClasses = useMemo4(() => decorationsForCell.flatMap((d) => d.classNames ?? []), [
2414
+ decorationsForCell
2415
+ ]);
2416
+ const decoratedContent = decorationsForCell.reduce((children, { decorate }) => {
2417
+ if (!decorate) {
2418
+ return children;
2419
+ }
2420
+ const DecoratorComponent = decorate;
2421
+ return /* @__PURE__ */ React6.createElement(DecoratorComponent, null, children);
2422
+ }, /* @__PURE__ */ React6.createElement("div", {
2423
+ role: "none",
2424
+ className: mx2("flex flex-grow bs-full is-full px-2 items-center truncate cursor-pointer", ...decorationAddedClasses)
2425
+ }, value));
2426
+ return /* @__PURE__ */ React6.createElement("div", {
2427
+ [`data-${CELL_DATA_KEY}`]: id,
2428
+ role: "cell",
2429
+ style,
2430
+ className: mx2("border border-gridLine cursor-pointer", fragments.cell, active && [
2431
+ "z-20",
2432
+ fragments.cellSelected
2433
+ ], classNames),
2434
+ onClick: () => {
2435
+ if (editing) {
2436
+ setRange?.({
2437
+ from: cell
2438
+ });
2439
+ } else {
2440
+ onSelect?.(cell, false);
2441
+ }
2442
+ },
2443
+ onDoubleClick: () => onSelect?.(cell, true)
2444
+ }, decoratedContent);
2445
+ };
2446
+ var GridCellEditor = ({ style, value, onNav, onClose }) => {
2447
+ const { model, range } = useSheetContext();
2448
+ const notifier = useRef();
2449
+ useEffect4(() => {
2450
+ if (range) {
2451
+ notifier.current?.(rangeToA1Notation(range));
2452
+ }
2453
+ }, [
2454
+ range
2455
+ ]);
2456
+ const extension = useMemo4(() => [
2457
+ editorKeys({
2458
+ onNav,
2459
+ onClose
2460
+ }),
2461
+ sheetExtension({
2462
+ functions: model.graph.getFunctions()
2463
+ }),
2464
+ rangeExtension((fn) => notifier.current = fn)
2465
+ ], [
2466
+ model
2467
+ ]);
2468
+ return /* @__PURE__ */ React6.createElement("div", {
2469
+ role: "cell",
2470
+ style,
2471
+ className: mx2("z-20 flex", fragments.cellSelected),
2472
+ onClick: (ev) => ev.stopPropagation()
2473
+ }, /* @__PURE__ */ React6.createElement(CellEditor, {
2474
+ autoFocus: true,
2475
+ value,
2476
+ extension
2477
+ }));
2478
+ };
2479
+ var SheetStatusBar = () => {
2480
+ const { model, cursor, range } = useSheetContext();
2481
+ let value;
2482
+ let isFormula = false;
2483
+ if (cursor) {
2484
+ value = model.getCellValue(cursor);
2485
+ if (typeof value === "string" && value.charAt(0) === "=") {
2486
+ value = model.graph.mapFunctionBindingFromId(model.mapFormulaIndicesToRefs(value));
2487
+ isFormula = true;
2488
+ } else if (value != null) {
2489
+ value = String(value);
2490
+ }
2491
+ }
2492
+ return /* @__PURE__ */ React6.createElement("div", {
2493
+ className: mx2("flex shrink-0 justify-between items-center px-4 py-1 text-sm border-x border-gridLine")
2494
+ }, /* @__PURE__ */ React6.createElement("div", {
2495
+ className: "flex gap-4 items-center"
2496
+ }, /* @__PURE__ */ React6.createElement("div", {
2497
+ className: "flex w-16 items-center font-mono"
2498
+ }, range && rangeToA1Notation(range) || cursor && addressToA1Notation(cursor)), /* @__PURE__ */ React6.createElement("div", {
2499
+ className: "flex gap-2 items-center"
2500
+ }, /* @__PURE__ */ React6.createElement(FunctionIcon, {
2501
+ className: mx2("text-greenText", isFormula ? "visible" : "invisible")
2502
+ }), /* @__PURE__ */ React6.createElement("span", {
2503
+ className: "font-mono"
2504
+ }, value))));
2505
+ };
2506
+ var SheetDebug = () => {
2507
+ const { model, cursor, range } = useSheetContext();
2508
+ const [, forceUpdate] = useState5({});
2509
+ useEffect4(() => {
2510
+ const accessor = createDocAccessor(model.sheet, []);
2511
+ const handleUpdate = () => forceUpdate({});
2512
+ accessor.handle.addListener("change", handleUpdate);
2513
+ handleUpdate();
2514
+ return () => {
2515
+ accessor.handle.removeListener("change", handleUpdate);
2516
+ };
2517
+ }, [
2518
+ model
2519
+ ]);
2520
+ return /* @__PURE__ */ React6.createElement("div", {
2521
+ className: mx2("z-20 absolute right-0 top-20 bottom-20 w-[30rem] overflow-auto scrollbar-thin", "border border-gridLine text-xs bg-neutral-50 dark:bg-black text-cyan-500 font-mono p-1 opacity-80")
2522
+ }, /* @__PURE__ */ React6.createElement("pre", {
2523
+ className: "whitespace-pre-wrap"
2524
+ }, JSON.stringify({
2525
+ cursor,
2526
+ range,
2527
+ cells: model.sheet.cells,
2528
+ rowMeta: model.sheet.rowMeta,
2529
+ columnMeta: model.sheet.columnMeta,
2530
+ formatting: model.sheet.formatting
2531
+ }, void 0, 2)));
2532
+ };
2533
+ var Sheet = {
2534
+ Root: SheetRoot,
2535
+ Main: SheetMain,
2536
+ Rows: SheetRows,
2537
+ Columns: SheetColumns,
2538
+ Grid: SheetGrid,
2539
+ Cell: SheetCell,
2540
+ StatusBar: SheetStatusBar,
2541
+ Debug: SheetDebug
2542
+ };
2543
+
2544
+ export {
2545
+ ComputeGraphContextProvider,
2546
+ createSheet,
2547
+ addressToIndex,
2548
+ compareIndexPositions,
2549
+ useSheetContext,
2550
+ Sheet,
2551
+ SheetContainer
2552
+ };
2553
+ //# sourceMappingURL=chunk-7HVSOTGA.mjs.map