@dxos/plugin-sheet 0.6.12-staging.e11e696 → 0.6.13-main.09887cd

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