@dxos/plugin-sheet 0.6.12-staging.e11e696 → 0.6.13-main.041e8aa

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