@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,1199 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import {
6
- type Active,
7
- DndContext,
8
- type DragEndEvent,
9
- DragOverlay,
10
- type DragStartEvent,
11
- KeyboardSensor,
12
- type Modifier,
13
- MouseSensor,
14
- type PointerActivationConstraint,
15
- TouchSensor,
16
- useDraggable,
17
- useDroppable,
18
- useSensor,
19
- useSensors,
20
- } from '@dnd-kit/core';
21
- import { restrictToHorizontalAxis, restrictToVerticalAxis } from '@dnd-kit/modifiers';
22
- import { getEventCoordinates, useCombinedRefs } from '@dnd-kit/utilities';
23
- import { Function as FunctionIcon } from '@phosphor-icons/react';
24
- import { Resizable, type ResizeCallback, type ResizeStartCallback } from 're-resizable';
25
- import React, {
26
- type CSSProperties,
27
- type DOMAttributes,
28
- type PropsWithChildren,
29
- forwardRef,
30
- useEffect,
31
- useImperativeHandle,
32
- useMemo,
33
- useRef,
34
- useState,
35
- } from 'react';
36
- import { createPortal } from 'react-dom';
37
- import { useResizeDetector } from 'react-resize-detector';
38
-
39
- import { debounce } from '@dxos/async';
40
- import { fullyQualifiedId, createDocAccessor } from '@dxos/client/echo';
41
- import { log } from '@dxos/log';
42
- import { type ThemedClassName } from '@dxos/react-ui';
43
- import { createAttendableAttributes, useHasAttention } from '@dxos/react-ui-attention';
44
- import { mx } from '@dxos/react-ui-theme';
45
-
46
- import {
47
- type GridLayoutProps,
48
- type SizeMap,
49
- CELL_DATA_KEY,
50
- axisHeight,
51
- axisWidth,
52
- defaultHeight,
53
- defaultWidth,
54
- maxWidth,
55
- maxHeight,
56
- minWidth,
57
- minHeight,
58
- getCellElement,
59
- useGridLayout,
60
- } from './grid';
61
- import { type GridSize, handleArrowNav, handleNav, useRangeSelect } from './nav';
62
- import { type SheetContextProps, SheetContextProvider, useSheetContext } from './sheet-context';
63
- import { useThreads } from './threads';
64
- import { getRectUnion, getRelativeClientRect, scrollIntoView } from './util';
65
- import {
66
- type CellIndex,
67
- type CellAddress,
68
- addressToA1Notation,
69
- columnLetter,
70
- posEquals,
71
- rangeToA1Notation,
72
- addressToIndex,
73
- addressFromIndex,
74
- } from '../../defs';
75
- import {
76
- CellEditor,
77
- type CellRangeNotifier,
78
- type EditorKeysProps,
79
- editorKeys,
80
- rangeExtension,
81
- sheetExtension,
82
- } from '../CellEditor';
83
-
84
- // TODO(burdon): Virtualization bug.
85
- // TODO(burdon): Toolbar styles and formatting.
86
- // TODO(burdon): Insert/delete rows/columns (menu).
87
- // TODO(burdon): Scroll to position if off screen.
88
- // TODO(burdon): Don't render until sizes were updated (otherwise, flickers).
89
-
90
- // TODO(burdon): Model multiple sheets (e.g., documents). And cross sheet references.
91
- // TODO(burdon): Factor out react-ui-sheet.
92
- // TODO(burdon): Comments (josiah).
93
- // TODO(burdon): Realtime long text.
94
- // TODO(burdon): Search.
95
-
96
- // TODO(burdon): Virtualization:
97
- // https://github.com/TanStack/virtual/blob/main/examples/react/dynamic/src/main.tsx#L171
98
- // https://tanstack.com/virtual/v3/docs/framework/react/examples/variable
99
- // https://canvas-grid-demo.vercel.app
100
- // https://sheet.brianhung.me
101
- // https://github.com/BrianHung
102
- // https://daybrush.com/moveable
103
-
104
- /**
105
- * Features:
106
- * - Move rows/columns.
107
- * - Insert/delete rows/columns.
108
- * - Copy/paste.
109
- * - Undo/redo.
110
- * - Comments.
111
- * - Real time collaborative editing of large text cells.
112
- * - Select range.
113
- * - Format cells.
114
- * - Formulae.
115
- * - Update formula ranges by selection.
116
- */
117
-
118
- const fragments = {
119
- axis: 'bg-axisSurface text-axisText text-xs select-none',
120
- axisSelected: 'bg-attention text-baseText',
121
- cell: 'bg-gridCell',
122
- cellSelected: 'bg-gridCellSelected text-baseText border !border-accentSurface',
123
- };
124
-
125
- //
126
- // Root
127
- //
128
-
129
- type SheetRootProps = SheetContextProps;
130
-
131
- const SheetRoot = ({ children, ...props }: PropsWithChildren<SheetContextProps>) => {
132
- return <SheetContextProvider {...props}>{children}</SheetContextProvider>;
133
- };
134
-
135
- //
136
- // Main
137
- //
138
-
139
- type SheetMainProps = ThemedClassName<Partial<GridSize>>;
140
-
141
- const SheetMain = forwardRef<HTMLDivElement, SheetMainProps>(({ classNames, numRows, numCols }, forwardRef) => {
142
- const { model, cursor, setCursor, setRange, setEditing } = useSheetContext();
143
-
144
- // Scrolling.
145
- const { rowsRef, columnsRef, contentRef } = useScrollHandlers();
146
-
147
- // Threads.
148
- // TODO(Zan): Move this to an extension once we have an extension model.
149
- useThreads();
150
-
151
- //
152
- // Order of Row/columns.
153
- //
154
- const [rows, setRows] = useState([...model.sheet.rows]);
155
- const [columns, setColumns] = useState([...model.sheet.columns]);
156
- useEffect(() => {
157
- const rowsAccessor = createDocAccessor(model.sheet, ['rows']);
158
- const columnsAccessor = createDocAccessor(model.sheet, ['columns']);
159
- const handleUpdate = debounce(() => {
160
- setRows([...model.sheet.rows]);
161
- setColumns([...model.sheet.columns]);
162
- }, 100);
163
-
164
- rowsAccessor.handle.addListener('change', handleUpdate);
165
- columnsAccessor.handle.addListener('change', handleUpdate);
166
- handleUpdate();
167
- return () => {
168
- rowsAccessor.handle.removeListener('change', handleUpdate);
169
- columnsAccessor.handle.removeListener('change', handleUpdate);
170
- };
171
- }, [model]);
172
-
173
- // Refresh the model.
174
- // TODO(burdon): Breaks undo.
175
- useEffect(() => {
176
- model.reset();
177
- }, [rows, columns]);
178
-
179
- const handleMoveRows: SheetRowsProps['onMove'] = (from, to, num = 1) => {
180
- const cursorIdx = cursor ? addressToIndex(model.sheet, cursor) : undefined;
181
- const [rows] = model.sheet.rows.splice(from, num);
182
- model.sheet.rows.splice(to, 0, rows);
183
- if (cursorIdx) {
184
- setCursor(addressFromIndex(model.sheet, cursorIdx));
185
- }
186
- setRows([...model.sheet.rows]);
187
- };
188
-
189
- const handleMoveColumns: SheetColumnsProps['onMove'] = (from, to, num = 1) => {
190
- const cursorIdx = cursor ? addressToIndex(model.sheet, cursor) : undefined;
191
- const columns = model.sheet.columns.splice(from, num);
192
- model.sheet.columns.splice(to, 0, ...columns);
193
- if (cursorIdx) {
194
- setCursor(addressFromIndex(model.sheet, cursorIdx));
195
- }
196
- setColumns([...model.sheet.columns]);
197
- };
198
-
199
- //
200
- // Row/column sizes.
201
- //
202
- const [rowSizes, setRowSizes] = useState<SizeMap>();
203
- const [columnSizes, setColumnSizes] = useState<SizeMap>();
204
- useEffect(() => {
205
- const rowAccessor = createDocAccessor(model.sheet, ['rowMeta']);
206
- const columnAccessor = createDocAccessor(model.sheet, ['columnMeta']);
207
- const handleUpdate = debounce(() => {
208
- const mapSizes = (values: [string, { size?: number | undefined }][]) =>
209
- values.reduce<SizeMap>((map, [idx, meta]) => {
210
- if (meta.size) {
211
- map[idx] = meta.size;
212
- }
213
- return map;
214
- }, {});
215
-
216
- setRowSizes(mapSizes(Object.entries(model.sheet.rowMeta)));
217
- setColumnSizes(mapSizes(Object.entries(model.sheet.columnMeta)));
218
- }, 100);
219
-
220
- rowAccessor.handle.addListener('change', handleUpdate);
221
- columnAccessor.handle.addListener('change', handleUpdate);
222
- handleUpdate();
223
- return () => {
224
- rowAccessor.handle.removeListener('change', handleUpdate);
225
- columnAccessor.handle.removeListener('change', handleUpdate);
226
- };
227
- }, [model]);
228
-
229
- const handleResizeRow: SheetRowsProps['onResize'] = (idx, size, save) => {
230
- if (save) {
231
- model.sheet.rowMeta[idx] ??= {};
232
- model.sheet.rowMeta[idx].size = size;
233
- } else {
234
- setRowSizes((sizes) => ({ ...sizes, [idx]: size }));
235
- }
236
- };
237
-
238
- const handleResizeColumn: SheetColumnsProps['onResize'] = (idx, size, save) => {
239
- if (save) {
240
- model.sheet.columnMeta[idx] ??= {};
241
- model.sheet.columnMeta[idx].size = size;
242
- } else {
243
- setColumnSizes((sizes) => ({ ...sizes, [idx]: size }));
244
- }
245
- };
246
-
247
- return (
248
- <div
249
- role='none'
250
- className={mx(
251
- 'grid grid-cols-[calc(var(--rail-size)-2px)_1fr] grid-rows-[32px_1fr_32px] bs-full is-full overflow-hidden',
252
- classNames,
253
- )}
254
- >
255
- <GridCorner
256
- onClick={() => {
257
- setCursor(undefined);
258
- setRange(undefined);
259
- setEditing(false);
260
- }}
261
- />
262
- <SheetColumns
263
- ref={columnsRef}
264
- columns={columns}
265
- sizes={columnSizes}
266
- selected={cursor?.col}
267
- onSelect={(col) => setCursor(cursor?.col === col ? undefined : { row: -1, col })}
268
- onResize={handleResizeColumn}
269
- onMove={handleMoveColumns}
270
- />
271
-
272
- <SheetRows
273
- ref={rowsRef}
274
- rows={rows}
275
- sizes={rowSizes}
276
- selected={cursor?.row}
277
- onSelect={(row) => setCursor(cursor?.row === row ? undefined : { row, col: -1 })}
278
- onResize={handleResizeRow}
279
- onMove={handleMoveRows}
280
- />
281
- <SheetGrid
282
- ref={contentRef}
283
- size={{ numRows: numRows ?? rows.length, numCols: numCols ?? columns.length }}
284
- rows={rows}
285
- columns={columns}
286
- rowSizes={rowSizes}
287
- columnSizes={columnSizes}
288
- />
289
-
290
- <GridCorner />
291
- <SheetStatusBar />
292
- </div>
293
- );
294
- });
295
-
296
- /**
297
- * Coordinate scrolling across components.
298
- */
299
- const useScrollHandlers = () => {
300
- const rowsRef = useRef<HTMLDivElement>(null);
301
- const columnsRef = useRef<HTMLDivElement>(null);
302
- const contentRef = useRef<HTMLDivElement>(null);
303
-
304
- useEffect(() => {
305
- const handleRowsScroll = (ev: Event) => {
306
- const { scrollTop } = ev.target as HTMLDivElement;
307
- if (!rowsRef.current!.dataset.locked) {
308
- contentRef.current!.scrollTop = scrollTop;
309
- }
310
- };
311
-
312
- const handleColumnsScroll = (ev: Event) => {
313
- const { scrollLeft } = ev.target as HTMLDivElement;
314
- if (!columnsRef.current!.dataset.locked) {
315
- contentRef.current!.scrollLeft = scrollLeft;
316
- }
317
- };
318
-
319
- const handleContentScroll = (ev: Event) => {
320
- const { scrollTop, scrollLeft } = ev.target as HTMLDivElement;
321
- rowsRef.current!.scrollTop = scrollTop;
322
- columnsRef.current!.scrollLeft = scrollLeft;
323
- };
324
-
325
- const rows = rowsRef.current!;
326
- const columns = columnsRef.current!;
327
- const content = contentRef.current!;
328
-
329
- rows.addEventListener('scroll', handleRowsScroll);
330
- columns.addEventListener('scroll', handleColumnsScroll);
331
- content.addEventListener('scroll', handleContentScroll);
332
- return () => {
333
- rows.removeEventListener('scroll', handleRowsScroll);
334
- columns.removeEventListener('scroll', handleColumnsScroll);
335
- content.removeEventListener('scroll', handleContentScroll);
336
- };
337
- }, []);
338
-
339
- return { rowsRef, columnsRef, contentRef };
340
- };
341
-
342
- //
343
- // Row/Column
344
- //
345
-
346
- const GridCorner = (props: { className?: string } & Pick<DOMAttributes<HTMLDivElement>, 'onClick'>) => {
347
- return <div className={fragments.axis} {...props} />;
348
- };
349
-
350
- const MovingOverlay = ({ label }: { label: string }) => {
351
- return (
352
- <div className='flex w-full h-full justify-center items-center text-sm p-1 bg-gridOverlay cursor-pointer'>
353
- {label}
354
- </div>
355
- );
356
- };
357
-
358
- // https://docs.dndkit.com/api-documentation/sensors/pointer#activation-constraints
359
- const mouseConstraints: PointerActivationConstraint = { distance: 10 };
360
- const touchConstraints: PointerActivationConstraint = { delay: 250, tolerance: 5 };
361
-
362
- type ResizeProps = {
363
- sizes?: SizeMap;
364
- onResize?: (idx: CellIndex, size: number, save?: boolean) => void;
365
- };
366
-
367
- type MoveProps = {
368
- onMove?: (from: number, to: number) => void;
369
- };
370
-
371
- type RowColumnSelection = {
372
- selected?: number;
373
- onSelect?: (selected: number) => void;
374
- };
375
-
376
- type RowColumnProps = {
377
- idx: CellIndex;
378
- index: number;
379
- label: string;
380
- size: number;
381
- resize: boolean;
382
- selected: boolean;
383
- } & Pick<ResizeProps, 'onResize'> &
384
- Pick<RowColumnSelection, 'onSelect'>;
385
-
386
- //
387
- // Rows
388
- //
389
-
390
- type SheetRowsProps = { rows: CellIndex[] } & RowColumnSelection & ResizeProps & MoveProps;
391
-
392
- const SheetRows = forwardRef<HTMLDivElement, SheetRowsProps>(
393
- ({ rows, sizes, selected, onSelect, onResize, onMove }, forwardRef) => {
394
- const mouseSensor = useSensor(MouseSensor, { activationConstraint: mouseConstraints });
395
- const touchSensor = useSensor(TouchSensor, { activationConstraint: touchConstraints });
396
- const keyboardSensor = useSensor(KeyboardSensor, {});
397
- const sensors = useSensors(mouseSensor, touchSensor, keyboardSensor);
398
-
399
- const [active, setActive] = useState<Active | null>(null);
400
- const handleDragStart = ({ active }: DragStartEvent) => {
401
- setActive(active);
402
- };
403
-
404
- const handleDragEnd = ({ over, active }: DragEndEvent) => {
405
- if (over && over.id !== active.id) {
406
- setActive(null);
407
- onMove?.(active.data.current!.index, over.data.current!.index);
408
- }
409
- };
410
-
411
- const snapToCenter: Modifier = ({ activatorEvent, draggingNodeRect, transform }) => {
412
- if (draggingNodeRect && activatorEvent) {
413
- const activatorCoordinates = getEventCoordinates(activatorEvent);
414
- if (!activatorCoordinates) {
415
- return transform;
416
- }
417
-
418
- const offset = activatorCoordinates.y - draggingNodeRect.top;
419
- return {
420
- ...transform,
421
- y: transform.y + offset - draggingNodeRect.height / 2,
422
- };
423
- }
424
-
425
- return transform;
426
- };
427
-
428
- return (
429
- <div className='relative flex grow overflow-hidden'>
430
- {/* Fixed border. */}
431
- <div
432
- className={mx('z-20 absolute inset-0 border-y border-gridLine pointer-events-none')}
433
- style={{ width: axisWidth }}
434
- />
435
-
436
- {/* Scrollbar. */}
437
- <div ref={forwardRef} role='rowheader' className='grow overflow-y-auto scrollbar-none'>
438
- <DndContext
439
- sensors={sensors}
440
- modifiers={[restrictToVerticalAxis, snapToCenter]}
441
- onDragStart={handleDragStart}
442
- onDragEnd={handleDragEnd}
443
- >
444
- <div className='flex flex-col' style={{ width: axisWidth }}>
445
- {rows.map((idx, index) => (
446
- <GridRowCell
447
- key={idx}
448
- idx={idx}
449
- index={index}
450
- label={String(index + 1)}
451
- size={sizes?.[idx] ?? defaultHeight}
452
- resize={index < rows.length - 1}
453
- selected={selected === index}
454
- onResize={onResize}
455
- onSelect={onSelect}
456
- />
457
- ))}
458
- </div>
459
-
460
- {createPortal(
461
- <DragOverlay>{active && <MovingOverlay label={String(active.data.current!.index + 1)} />}</DragOverlay>,
462
- document.body,
463
- )}
464
- </DndContext>
465
- </div>
466
- </div>
467
- );
468
- },
469
- );
470
-
471
- const GridRowCell = ({ idx, index, label, size, resize, selected, onSelect, onResize }: RowColumnProps) => {
472
- const { setNodeRef: setDroppableNodeRef } = useDroppable({ id: idx, data: { index } });
473
- const {
474
- setNodeRef: setDraggableNodeRef,
475
- attributes,
476
- listeners,
477
- isDragging,
478
- over,
479
- } = useDraggable({ id: idx, data: { index } });
480
- const setNodeRef = useCombinedRefs(setDroppableNodeRef, setDraggableNodeRef);
481
- const [initialSize, setInitialSize] = useState(size);
482
- const [resizing, setResizing] = useState(false);
483
-
484
- // Lock scroll container while resizing (fixes scroll bug).
485
- // https://github.com/bokuweb/re-resizable/issues/727
486
- const scrollHandler = useRef<any>();
487
- const handleResizeStart: ResizeStartCallback = (_ev, _dir, elementRef) => {
488
- const scrollContainer = elementRef.closest<HTMLDivElement>('[role="rowheader"]')!;
489
- const scrollTop = scrollContainer.scrollTop;
490
- scrollHandler.current = (ev: Event) => ((ev.target as HTMLElement).scrollTop = scrollTop);
491
- scrollContainer.addEventListener('scroll', scrollHandler.current);
492
- scrollContainer.dataset.locked = 'true';
493
- setResizing(true);
494
- };
495
-
496
- const handleResize: ResizeCallback = (_ev, _dir, _elementRef, { height }) => {
497
- onResize?.(idx, initialSize + height);
498
- };
499
-
500
- const handleResizeStop: ResizeCallback = (_ev, _dir, elementRef, { height }) => {
501
- const scrollContainer = elementRef.closest<HTMLDivElement>('[role="rowheader"]')!;
502
- scrollContainer.removeEventListener('scroll', scrollHandler.current!);
503
- delete scrollContainer.dataset.locked;
504
- scrollHandler.current = undefined;
505
- setInitialSize(initialSize + height);
506
- onResize?.(idx, initialSize + height, true);
507
- setResizing(false);
508
- };
509
-
510
- // Row.
511
- return (
512
- <Resizable
513
- enable={{ bottom: resize }}
514
- size={{ height: size - 1 }}
515
- minHeight={minHeight - 1}
516
- maxHeight={maxHeight}
517
- onResizeStart={handleResizeStart}
518
- onResize={handleResize}
519
- onResizeStop={handleResizeStop}
520
- >
521
- <div
522
- ref={setNodeRef}
523
- {...attributes}
524
- {...listeners}
525
- className={mx(
526
- 'flex h-full items-center justify-center cursor-pointer',
527
- 'border-t border-gridLine focus-visible:outline-none',
528
- fragments.axis,
529
- selected && fragments.axisSelected,
530
- isDragging && fragments.axisSelected,
531
- )}
532
- onClick={() => onSelect?.(index)}
533
- >
534
- <span className='flex w-full justify-center'>{label}</span>
535
-
536
- {/* Drop indicator. */}
537
- {over?.id === idx && !isDragging && (
538
- <div className='z-20 absolute top-0 w-full min-h-[4px] border-b-4 border-accentSurface' />
539
- )}
540
-
541
- {/* Resize indicator. */}
542
- {resizing && <div className='z-20 absolute bottom-0 w-full min-h-[4px] border-b-4 border-accentSurface' />}
543
- </div>
544
- </Resizable>
545
- );
546
- };
547
-
548
- //
549
- // Columns
550
- //
551
-
552
- type SheetColumnsProps = { columns: CellIndex[] } & RowColumnSelection & ResizeProps & MoveProps;
553
-
554
- const SheetColumns = forwardRef<HTMLDivElement, SheetColumnsProps>(
555
- ({ columns, sizes, selected, onSelect, onResize, onMove }, forwardRef) => {
556
- const mouseSensor = useSensor(MouseSensor, { activationConstraint: mouseConstraints });
557
- const touchSensor = useSensor(TouchSensor, { activationConstraint: touchConstraints });
558
- const keyboardSensor = useSensor(KeyboardSensor, {});
559
- const sensors = useSensors(mouseSensor, touchSensor, keyboardSensor);
560
-
561
- const [active, setActive] = useState<Active | null>(null);
562
- const handleDragStart = ({ active }: DragStartEvent) => {
563
- setActive(active);
564
- };
565
-
566
- const handleDragEnd = ({ active, over }: DragEndEvent) => {
567
- if (over && over.id !== active.id) {
568
- setActive(null);
569
- onMove?.(active.data.current!.index, over.data.current!.index);
570
- }
571
- };
572
-
573
- const snapToCenter: Modifier = ({ activatorEvent, draggingNodeRect, transform }) => {
574
- if (draggingNodeRect && activatorEvent) {
575
- const activatorCoordinates = getEventCoordinates(activatorEvent);
576
- if (!activatorCoordinates) {
577
- return transform;
578
- }
579
-
580
- const offset = activatorCoordinates.x - draggingNodeRect.left;
581
- return {
582
- ...transform,
583
- x: transform.x + offset - draggingNodeRect.width / 2,
584
- };
585
- }
586
-
587
- return transform;
588
- };
589
-
590
- return (
591
- <div className='relative flex grow overflow-hidden'>
592
- {/* Fixed border. */}
593
- <div
594
- className={mx('z-20 absolute inset-0 border-x border-gridLine pointer-events-none')}
595
- style={{ height: axisHeight }}
596
- />
597
-
598
- {/* Scrollbar. */}
599
- <div ref={forwardRef} role='columnheader' className='grow overflow-x-auto scrollbar-none'>
600
- <DndContext
601
- autoScroll={{ enabled: true }}
602
- sensors={sensors}
603
- modifiers={[restrictToHorizontalAxis, snapToCenter]}
604
- onDragStart={handleDragStart}
605
- onDragEnd={handleDragEnd}
606
- >
607
- <div className='flex h-full' style={{ height: axisHeight }}>
608
- {columns.map((idx, index) => (
609
- <GridColumnCell
610
- key={idx}
611
- idx={idx}
612
- index={index}
613
- label={columnLetter(index)}
614
- size={sizes?.[idx] ?? defaultWidth}
615
- resize={index < columns.length - 1}
616
- selected={selected === index}
617
- onResize={onResize}
618
- onSelect={onSelect}
619
- />
620
- ))}
621
- </div>
622
-
623
- {createPortal(
624
- <DragOverlay>{active && <MovingOverlay label={columnLetter(active.data.current!.index)} />}</DragOverlay>,
625
- document.body,
626
- )}
627
- </DndContext>
628
- </div>
629
- </div>
630
- );
631
- },
632
- );
633
-
634
- const GridColumnCell = ({ idx, index, label, size, resize, selected, onSelect, onResize }: RowColumnProps) => {
635
- const { setNodeRef: setDroppableNodeRef } = useDroppable({ id: idx, data: { index } });
636
- const {
637
- setNodeRef: setDraggableNodeRef,
638
- attributes,
639
- listeners,
640
- over,
641
- isDragging,
642
- } = useDraggable({ id: idx, data: { index } });
643
- const setNodeRef = useCombinedRefs(setDroppableNodeRef, setDraggableNodeRef);
644
- const [initialSize, setInitialSize] = useState(size);
645
- const [resizing, setResizing] = useState(false);
646
-
647
- // Lock scroll container while resizing (fixes scroll bug).
648
- // https://github.com/bokuweb/re-resizable/issues/727
649
- const scrollHandler = useRef<any>();
650
- const handleResizeStart: ResizeStartCallback = (_ev, _dir, elementRef) => {
651
- const scrollContainer = elementRef.closest<HTMLDivElement>('[role="columnheader"]')!;
652
- const scrollLeft = scrollContainer.scrollLeft;
653
- scrollHandler.current = (ev: Event) => ((ev.target as HTMLElement).scrollLeft = scrollLeft);
654
- scrollContainer.addEventListener('scroll', scrollHandler.current);
655
- scrollContainer.dataset.locked = 'true';
656
- setResizing(true);
657
- };
658
-
659
- const handleResize: ResizeCallback = (_ev, _dir, _elementRef, { width }) => {
660
- onResize?.(idx, initialSize + width);
661
- };
662
-
663
- const handleResizeStop: ResizeCallback = (_ev, _dir, elementRef, { width }) => {
664
- const scrollContainer = elementRef.closest<HTMLDivElement>('[role="columnheader"]')!;
665
- scrollContainer.removeEventListener('scroll', scrollHandler.current!);
666
- delete scrollContainer.dataset.locked;
667
- scrollHandler.current = undefined;
668
- setInitialSize(initialSize + width);
669
- onResize?.(idx, initialSize + width, true);
670
- setResizing(false);
671
- };
672
-
673
- // Column.
674
- return (
675
- <Resizable
676
- enable={{ right: resize }}
677
- size={{ width: size - 1 }}
678
- minWidth={minWidth - 1}
679
- maxWidth={maxWidth}
680
- onResizeStart={handleResizeStart}
681
- onResize={handleResize}
682
- onResizeStop={handleResizeStop}
683
- >
684
- <div
685
- ref={setNodeRef}
686
- {...attributes}
687
- {...listeners}
688
- className={mx(
689
- 'flex h-full items-center justify-center cursor-pointer',
690
- 'border-l border-gridLine focus-visible:outline-none',
691
- fragments.axis,
692
- selected && fragments.axisSelected,
693
- isDragging && fragments.axisSelected,
694
- )}
695
- onClick={() => onSelect?.(index)}
696
- >
697
- <span className='flex w-full justify-center'>{label}</span>
698
-
699
- {/* Drop indicator. */}
700
- {over?.id === idx && !isDragging && (
701
- <div className='z-20 absolute left-0 h-full min-w-[4px] border-l-4 border-accentSurface' />
702
- )}
703
-
704
- {/* Resize indicator. */}
705
- {resizing && <div className='z-20 absolute right-0 h-full min-h-[4px] border-l-4 border-accentSurface' />}
706
- </div>
707
- </Resizable>
708
- );
709
- };
710
-
711
- //
712
- // Content
713
- //
714
-
715
- type SheetGridProps = GridLayoutProps & {
716
- size: GridSize;
717
- };
718
-
719
- const SheetGrid = forwardRef<HTMLDivElement, SheetGridProps>(
720
- ({ size, rows, columns, rowSizes, columnSizes }, forwardRef) => {
721
- const {
722
- ref: containerRef,
723
- width: containerWidth = 0,
724
- height: containerHeight = 0,
725
- } = useResizeDetector({ refreshRate: 200 });
726
- const scrollerRef = useRef<HTMLDivElement>(null);
727
- useImperativeHandle(forwardRef, () => scrollerRef.current!);
728
-
729
- const { model, cursor, range, editing, setCursor, setRange, setEditing, onInfo } = useSheetContext();
730
- const initialText = useRef<string>();
731
- const quickEdit = useRef(false);
732
-
733
- // Listen for async calculation updates.
734
- const [, forceUpdate] = useState({});
735
- useEffect(() => {
736
- const unsubscribe = model.update.on(() => {
737
- log('updated', { id: model.id });
738
- forceUpdate({});
739
- });
740
-
741
- return () => {
742
- unsubscribe();
743
- };
744
- }, [model]);
745
-
746
- //
747
- // Event handling.
748
- //
749
-
750
- const inputRef = useRef<HTMLInputElement>(null);
751
- const handleKeyDown: DOMAttributes<HTMLInputElement>['onKeyDown'] = (ev) => {
752
- // Cut-and-paste.
753
- const isMacOS = /Mac|iPhone|iPod|iPad/.test(navigator.userAgent);
754
- if (cursor && ((isMacOS && ev.metaKey) || ev.ctrlKey)) {
755
- switch (ev.key) {
756
- case 'x': {
757
- model.cut(range ?? { from: cursor });
758
- return;
759
- }
760
- case 'c': {
761
- model.copy(range ?? { from: cursor });
762
- return;
763
- }
764
- case 'v': {
765
- model.paste(cursor);
766
- return;
767
- }
768
- case 'z': {
769
- if (ev.shiftKey) {
770
- model.redo();
771
- } else {
772
- model.undo();
773
- }
774
- return;
775
- }
776
- }
777
- }
778
-
779
- switch (ev.key) {
780
- case 'ArrowUp':
781
- case 'ArrowDown':
782
- case 'ArrowLeft':
783
- case 'ArrowRight':
784
- case 'Home':
785
- case 'End': {
786
- const next = handleNav(ev, cursor, range, size);
787
- setRange(next.range);
788
- if (next.cursor) {
789
- setCursor(next.cursor);
790
- const element = getCellElement(scrollerRef.current!, next.cursor);
791
- if (element) {
792
- scrollIntoView(scrollerRef.current!, element);
793
- }
794
- }
795
- break;
796
- }
797
-
798
- case 'Backspace': {
799
- if (cursor) {
800
- if (range) {
801
- model.clear(range);
802
- } else {
803
- model.setValue(cursor, null);
804
- }
805
- }
806
- break;
807
- }
808
-
809
- case 'Escape': {
810
- setRange(undefined);
811
- break;
812
- }
813
-
814
- case 'Enter': {
815
- ev.stopPropagation();
816
- if (cursor) {
817
- setEditing(true);
818
- }
819
- break;
820
- }
821
-
822
- case '?': {
823
- onInfo?.();
824
- break;
825
- }
826
-
827
- default: {
828
- if (ev.key.length === 1) {
829
- initialText.current = ev.key;
830
- quickEdit.current = true;
831
- setEditing(true);
832
- }
833
- }
834
- }
835
- };
836
-
837
- // Mouse handlers for selection.
838
- const { handlers } = useRangeSelect((event, range) => {
839
- switch (event) {
840
- case 'start': {
841
- // if (!editing) {
842
- // setCursor(range?.from);
843
- // }
844
- setRange(undefined);
845
- break;
846
- }
847
-
848
- default: {
849
- setRange(range);
850
- }
851
- }
852
- });
853
-
854
- // Calculate visible grid.
855
- const { width, height, rowRange, columnRange } = useGridLayout({
856
- scroller: scrollerRef.current,
857
- size: { width: containerWidth, height: containerHeight },
858
- rows,
859
- columns,
860
- rowSizes,
861
- columnSizes,
862
- });
863
-
864
- // TODO(burdon): Prevent scroll if not attended.
865
- const id = fullyQualifiedId(model.sheet);
866
- const attendableAttrs = createAttendableAttributes(id);
867
- const hasAttention = useHasAttention(id);
868
-
869
- return (
870
- <div ref={containerRef} role='grid' className='relative flex grow overflow-hidden'>
871
- {/* Fixed border. */}
872
- <div className={mx('z-20 absolute inset-0 border border-gridLine pointer-events-none')} />
873
-
874
- {/* Grid scroll container. */}
875
- <div ref={scrollerRef} className={mx('grow', hasAttention && 'overflow-auto scrollbar-thin')}>
876
- {/* Scroll content. */}
877
- <div
878
- className='relative select-none'
879
- style={{ width, height }}
880
- onClick={() => inputRef.current?.focus()}
881
- {...handlers}
882
- >
883
- {/* Selection. */}
884
- {scrollerRef.current && <SelectionOverlay root={scrollerRef.current} />}
885
-
886
- {/* Grid cells. */}
887
- {rowRange.map(({ row, top, height }) => {
888
- return columnRange.map(({ col, left, width }) => {
889
- const style: CSSProperties = { position: 'absolute', top, left, width, height };
890
- const cell: CellAddress = { row, col };
891
- const id = addressToA1Notation(cell);
892
- const idx = addressToIndex(model.sheet, cell);
893
- const active = posEquals(cursor, cell);
894
- if (active && editing) {
895
- const value = initialText.current ?? model.getCellText(cell) ?? '';
896
-
897
- // TODO(burdon): Validate formula before closing: hf.validateFormula();
898
- const handleClose: GridCellEditorProps['onClose'] = (value) => {
899
- initialText.current = undefined;
900
- quickEdit.current = false;
901
- if (value !== undefined) {
902
- model.setValue(cell, value);
903
- // Auto-advance to next cell.
904
- const next = handleArrowNav({ key: 'ArrowDown', metaKey: false }, cursor, size);
905
- if (next) {
906
- setCursor(next);
907
- }
908
- }
909
- inputRef.current?.focus();
910
- setEditing(false);
911
- };
912
-
913
- // Quick entry mode: i.e., typing to enter cell.
914
- const handleNav: GridCellEditorProps['onNav'] = (value, { key }) => {
915
- initialText.current = undefined;
916
- model.setValue(cell, value ?? null);
917
- const next = handleArrowNav({ key, metaKey: false }, cursor, size);
918
- if (next) {
919
- setCursor(next);
920
- }
921
- inputRef.current?.focus();
922
- setEditing(false);
923
- };
924
-
925
- return (
926
- <GridCellEditor
927
- key={idx}
928
- value={value}
929
- style={style}
930
- onNav={quickEdit.current ? handleNav : undefined}
931
- onClose={handleClose}
932
- />
933
- );
934
- }
935
-
936
- return (
937
- <SheetCell
938
- key={id}
939
- id={id}
940
- cell={cell}
941
- active={active}
942
- style={style}
943
- onSelect={(cell, edit) => {
944
- setEditing(edit);
945
- setCursor(cell);
946
- }}
947
- />
948
- );
949
- });
950
- })}
951
- </div>
952
- </div>
953
-
954
- {/* Hidden input for key navigation. */}
955
- {createPortal(
956
- <input
957
- ref={inputRef}
958
- autoFocus
959
- className='absolute w-[1px] h-[1px] bg-transparent outline-none border-none caret-transparent'
960
- onKeyDown={handleKeyDown}
961
- {...attendableAttrs}
962
- />,
963
- document.body,
964
- )}
965
- </div>
966
- );
967
- },
968
- );
969
-
970
- //
971
- // Selection
972
- //
973
-
974
- const SelectionOverlay = ({ root }: { root: HTMLDivElement }) => {
975
- const { range } = useSheetContext();
976
- if (!range) {
977
- return null;
978
- }
979
-
980
- const c1 = getCellElement(root, range.from);
981
- const c2 = range.to ? getCellElement(root, range.to)! : c1;
982
- if (!c1 || !c2) {
983
- return null;
984
- }
985
-
986
- // TODO(burdon): Instead of measuring cells, get from grid layout?
987
- const b1 = getRelativeClientRect(root, c1);
988
- const b2 = getRelativeClientRect(root, c2);
989
- const bounds = getRectUnion(b1, b2);
990
-
991
- return (
992
- <div
993
- role='none'
994
- style={bounds}
995
- className='z-10 absolute pointer-events-none bg-gridSelectionOverlay border border-gridOverlay'
996
- />
997
- );
998
- };
999
-
1000
- //
1001
- // Cell
1002
- //
1003
-
1004
- type SheetCellProps = {
1005
- id: string; // TODO(burdon): Should this be the index?
1006
- cell: CellAddress;
1007
- style: CSSProperties;
1008
- active: boolean;
1009
- onSelect?: (selected: CellAddress, edit: boolean) => void;
1010
- };
1011
-
1012
- const SheetCell = ({ id, cell, style, active, onSelect }: SheetCellProps) => {
1013
- const {
1014
- formatting,
1015
- editing,
1016
- setRange,
1017
- decorations,
1018
- model: { sheet },
1019
- } = useSheetContext();
1020
- const { value, classNames } = formatting.getFormatting(cell);
1021
-
1022
- const decorationsForCell = decorations.getDecorationsForCell(addressToIndex(sheet, cell)) ?? [];
1023
- const decorationAddedClasses = useMemo(
1024
- () => decorationsForCell.flatMap((d) => d.classNames ?? []),
1025
- [decorationsForCell],
1026
- );
1027
- const decoratedContent = decorationsForCell.reduce(
1028
- (children, { decorate }) => {
1029
- if (!decorate) {
1030
- return children;
1031
- }
1032
- const DecoratorComponent = decorate;
1033
- return <DecoratorComponent>{children}</DecoratorComponent>;
1034
- },
1035
- <div
1036
- role='none'
1037
- className={mx(
1038
- 'flex flex-grow bs-full is-full px-2 items-center truncate cursor-pointer',
1039
- ...decorationAddedClasses,
1040
- )}
1041
- >
1042
- {value}
1043
- </div>,
1044
- );
1045
-
1046
- return (
1047
- <div
1048
- {...{ [`data-${CELL_DATA_KEY}`]: id }}
1049
- role='cell'
1050
- style={style}
1051
- className={mx(
1052
- 'border border-gridLine cursor-pointer',
1053
- fragments.cell,
1054
- active && ['z-20', fragments.cellSelected],
1055
- classNames,
1056
- )}
1057
- onClick={() => {
1058
- if (editing) {
1059
- setRange?.({ from: cell });
1060
- } else {
1061
- onSelect?.(cell, false);
1062
- }
1063
- }}
1064
- onDoubleClick={() => onSelect?.(cell, true)}
1065
- >
1066
- {decoratedContent}
1067
- </div>
1068
- );
1069
- };
1070
-
1071
- type GridCellEditorProps = {
1072
- style: CSSProperties;
1073
- value: string;
1074
- } & EditorKeysProps;
1075
-
1076
- const GridCellEditor = ({ style, value, onNav, onClose }: GridCellEditorProps) => {
1077
- const { model, range } = useSheetContext();
1078
- const notifier = useRef<CellRangeNotifier>();
1079
- useEffect(() => {
1080
- if (range) {
1081
- // Update range selection in formula.
1082
- notifier.current?.(rangeToA1Notation(range));
1083
- }
1084
- }, [range]);
1085
-
1086
- const extension = useMemo(
1087
- () => [
1088
- editorKeys({ onNav, onClose }),
1089
- sheetExtension({ functions: model.graph.getFunctions() }),
1090
- rangeExtension((fn) => (notifier.current = fn)),
1091
- ],
1092
- [model],
1093
- );
1094
-
1095
- return (
1096
- <div
1097
- role='cell'
1098
- style={style}
1099
- className={mx('z-20 flex', fragments.cellSelected)}
1100
- onClick={(ev) => ev.stopPropagation()}
1101
- >
1102
- <CellEditor autoFocus value={value} extension={extension} />
1103
- </div>
1104
- );
1105
- };
1106
-
1107
- //
1108
- // StatusBar
1109
- //
1110
-
1111
- const SheetStatusBar = () => {
1112
- const { model, cursor, range } = useSheetContext();
1113
-
1114
- let value;
1115
- let isFormula = false;
1116
- if (cursor) {
1117
- value = model.getCellValue(cursor);
1118
- if (typeof value === 'string' && value.charAt(0) === '=') {
1119
- value = model.graph.mapFunctionBindingFromId(model.mapFormulaIndicesToRefs(value));
1120
- isFormula = true;
1121
- } else if (value != null) {
1122
- value = String(value);
1123
- }
1124
- }
1125
-
1126
- return (
1127
- <div className={mx('flex shrink-0 justify-between items-center px-4 py-1 text-sm border-x border-gridLine')}>
1128
- <div className='flex gap-4 items-center'>
1129
- <div className='flex w-16 items-center font-mono'>
1130
- {(range && rangeToA1Notation(range)) || (cursor && addressToA1Notation(cursor))}
1131
- </div>
1132
- <div className='flex gap-2 items-center'>
1133
- <FunctionIcon className={mx('text-greenText', isFormula ? 'visible' : 'invisible')} />
1134
- <span className='font-mono'>{value}</span>
1135
- </div>
1136
- </div>
1137
- </div>
1138
- );
1139
- };
1140
-
1141
- //
1142
- // Debug
1143
- //
1144
-
1145
- const SheetDebug = () => {
1146
- const { model, cursor, range } = useSheetContext();
1147
- const [, forceUpdate] = useState({});
1148
- useEffect(() => {
1149
- // TODO(burdon): This is called without registering a listener.
1150
- const accessor = createDocAccessor(model.sheet, []);
1151
- const handleUpdate = () => forceUpdate({});
1152
- accessor.handle.addListener('change', handleUpdate);
1153
- handleUpdate();
1154
- return () => {
1155
- accessor.handle.removeListener('change', handleUpdate);
1156
- };
1157
- }, [model]);
1158
-
1159
- return (
1160
- <div
1161
- className={mx(
1162
- 'z-20 absolute right-0 top-20 bottom-20 w-[30rem] overflow-auto scrollbar-thin',
1163
- 'border border-gridLine text-xs bg-neutral-50 dark:bg-black text-cyan-500 font-mono p-1 opacity-80',
1164
- )}
1165
- >
1166
- <pre className='whitespace-pre-wrap'>
1167
- {JSON.stringify(
1168
- {
1169
- cursor,
1170
- range,
1171
- cells: model.sheet.cells,
1172
- rowMeta: model.sheet.rowMeta,
1173
- columnMeta: model.sheet.columnMeta,
1174
- formatting: model.sheet.formatting,
1175
- },
1176
- undefined,
1177
- 2,
1178
- )}
1179
- </pre>
1180
- </div>
1181
- );
1182
- };
1183
-
1184
- //
1185
- // Grid
1186
- //
1187
-
1188
- export const Sheet = {
1189
- Root: SheetRoot,
1190
- Main: SheetMain,
1191
- Rows: SheetRows,
1192
- Columns: SheetColumns,
1193
- Grid: SheetGrid,
1194
- Cell: SheetCell,
1195
- StatusBar: SheetStatusBar,
1196
- Debug: SheetDebug,
1197
- };
1198
-
1199
- export type { SheetRootProps, SheetMainProps, SheetRowsProps, SheetColumnsProps, SheetGridProps, SheetCellProps };