@dxos/plugin-sheet 0.6.8-main.046e6cf

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 (147) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +14 -0
  3. package/dist/lib/browser/SheetContainer-H22IDJ43.mjs +3740 -0
  4. package/dist/lib/browser/SheetContainer-H22IDJ43.mjs.map +7 -0
  5. package/dist/lib/browser/chunk-6VPEAUG6.mjs +82 -0
  6. package/dist/lib/browser/chunk-6VPEAUG6.mjs.map +7 -0
  7. package/dist/lib/browser/chunk-AT2FJXQX.mjs +861 -0
  8. package/dist/lib/browser/chunk-AT2FJXQX.mjs.map +7 -0
  9. package/dist/lib/browser/chunk-JRL5LGCE.mjs +18 -0
  10. package/dist/lib/browser/chunk-JRL5LGCE.mjs.map +7 -0
  11. package/dist/lib/browser/index.mjs +213 -0
  12. package/dist/lib/browser/index.mjs.map +7 -0
  13. package/dist/lib/browser/meta.json +1 -0
  14. package/dist/lib/browser/meta.mjs +9 -0
  15. package/dist/lib/browser/meta.mjs.map +7 -0
  16. package/dist/lib/browser/types.mjs +22 -0
  17. package/dist/lib/browser/types.mjs.map +7 -0
  18. package/dist/lib/node/SheetContainer-S32KTNZ6.cjs +3731 -0
  19. package/dist/lib/node/SheetContainer-S32KTNZ6.cjs.map +7 -0
  20. package/dist/lib/node/chunk-4CE6FK5Z.cjs +108 -0
  21. package/dist/lib/node/chunk-4CE6FK5Z.cjs.map +7 -0
  22. package/dist/lib/node/chunk-BJ6ZD7MN.cjs +51 -0
  23. package/dist/lib/node/chunk-BJ6ZD7MN.cjs.map +7 -0
  24. package/dist/lib/node/chunk-FCKJ4QRM.cjs +881 -0
  25. package/dist/lib/node/chunk-FCKJ4QRM.cjs.map +7 -0
  26. package/dist/lib/node/index.cjs +226 -0
  27. package/dist/lib/node/index.cjs.map +7 -0
  28. package/dist/lib/node/meta.cjs +30 -0
  29. package/dist/lib/node/meta.cjs.map +7 -0
  30. package/dist/lib/node/meta.json +1 -0
  31. package/dist/lib/node/types.cjs +44 -0
  32. package/dist/lib/node/types.cjs.map +7 -0
  33. package/dist/types/src/SheetPlugin.d.ts +4 -0
  34. package/dist/types/src/SheetPlugin.d.ts.map +1 -0
  35. package/dist/types/src/components/CellEditor/CellEditor.d.ts +14 -0
  36. package/dist/types/src/components/CellEditor/CellEditor.d.ts.map +1 -0
  37. package/dist/types/src/components/CellEditor/CellEditor.stories.d.ts +29 -0
  38. package/dist/types/src/components/CellEditor/CellEditor.stories.d.ts.map +1 -0
  39. package/dist/types/src/components/CellEditor/extension.d.ts +18 -0
  40. package/dist/types/src/components/CellEditor/extension.d.ts.map +1 -0
  41. package/dist/types/src/components/CellEditor/extension.test.d.ts +2 -0
  42. package/dist/types/src/components/CellEditor/extension.test.d.ts.map +1 -0
  43. package/dist/types/src/components/CellEditor/functions.d.ts +66 -0
  44. package/dist/types/src/components/CellEditor/functions.d.ts.map +1 -0
  45. package/dist/types/src/components/CellEditor/index.d.ts +3 -0
  46. package/dist/types/src/components/CellEditor/index.d.ts.map +1 -0
  47. package/dist/types/src/components/ComputeGraph/async-function.d.ts +52 -0
  48. package/dist/types/src/components/ComputeGraph/async-function.d.ts.map +1 -0
  49. package/dist/types/src/components/ComputeGraph/custom.d.ts +21 -0
  50. package/dist/types/src/components/ComputeGraph/custom.d.ts.map +1 -0
  51. package/dist/types/src/components/ComputeGraph/edge-function.d.ts +20 -0
  52. package/dist/types/src/components/ComputeGraph/edge-function.d.ts.map +1 -0
  53. package/dist/types/src/components/ComputeGraph/graph-context.d.ts +11 -0
  54. package/dist/types/src/components/ComputeGraph/graph-context.d.ts.map +1 -0
  55. package/dist/types/src/components/ComputeGraph/graph.browser.test.d.ts +2 -0
  56. package/dist/types/src/components/ComputeGraph/graph.browser.test.d.ts.map +1 -0
  57. package/dist/types/src/components/ComputeGraph/graph.d.ts +21 -0
  58. package/dist/types/src/components/ComputeGraph/graph.d.ts.map +1 -0
  59. package/dist/types/src/components/ComputeGraph/index.d.ts +4 -0
  60. package/dist/types/src/components/ComputeGraph/index.d.ts.map +1 -0
  61. package/dist/types/src/components/Sheet/Sheet.d.ts +55 -0
  62. package/dist/types/src/components/Sheet/Sheet.d.ts.map +1 -0
  63. package/dist/types/src/components/Sheet/Sheet.stories.d.ts +54 -0
  64. package/dist/types/src/components/Sheet/Sheet.stories.d.ts.map +1 -0
  65. package/dist/types/src/components/Sheet/formatting.d.ts +14 -0
  66. package/dist/types/src/components/Sheet/formatting.d.ts.map +1 -0
  67. package/dist/types/src/components/Sheet/grid.d.ts +52 -0
  68. package/dist/types/src/components/Sheet/grid.d.ts.map +1 -0
  69. package/dist/types/src/components/Sheet/index.d.ts +2 -0
  70. package/dist/types/src/components/Sheet/index.d.ts.map +1 -0
  71. package/dist/types/src/components/Sheet/nav.d.ts +29 -0
  72. package/dist/types/src/components/Sheet/nav.d.ts.map +1 -0
  73. package/dist/types/src/components/Sheet/sheet-context.d.ts +24 -0
  74. package/dist/types/src/components/Sheet/sheet-context.d.ts.map +1 -0
  75. package/dist/types/src/components/Sheet/util.d.ts +18 -0
  76. package/dist/types/src/components/Sheet/util.d.ts.map +1 -0
  77. package/dist/types/src/components/SheetContainer.d.ts +9 -0
  78. package/dist/types/src/components/SheetContainer.d.ts.map +1 -0
  79. package/dist/types/src/components/Toolbar/Toolbar.d.ts +21 -0
  80. package/dist/types/src/components/Toolbar/Toolbar.d.ts.map +1 -0
  81. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts +35 -0
  82. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts.map +1 -0
  83. package/dist/types/src/components/Toolbar/common.d.ts +20 -0
  84. package/dist/types/src/components/Toolbar/common.d.ts.map +1 -0
  85. package/dist/types/src/components/Toolbar/index.d.ts +2 -0
  86. package/dist/types/src/components/Toolbar/index.d.ts.map +1 -0
  87. package/dist/types/src/components/index.d.ts +7 -0
  88. package/dist/types/src/components/index.d.ts.map +1 -0
  89. package/dist/types/src/index.d.ts +4 -0
  90. package/dist/types/src/index.d.ts.map +1 -0
  91. package/dist/types/src/meta.d.ts +15 -0
  92. package/dist/types/src/meta.d.ts.map +1 -0
  93. package/dist/types/src/model/index.d.ts +3 -0
  94. package/dist/types/src/model/index.d.ts.map +1 -0
  95. package/dist/types/src/model/model.browser.test.d.ts +2 -0
  96. package/dist/types/src/model/model.browser.test.d.ts.map +1 -0
  97. package/dist/types/src/model/model.d.ts +142 -0
  98. package/dist/types/src/model/model.d.ts.map +1 -0
  99. package/dist/types/src/model/types.d.ts +17 -0
  100. package/dist/types/src/model/types.d.ts.map +1 -0
  101. package/dist/types/src/model/types.test.d.ts +2 -0
  102. package/dist/types/src/model/types.test.d.ts.map +1 -0
  103. package/dist/types/src/model/util.d.ts +15 -0
  104. package/dist/types/src/model/util.d.ts.map +1 -0
  105. package/dist/types/src/translations.d.ts +16 -0
  106. package/dist/types/src/translations.d.ts.map +1 -0
  107. package/dist/types/src/types.d.ts +94 -0
  108. package/dist/types/src/types.d.ts.map +1 -0
  109. package/package.json +122 -0
  110. package/src/SheetPlugin.tsx +150 -0
  111. package/src/components/CellEditor/CellEditor.stories.tsx +88 -0
  112. package/src/components/CellEditor/CellEditor.tsx +113 -0
  113. package/src/components/CellEditor/extension.test.ts +42 -0
  114. package/src/components/CellEditor/extension.ts +286 -0
  115. package/src/components/CellEditor/functions.ts +2017 -0
  116. package/src/components/CellEditor/index.ts +6 -0
  117. package/src/components/ComputeGraph/async-function.ts +148 -0
  118. package/src/components/ComputeGraph/custom.ts +70 -0
  119. package/src/components/ComputeGraph/edge-function.ts +60 -0
  120. package/src/components/ComputeGraph/graph-context.tsx +37 -0
  121. package/src/components/ComputeGraph/graph.browser.test.ts +49 -0
  122. package/src/components/ComputeGraph/graph.ts +52 -0
  123. package/src/components/ComputeGraph/index.ts +7 -0
  124. package/src/components/Sheet/Sheet.stories.tsx +329 -0
  125. package/src/components/Sheet/Sheet.tsx +1164 -0
  126. package/src/components/Sheet/formatting.ts +106 -0
  127. package/src/components/Sheet/grid.ts +191 -0
  128. package/src/components/Sheet/index.ts +5 -0
  129. package/src/components/Sheet/nav.ts +157 -0
  130. package/src/components/Sheet/sheet-context.tsx +101 -0
  131. package/src/components/Sheet/util.ts +56 -0
  132. package/src/components/SheetContainer.tsx +30 -0
  133. package/src/components/Toolbar/Toolbar.stories.tsx +36 -0
  134. package/src/components/Toolbar/Toolbar.tsx +198 -0
  135. package/src/components/Toolbar/common.tsx +72 -0
  136. package/src/components/Toolbar/index.ts +5 -0
  137. package/src/components/index.ts +10 -0
  138. package/src/index.ts +9 -0
  139. package/src/meta.tsx +18 -0
  140. package/src/model/index.ts +6 -0
  141. package/src/model/model.browser.test.ts +100 -0
  142. package/src/model/model.ts +480 -0
  143. package/src/model/types.test.ts +92 -0
  144. package/src/model/types.ts +71 -0
  145. package/src/model/util.ts +36 -0
  146. package/src/translations.ts +22 -0
  147. package/src/types.ts +110 -0
@@ -0,0 +1,881 @@
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_FCKJ4QRM_exports = {};
30
+ __export(chunk_FCKJ4QRM_exports, {
31
+ ComputeGraphContextProvider: () => ComputeGraphContextProvider,
32
+ SheetModel: () => SheetModel,
33
+ addressFromA1Notation: () => addressFromA1Notation,
34
+ addressToA1Notation: () => addressToA1Notation,
35
+ columnLetter: () => columnLetter,
36
+ createComputeGraph: () => createComputeGraph,
37
+ inRange: () => inRange,
38
+ posEquals: () => posEquals,
39
+ rangeToA1Notation: () => rangeToA1Notation,
40
+ useComputeGraph: () => useComputeGraph
41
+ });
42
+ module.exports = __toCommonJS(chunk_FCKJ4QRM_exports);
43
+ var import_chunk_4CE6FK5Z = require("./chunk-4CE6FK5Z.cjs");
44
+ var import_hyperformula = require("hyperformula");
45
+ var import_async = require("@dxos/async");
46
+ var import_keys = require("@dxos/keys");
47
+ var import_log = require("@dxos/log");
48
+ var import_hyperformula2 = require("hyperformula");
49
+ var import_async2 = require("@dxos/async");
50
+ var import_log2 = require("@dxos/log");
51
+ var import_hyperformula3 = require("hyperformula");
52
+ var import_util = require("@dxos/util");
53
+ var import_hyperformula4 = require("hyperformula");
54
+ var import_echo = require("@dxos/client/echo");
55
+ var import_edge = require("@dxos/plugin-script/edge");
56
+ var import_types = require("@dxos/plugin-script/types");
57
+ var import_react = __toESM(require("react"));
58
+ var import_invariant = require("@dxos/invariant");
59
+ var import_hyperformula5 = require("hyperformula");
60
+ var import_async3 = require("@dxos/async");
61
+ var import_context = require("@dxos/context");
62
+ var import_invariant2 = require("@dxos/invariant");
63
+ var import_keys2 = require("@dxos/keys");
64
+ var import_log3 = require("@dxos/log");
65
+ var import_crypto = require("@dxos/crypto");
66
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/plugin-sheet/src/components/ComputeGraph/async-function.ts";
67
+ var defaultFunctionContextOptions = {
68
+ defaultTtl: 5e3,
69
+ recalculationDelay: 200
70
+ };
71
+ var FunctionContext = class _FunctionContext {
72
+ // Mangle name with params.
73
+ static createInvocationKey(name, ...args) {
74
+ return JSON.stringify({
75
+ name,
76
+ ...args
77
+ });
78
+ }
79
+ constructor(_hf, _space, onUpdate, _options = defaultFunctionContextOptions) {
80
+ this._hf = _hf;
81
+ this._space = _space;
82
+ this._options = _options;
83
+ this._cache = /* @__PURE__ */ new Map();
84
+ this._pending = /* @__PURE__ */ new Map();
85
+ this._invocations = {};
86
+ this._onUpdate = (0, import_async2.debounce)(() => {
87
+ this._hf.resumeEvaluation();
88
+ onUpdate(this);
89
+ }, this._options.recalculationDelay);
90
+ }
91
+ get space() {
92
+ return this._space;
93
+ }
94
+ get info() {
95
+ return {
96
+ cache: this._cache.size,
97
+ invocations: this._invocations
98
+ };
99
+ }
100
+ flush() {
101
+ this._cache.clear();
102
+ this._invocations = {};
103
+ }
104
+ /**
105
+ * Exec the function if TTL has expired.
106
+ * Return the cached value.
107
+ */
108
+ invokeFunction(name, state, args, cb, options) {
109
+ const ttl = options?.ttl ?? this._options.defaultTtl;
110
+ const { formulaAddress: cell } = state;
111
+ const invocationKey = _FunctionContext.createInvocationKey(name, ...args);
112
+ const { value = void 0, ts = 0 } = this._cache.get(invocationKey) ?? {};
113
+ const now = Date.now();
114
+ const delta = now - ts;
115
+ if ((!ts || delta > ttl) && !this._pending.has(invocationKey)) {
116
+ this._pending.set(invocationKey, now);
117
+ setTimeout(async () => {
118
+ this._invocations[name] = (this._invocations[name] ?? 0) + 1;
119
+ try {
120
+ const value2 = await cb(...args);
121
+ this._cache.set(invocationKey, {
122
+ value: value2,
123
+ ts: Date.now()
124
+ });
125
+ (0, import_log2.log)("set", {
126
+ cell,
127
+ value: value2
128
+ }, {
129
+ F: __dxlog_file,
130
+ L: 116,
131
+ S: this,
132
+ C: (f, a) => f(...a)
133
+ });
134
+ this._onUpdate();
135
+ } catch (err) {
136
+ import_log2.log.warn("failed", {
137
+ cell,
138
+ err
139
+ }, {
140
+ F: __dxlog_file,
141
+ L: 120,
142
+ S: this,
143
+ C: (f, a) => f(...a)
144
+ });
145
+ this._cache.set(invocationKey, {
146
+ value: new import_hyperformula2.CellError(import_hyperformula2.ErrorType.ERROR, "Function failed."),
147
+ ts: Date.now()
148
+ });
149
+ } finally {
150
+ this._pending.delete(invocationKey);
151
+ }
152
+ });
153
+ }
154
+ (0, import_log2.log)("invoke", {
155
+ cell,
156
+ name,
157
+ args,
158
+ cache: value
159
+ }, {
160
+ F: __dxlog_file,
161
+ L: 128,
162
+ S: this,
163
+ C: (f, a) => f(...a)
164
+ });
165
+ return value;
166
+ }
167
+ };
168
+ var FunctionPluginAsync = class extends import_hyperformula2.FunctionPlugin {
169
+ get context() {
170
+ return this.config.context;
171
+ }
172
+ runAsyncFunction(ast, state, cb, options) {
173
+ const { procedureName } = ast;
174
+ const metadata = this.metadata(procedureName);
175
+ return this.runFunction(ast.args, state, metadata, (...args) => {
176
+ return this.context.invokeFunction(procedureName, state, args, cb, options) ?? import_hyperformula2.EmptyValue;
177
+ });
178
+ }
179
+ };
180
+ var parseNumberString = (str) => {
181
+ return parseFloat(str.replace(/[^\d.]/g, ""));
182
+ };
183
+ var CustomPlugin = class extends FunctionPluginAsync {
184
+ test(ast, state) {
185
+ const handler = async () => {
186
+ return Math.random();
187
+ };
188
+ return this.runAsyncFunction(ast, state, handler);
189
+ }
190
+ crypto(ast, state) {
191
+ const handler = async (_currency) => {
192
+ const currency = (_currency || "USD").toUpperCase();
193
+ const result = await fetch(`https://api.coindesk.com/v1/bpi/currentprice/${currency}.json`);
194
+ const data = await result.json();
195
+ const rate = (0, import_util.getDeep)(data, [
196
+ "bpi",
197
+ currency,
198
+ "rate"
199
+ ]);
200
+ if (!rate) {
201
+ return NaN;
202
+ }
203
+ return parseNumberString(rate);
204
+ };
205
+ return this.runAsyncFunction(ast, state, handler, {
206
+ ttl: 1e4
207
+ });
208
+ }
209
+ };
210
+ CustomPlugin.implementedFunctions = {
211
+ TEST: {
212
+ method: "test",
213
+ parameters: [],
214
+ isVolatile: true
215
+ },
216
+ CRYPTO: {
217
+ method: "crypto",
218
+ parameters: [
219
+ {
220
+ argumentType: import_hyperformula3.FunctionArgumentType.STRING,
221
+ optionalArg: true
222
+ }
223
+ ],
224
+ isVolatile: true
225
+ }
226
+ };
227
+ var CustomPluginTranslations = {
228
+ enGB: {
229
+ TEST: "TEST",
230
+ CRYPTO: "CRYPTO"
231
+ },
232
+ enUS: {
233
+ TEST: "TEST",
234
+ CRYPTO: "CRYPTO"
235
+ }
236
+ };
237
+ var EdgeFunctionPlugin = class extends FunctionPluginAsync {
238
+ edge(ast, state) {
239
+ const handler = async (binding) => {
240
+ const space = this.context.space;
241
+ if (!space) {
242
+ return new import_hyperformula4.CellError(import_hyperformula4.ErrorType.VALUE, "No space");
243
+ }
244
+ const { objects: [script] } = await space.db.query(import_echo.Filter.schema(import_types.ScriptType, {
245
+ binding
246
+ })).run();
247
+ if (!script) {
248
+ return new import_hyperformula4.CellError(import_hyperformula4.ErrorType.VALUE, "No script");
249
+ }
250
+ const path = (0, import_edge.getUserFunctionUrlInMetadata)((0, import_echo.getMeta)(script));
251
+ const result = await fetch(`https://functions-staging.dxos.workers.dev${path}`, {
252
+ method: "POST"
253
+ });
254
+ return await result.text();
255
+ };
256
+ return this.runAsyncFunction(ast, state, handler, {
257
+ ttl: 1e4
258
+ });
259
+ }
260
+ };
261
+ EdgeFunctionPlugin.implementedFunctions = {
262
+ EDGE: {
263
+ method: "edge",
264
+ parameters: [
265
+ {
266
+ argumentType: import_hyperformula4.FunctionArgumentType.STRING
267
+ }
268
+ ],
269
+ isVolatile: true
270
+ }
271
+ };
272
+ var EdgeFunctionPluginTranslations = {
273
+ enGB: {
274
+ EDGE: "EDGE"
275
+ },
276
+ enUS: {
277
+ EDGE: "EDGE"
278
+ }
279
+ };
280
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/plugins/plugin-sheet/src/components/ComputeGraph/graph.ts";
281
+ var createComputeGraph = (space) => {
282
+ import_hyperformula.HyperFormula.registerFunctionPlugin(CustomPlugin, CustomPluginTranslations);
283
+ import_hyperformula.HyperFormula.registerFunctionPlugin(EdgeFunctionPlugin, EdgeFunctionPluginTranslations);
284
+ const hf = import_hyperformula.HyperFormula.buildEmpty({
285
+ licenseKey: "gpl-v3"
286
+ });
287
+ return new ComputeGraph(hf, space);
288
+ };
289
+ var ComputeGraph = class {
290
+ constructor(hf, _space) {
291
+ this.hf = hf;
292
+ this._space = _space;
293
+ this.id = `graph-${import_keys.PublicKey.random().truncate()}`;
294
+ this.update = new import_async.Event();
295
+ this.context = new FunctionContext(this.hf, this._space, () => {
296
+ this.refresh();
297
+ });
298
+ this.hf.updateConfig({
299
+ context: this.context
300
+ });
301
+ }
302
+ refresh() {
303
+ (0, import_log.log)("refresh", {
304
+ id: this.id
305
+ }, {
306
+ F: __dxlog_file2,
307
+ L: 49,
308
+ S: this,
309
+ C: (f, a) => f(...a)
310
+ });
311
+ this.update.emit();
312
+ }
313
+ };
314
+ var ComputeGraphContext = /* @__PURE__ */ (0, import_react.createContext)({
315
+ graphs: {},
316
+ setGraph: () => {
317
+ }
318
+ });
319
+ var ComputeGraphContextProvider = ({ children, graphs, setGraph }) => {
320
+ return /* @__PURE__ */ import_react.default.createElement(ComputeGraphContext.Provider, {
321
+ value: {
322
+ graphs,
323
+ setGraph
324
+ }
325
+ }, children);
326
+ };
327
+ var useComputeGraph = (space) => {
328
+ const { graphs, setGraph } = (0, import_react.useContext)(ComputeGraphContext);
329
+ const graph = graphs[space.id] ?? createComputeGraph(space);
330
+ (0, import_react.useEffect)(() => {
331
+ if (!graphs[space.id]) {
332
+ setGraph(space.id, graph);
333
+ }
334
+ }, [
335
+ space
336
+ ]);
337
+ return graph;
338
+ };
339
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/plugins/plugin-sheet/src/model/types.ts";
340
+ var MAX_COLUMNS = 26 * 26;
341
+ var posEquals = (a, b) => {
342
+ return a?.column === b?.column && a?.row === b?.row;
343
+ };
344
+ var columnLetter = (column) => {
345
+ (0, import_invariant.invariant)(column < MAX_COLUMNS, `Invalid column: ${column}`, {
346
+ F: __dxlog_file3,
347
+ L: 17,
348
+ S: void 0,
349
+ A: [
350
+ "column < MAX_COLUMNS",
351
+ "`Invalid column: ${column}`"
352
+ ]
353
+ });
354
+ return (column >= 26 ? String.fromCharCode("A".charCodeAt(0) + Math.floor(column / 26) - 1) : "") + String.fromCharCode("A".charCodeAt(0) + column % 26);
355
+ };
356
+ var addressToA1Notation = ({ column, row }) => {
357
+ return `${columnLetter(column)}${row + 1}`;
358
+ };
359
+ var addressFromA1Notation = (ref) => {
360
+ const match = ref.match(/([A-Z]+)(\d+)/);
361
+ (0, import_invariant.invariant)(match, `Invalid notation: ${ref}`, {
362
+ F: __dxlog_file3,
363
+ L: 30,
364
+ S: void 0,
365
+ A: [
366
+ "match",
367
+ "`Invalid notation: ${ref}`"
368
+ ]
369
+ });
370
+ return {
371
+ row: parseInt(match[2], 10) - 1,
372
+ column: match[1].split("").reduce((acc, c) => acc * 26 + c.charCodeAt(0) - "A".charCodeAt(0) + 1, 0) - 1
373
+ };
374
+ };
375
+ var rangeToA1Notation = (range) => {
376
+ return [
377
+ range?.from && addressToA1Notation(range?.from),
378
+ range?.to && addressToA1Notation(range?.to)
379
+ ].filter(Boolean).join(":");
380
+ };
381
+ var inRange = (range, cell) => {
382
+ if (!range) {
383
+ return false;
384
+ }
385
+ const { from, to } = range;
386
+ if (from && posEquals(from, cell) || to && posEquals(to, cell)) {
387
+ return true;
388
+ }
389
+ if (!from || !to) {
390
+ return false;
391
+ }
392
+ const { column: c1, row: r1 } = from;
393
+ const { column: c2, row: r2 } = to;
394
+ const cMin = Math.min(c1, c2);
395
+ const cMax = Math.max(c1, c2);
396
+ const rMin = Math.min(r1, r2);
397
+ const rMax = Math.max(r1, r2);
398
+ const { column, row } = cell;
399
+ return column >= cMin && column <= cMax && row >= rMin && row <= rMax;
400
+ };
401
+ var ApiError = class extends Error {
402
+ };
403
+ var ReadonlyException = class extends ApiError {
404
+ };
405
+ var RangeException = class extends ApiError {
406
+ constructor(n) {
407
+ super();
408
+ }
409
+ };
410
+ var createIndex = (length = 8) => {
411
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
412
+ const charactersLength = characters.length;
413
+ const randomBuffer = (0, import_crypto.randomBytes)(length);
414
+ return Array.from(randomBuffer, (byte) => characters[byte % charactersLength]).join("");
415
+ };
416
+ var createIndices = (length) => Array.from({
417
+ length
418
+ }).map(() => createIndex());
419
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/plugins/plugin-sheet/src/model/model.ts";
420
+ var DEFAULT_ROWS = 500;
421
+ var DEFAULT_COLUMNS = 26 * 2;
422
+ var typeMap = {
423
+ BOOLEAN: import_chunk_4CE6FK5Z.ValueTypeEnum.Boolean,
424
+ NUMBER_RAW: import_chunk_4CE6FK5Z.ValueTypeEnum.Number,
425
+ NUMBER_PERCENT: import_chunk_4CE6FK5Z.ValueTypeEnum.Percent,
426
+ NUMBER_CURRENCY: import_chunk_4CE6FK5Z.ValueTypeEnum.Currency,
427
+ NUMBER_DATETIME: import_chunk_4CE6FK5Z.ValueTypeEnum.DateTime,
428
+ NUMBER_DATE: import_chunk_4CE6FK5Z.ValueTypeEnum.Date,
429
+ NUMBER_TIME: import_chunk_4CE6FK5Z.ValueTypeEnum.Time
430
+ };
431
+ var defaultOptions = {
432
+ rows: 50,
433
+ columns: 26
434
+ };
435
+ var getTopLeft = (range) => {
436
+ const to = range.to ?? range.from;
437
+ return {
438
+ row: Math.min(range.from.row, to.row),
439
+ column: Math.min(range.from.column, to.column)
440
+ };
441
+ };
442
+ var toSimpleCellAddress = (sheet, cell) => ({
443
+ sheet,
444
+ row: cell.row,
445
+ col: cell.column
446
+ });
447
+ var toModelRange = (sheet, range) => ({
448
+ start: toSimpleCellAddress(sheet, range.from),
449
+ end: toSimpleCellAddress(sheet, range.to ?? range.from)
450
+ });
451
+ var SheetModel = class {
452
+ constructor(_graph, _sheet, options = {}) {
453
+ this._graph = _graph;
454
+ this._sheet = _sheet;
455
+ this.id = `model-${import_keys2.PublicKey.random().truncate()}`;
456
+ this._ctx = void 0;
457
+ this.update = new import_async3.Event();
458
+ const name = this._sheet.id;
459
+ if (!this._graph.hf.doesSheetExist(name)) {
460
+ this._graph.hf.addSheet(name);
461
+ }
462
+ this._sheetId = this._graph.hf.getSheetId(name);
463
+ this._options = {
464
+ ...defaultOptions,
465
+ ...options
466
+ };
467
+ this.reset();
468
+ }
469
+ get graph() {
470
+ return this._graph;
471
+ }
472
+ get sheet() {
473
+ return this._sheet;
474
+ }
475
+ get readonly() {
476
+ return this._options.readonly;
477
+ }
478
+ get bounds() {
479
+ return {
480
+ rows: this._sheet.rows.length,
481
+ columns: this._sheet.columns.length
482
+ };
483
+ }
484
+ get functions() {
485
+ return this._graph.hf.getRegisteredFunctionNames();
486
+ }
487
+ get initialized() {
488
+ return !!this._ctx;
489
+ }
490
+ /**
491
+ * Initialize sheet and engine.
492
+ */
493
+ async initialize() {
494
+ (0, import_log3.log)("initialize", {
495
+ id: this.id
496
+ }, {
497
+ F: __dxlog_file4,
498
+ L: 130,
499
+ S: this,
500
+ C: (f, a) => f(...a)
501
+ });
502
+ (0, import_invariant2.invariant)(!this.initialized, "Already initialized.", {
503
+ F: __dxlog_file4,
504
+ L: 131,
505
+ S: this,
506
+ A: [
507
+ "!this.initialized",
508
+ "'Already initialized.'"
509
+ ]
510
+ });
511
+ this._ctx = new import_context.Context(void 0, {
512
+ F: __dxlog_file4,
513
+ L: 132
514
+ });
515
+ if (!this._sheet.rows.length) {
516
+ this._insertIndices(this._sheet.rows, 0, this._options.rows, DEFAULT_ROWS);
517
+ }
518
+ if (!this._sheet.columns.length) {
519
+ this._insertIndices(this._sheet.columns, 0, this._options.columns, DEFAULT_COLUMNS);
520
+ }
521
+ this.reset();
522
+ const unsubscribe = this._graph.update.on(() => this.update.emit());
523
+ this._ctx.onDispose(unsubscribe);
524
+ return this;
525
+ }
526
+ async destroy() {
527
+ (0, import_log3.log)("destroy", {
528
+ id: this.id
529
+ }, {
530
+ F: __dxlog_file4,
531
+ L: 149,
532
+ S: this,
533
+ C: (f, a) => f(...a)
534
+ });
535
+ if (this._ctx) {
536
+ await this._ctx.dispose();
537
+ this._ctx = void 0;
538
+ }
539
+ }
540
+ /**
541
+ * Update engine.
542
+ * NOTE: This resets the undo history.
543
+ * @deprecated
544
+ */
545
+ reset() {
546
+ this._graph.hf.clearSheet(this._sheetId);
547
+ Object.entries(this._sheet.cells).forEach(([key, { value }]) => {
548
+ const { column, row } = this.addressFromIndex(key);
549
+ if (typeof value === "string" && value.charAt(0) === "=") {
550
+ value = this.mapFormulaIndicesToRefs(value);
551
+ }
552
+ this._graph.hf.setCellContents({
553
+ sheet: this._sheetId,
554
+ row,
555
+ col: column
556
+ }, value);
557
+ });
558
+ }
559
+ /**
560
+ * Recalculate formulas.
561
+ * NOTE: This resets the undo history.
562
+ * https://hyperformula.handsontable.com/guide/volatile-functions.html#volatile-actions
563
+ * @deprecated
564
+ */
565
+ // TODO(burdon): Remove.
566
+ recalculate() {
567
+ this._graph.hf.rebuildAndRecalculate();
568
+ }
569
+ insertRows(i, n = 1) {
570
+ this._insertIndices(this._sheet.rows, i, n, DEFAULT_ROWS);
571
+ this.reset();
572
+ }
573
+ insertColumns(i, n = 1) {
574
+ this._insertIndices(this._sheet.columns, i, n, DEFAULT_COLUMNS);
575
+ this.reset();
576
+ }
577
+ //
578
+ // Undoable actions.
579
+ // TODO(burdon): Group undoable methods; consistently update hf/sheet.
580
+ //
581
+ /**
582
+ * Clear range of values.
583
+ */
584
+ clear(range) {
585
+ const topLeft = getTopLeft(range);
586
+ const values = this._iterRange(range, () => null);
587
+ this._graph.hf.setCellContents(toSimpleCellAddress(this._sheetId, topLeft), values);
588
+ this._iterRange(range, (cell) => {
589
+ const idx = this.addressToIndex(cell);
590
+ delete this._sheet.cells[idx];
591
+ });
592
+ }
593
+ cut(range) {
594
+ this._graph.hf.cut(toModelRange(this._sheetId, range));
595
+ this._iterRange(range, (cell) => {
596
+ const idx = this.addressToIndex(cell);
597
+ delete this._sheet.cells[idx];
598
+ });
599
+ }
600
+ copy(range) {
601
+ this._graph.hf.copy(toModelRange(this._sheetId, range));
602
+ }
603
+ paste(cell) {
604
+ if (!this._graph.hf.isClipboardEmpty()) {
605
+ const changes = this._graph.hf.paste(toSimpleCellAddress(this._sheetId, cell));
606
+ for (const change of changes) {
607
+ if (change instanceof import_hyperformula5.ExportedCellChange) {
608
+ const { address, newValue } = change;
609
+ const idx = this.addressToIndex({
610
+ row: address.row,
611
+ column: address.col
612
+ });
613
+ this._sheet.cells[idx] = {
614
+ value: newValue
615
+ };
616
+ }
617
+ }
618
+ }
619
+ }
620
+ // TODO(burdon): Display undo/redo state.
621
+ undo() {
622
+ if (this._graph.hf.isThereSomethingToUndo()) {
623
+ this._graph.hf.undo();
624
+ this.update.emit();
625
+ }
626
+ }
627
+ redo() {
628
+ if (this._graph.hf.isThereSomethingToRedo()) {
629
+ this._graph.hf.redo();
630
+ this.update.emit();
631
+ }
632
+ }
633
+ /**
634
+ * Get value from sheet.
635
+ */
636
+ getCellValue(cell) {
637
+ const idx = this.addressToIndex(cell);
638
+ return this._sheet.cells[idx]?.value ?? null;
639
+ }
640
+ /**
641
+ * Get value as a string for editing.
642
+ */
643
+ getCellText(cell) {
644
+ const value = this.getCellValue(cell);
645
+ if (value == null) {
646
+ return void 0;
647
+ }
648
+ if (typeof value === "string" && value.charAt(0) === "=") {
649
+ return this.mapFormulaIndicesToRefs(value);
650
+ } else {
651
+ return String(value);
652
+ }
653
+ }
654
+ /**
655
+ * Get array of raw values from sheet.
656
+ */
657
+ getCellValues(range) {
658
+ return this._iterRange(range, (cell) => this.getCellValue(cell));
659
+ }
660
+ /**
661
+ * Gets the regular or computed value from the engine.
662
+ */
663
+ getValue(cell) {
664
+ const value = this._graph.hf.getCellValue(toSimpleCellAddress(this._sheetId, cell));
665
+ if (value instanceof import_hyperformula5.DetailedCellError) {
666
+ return value.toString();
667
+ }
668
+ return value;
669
+ }
670
+ /**
671
+ * Get value type.
672
+ */
673
+ getValueType(cell) {
674
+ const addr = toSimpleCellAddress(this._sheetId, cell);
675
+ const type = this._graph.hf.getCellValueDetailedType(addr);
676
+ return typeMap[type];
677
+ }
678
+ /**
679
+ * Sets the value, updating the sheet and engine.
680
+ */
681
+ setValue(cell, value) {
682
+ if (this._options.readonly) {
683
+ throw new ReadonlyException();
684
+ }
685
+ let refresh = false;
686
+ if (cell.row >= this._sheet.rows.length) {
687
+ this._insertIndices(this._sheet.rows, cell.row, 1, DEFAULT_ROWS);
688
+ refresh = true;
689
+ }
690
+ if (cell.column >= this._sheet.columns.length) {
691
+ this._insertIndices(this._sheet.columns, cell.column, 1, DEFAULT_COLUMNS);
692
+ refresh = true;
693
+ }
694
+ if (refresh) {
695
+ this.reset();
696
+ }
697
+ this._graph.hf.setCellContents({
698
+ sheet: this._sheetId,
699
+ row: cell.row,
700
+ col: cell.column
701
+ }, [
702
+ [
703
+ value
704
+ ]
705
+ ]);
706
+ const idx = this.addressToIndex(cell);
707
+ if (value === void 0 || value === null) {
708
+ delete this._sheet.cells[idx];
709
+ } else {
710
+ if (typeof value === "string" && value.charAt(0) === "=") {
711
+ value = this.mapFormulaRefsToIndices(value);
712
+ }
713
+ this._sheet.cells[idx] = {
714
+ value
715
+ };
716
+ }
717
+ }
718
+ /**
719
+ * Sets values from a simple map.
720
+ */
721
+ setValues(values) {
722
+ Object.entries(values).forEach(([key, { value }]) => {
723
+ this.setValue(addressFromA1Notation(key), value);
724
+ });
725
+ }
726
+ /**
727
+ * Iterate range.
728
+ */
729
+ _iterRange(range, cb) {
730
+ const to = range.to ?? range.from;
731
+ const rowRange = [
732
+ Math.min(range.from.row, to.row),
733
+ Math.max(range.from.row, to.row)
734
+ ];
735
+ const columnRange = [
736
+ Math.min(range.from.column, to.column),
737
+ Math.max(range.from.column, to.column)
738
+ ];
739
+ const rows = [];
740
+ for (let row = rowRange[0]; row <= rowRange[1]; row++) {
741
+ const rowCells = [];
742
+ for (let column = columnRange[0]; column <= columnRange[1]; column++) {
743
+ const value = cb({
744
+ row,
745
+ column
746
+ });
747
+ if (value !== void 0) {
748
+ rowCells.push(value);
749
+ }
750
+ }
751
+ rows.push(rowCells);
752
+ }
753
+ return rows;
754
+ }
755
+ /**
756
+ *
757
+ */
758
+ // TODO(burdon): Insert indices into sheet.
759
+ _insertIndices(indices, i, n, max) {
760
+ if (i + n > max) {
761
+ throw new RangeException(i + n);
762
+ }
763
+ const idx = createIndices(n);
764
+ indices.splice(i, 0, ...idx);
765
+ }
766
+ // TODO(burdon): Delete index.
767
+ _deleteIndices(indices, i, n) {
768
+ throw new Error("Not implemented");
769
+ }
770
+ // TODO(burdon): Move. Cannot use fractional without changing. Switch back to using unique IDs?
771
+ _moveIndices(indices, i, j, n) {
772
+ throw new Error("Not implemented");
773
+ }
774
+ //
775
+ // Indices.
776
+ //
777
+ /**
778
+ * E.g., "A1" => "x1@y1".
779
+ */
780
+ addressToIndex(cell) {
781
+ return `${this._sheet.columns[cell.column]}@${this._sheet.rows[cell.row]}`;
782
+ }
783
+ /**
784
+ * E.g., "x1@y1" => "A1".
785
+ */
786
+ addressFromIndex(idx) {
787
+ const [column, row] = idx.split("@");
788
+ return {
789
+ column: this._sheet.columns.indexOf(column),
790
+ row: this._sheet.rows.indexOf(row)
791
+ };
792
+ }
793
+ /**
794
+ * E.g., "A1:B2" => "x1@y1:x2@y2".
795
+ */
796
+ rangeToIndex(range) {
797
+ return [
798
+ range.from,
799
+ range.to ?? range.from
800
+ ].map((cell) => this.addressToIndex(cell)).join(":");
801
+ }
802
+ /**
803
+ * E.g., "x1@y1:x2@y2" => "A1:B2".
804
+ */
805
+ rangeFromIndex(idx) {
806
+ const [from, to] = idx.split(":").map((idx2) => this.addressFromIndex(idx2));
807
+ return {
808
+ from,
809
+ to
810
+ };
811
+ }
812
+ /**
813
+ * Map from A1 notation to indices.
814
+ */
815
+ mapFormulaRefsToIndices(formula) {
816
+ (0, import_invariant2.invariant)(formula.charAt(0) === "=", void 0, {
817
+ F: __dxlog_file4,
818
+ L: 439,
819
+ S: this,
820
+ A: [
821
+ "formula.charAt(0) === '='",
822
+ ""
823
+ ]
824
+ });
825
+ return formula.replace(/([a-zA-Z]+)([0-9]+)/g, (match) => {
826
+ return this.addressToIndex(addressFromA1Notation(match));
827
+ });
828
+ }
829
+ /**
830
+ * Map from indices to A1 notation.
831
+ */
832
+ mapFormulaIndicesToRefs(formula) {
833
+ (0, import_invariant2.invariant)(formula.charAt(0) === "=", void 0, {
834
+ F: __dxlog_file4,
835
+ L: 449,
836
+ S: this,
837
+ A: [
838
+ "formula.charAt(0) === '='",
839
+ ""
840
+ ]
841
+ });
842
+ return formula.replace(/([a-zA-Z0-9]+)@([a-zA-Z0-9]+)/g, (idx) => {
843
+ return addressToA1Notation(this.addressFromIndex(idx));
844
+ });
845
+ }
846
+ //
847
+ // Values
848
+ //
849
+ /**
850
+ * https://hyperformula.handsontable.com/guide/date-and-time-handling.html#example
851
+ * https://hyperformula.handsontable.com/api/interfaces/configparams.html#nulldate
852
+ * NOTE: TODAY() is number of FULL days since nullDate. It will typically be -1 days from NOW().
853
+ */
854
+ toLocalDate(num) {
855
+ const { year, month, day, hours, minutes, seconds } = this.toDateTime(num);
856
+ return new Date(year, month - 1, day, hours, minutes, seconds);
857
+ }
858
+ toDateTime(num) {
859
+ return this._graph.hf.numberToDateTime(num);
860
+ }
861
+ toDate(num) {
862
+ return this._graph.hf.numberToDate(num);
863
+ }
864
+ toTime(num) {
865
+ return this._graph.hf.numberToTime(num);
866
+ }
867
+ };
868
+ // Annotate the CommonJS export names for ESM import in node:
869
+ 0 && (module.exports = {
870
+ ComputeGraphContextProvider,
871
+ SheetModel,
872
+ addressFromA1Notation,
873
+ addressToA1Notation,
874
+ columnLetter,
875
+ createComputeGraph,
876
+ inRange,
877
+ posEquals,
878
+ rangeToA1Notation,
879
+ useComputeGraph
880
+ });
881
+ //# sourceMappingURL=chunk-FCKJ4QRM.cjs.map