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

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