@univerjs/engine-formula 0.12.3 → 0.12.4-experimental.20251210-8d33c6e

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.
package/lib/facade.js CHANGED
@@ -1,15 +1,15 @@
1
- import { FBase as f, FUniver as d } from "@univerjs/core/facade";
2
- import { Inject as c, ICommandService as p, Injector as _, IConfigService as C } from "@univerjs/core";
3
- import { LexerTreeBuilder as v, SetFormulaCalculationStartMutation as l, SetFormulaCalculationStopMutation as S, SetFormulaCalculationNotificationMutation as m, GlobalComputingStatusService as x, ENGINE_FORMULA_CYCLE_REFERENCE_COUNT as h } from "@univerjs/engine-formula";
4
- import { firstValueFrom as g, race as E, filter as F, timer as B, map as I } from "rxjs";
5
- var T = Object.getOwnPropertyDescriptor, N = (e, t, r, i) => {
6
- for (var o = i > 1 ? void 0 : i ? T(t, r) : t, a = e.length - 1, u; a >= 0; a--)
7
- (u = e[a]) && (o = u(o) || o);
8
- return o;
9
- }, n = (e, t) => (r, i) => t(r, i, e);
10
- let s = class extends f {
11
- constructor(e, t, r, i) {
12
- super(), this._commandService = e, this._injector = t, this._lexerTreeBuilder = r, this._configService = i, this._initialize();
1
+ import { FBase as _, FUniver as C } from "@univerjs/core/facade";
2
+ import { Inject as u, ICommandService as v, Injector as h, IConfigService as x } from "@univerjs/core";
3
+ import { LexerTreeBuilder as g, SetFormulaCalculationStartMutation as m, SetFormulaCalculationStopMutation as F, SetFormulaCalculationNotificationMutation as d, GlobalComputingStatusService as E, ENGINE_FORMULA_CYCLE_REFERENCE_COUNT as y, SetFormulaCalculationResultMutation as T, SetFormulaStringBatchCalculationMutation as R, SetFormulaStringBatchCalculationResultMutation as M, SetFormulaDependencyCalculationMutation as D, SetFormulaDependencyCalculationResultMutation as I, SetCellFormulaDependencyCalculationMutation as b, SetCellFormulaDependencyCalculationResultMutation as B, SetQueryFormulaDependencyMutation as p, SetQueryFormulaDependencyResultMutation as f } from "@univerjs/engine-formula";
4
+ import { firstValueFrom as L, race as P, filter as w, timer as N, map as O } from "rxjs";
5
+ var j = Object.getOwnPropertyDescriptor, A = (e, t, i, r) => {
6
+ for (var n = r > 1 ? void 0 : r ? j(t, i) : t, a = e.length - 1, o; a >= 0; a--)
7
+ (o = e[a]) && (n = o(n) || n);
8
+ return n;
9
+ }, s = (e, t) => (i, r) => t(i, r, e);
10
+ let c = class extends _ {
11
+ constructor(e, t, i, r) {
12
+ super(), this._commandService = e, this._injector = t, this._lexerTreeBuilder = i, this._configService = r, this._initialize();
13
13
  }
14
14
  /**
15
15
  * @ignore
@@ -38,8 +38,8 @@ let s = class extends f {
38
38
  * console.log(result);
39
39
  * ```
40
40
  */
41
- moveFormulaRefOffset(e, t, r, i) {
42
- return this._lexerTreeBuilder.moveFormulaRefOffset(e, t, r, i);
41
+ moveFormulaRefOffset(e, t, i, r) {
42
+ return this._lexerTreeBuilder.moveFormulaRefOffset(e, t, i, r);
43
43
  }
44
44
  /**
45
45
  * Resolves the formula string to a 'node' node
@@ -66,7 +66,7 @@ let s = class extends f {
66
66
  * ```
67
67
  */
68
68
  executeCalculation() {
69
- this._commandService.executeCommand(l.id, { commands: [], forceCalculation: !0 }, { onlyLocal: !0 });
69
+ this._commandService.executeCommand(m.id, { commands: [], forceCalculation: !0 }, { onlyLocal: !0 });
70
70
  }
71
71
  /**
72
72
  * Stop the calculation of the formula.
@@ -78,7 +78,7 @@ let s = class extends f {
78
78
  * ```
79
79
  */
80
80
  stopCalculation() {
81
- this._commandService.executeCommand(S.id, {});
81
+ this._commandService.executeCommand(F.id, {});
82
82
  }
83
83
  /**
84
84
  * Listening calculation starts.
@@ -95,9 +95,9 @@ let s = class extends f {
95
95
  */
96
96
  calculationStart(e) {
97
97
  return this._commandService.onCommandExecuted((t) => {
98
- if (t.id === l.id) {
99
- const r = t.params;
100
- e(r.forceCalculation);
98
+ if (t.id === m.id) {
99
+ const i = t.params;
100
+ e(i.forceCalculation);
101
101
  }
102
102
  });
103
103
  }
@@ -116,10 +116,10 @@ let s = class extends f {
116
116
  */
117
117
  calculationEnd(e) {
118
118
  return this._commandService.onCommandExecuted((t) => {
119
- if (t.id !== m.id)
119
+ if (t.id !== d.id)
120
120
  return;
121
- const r = t.params;
122
- r.functionsExecutedState !== void 0 && e(r.functionsExecutedState);
121
+ const i = t.params;
122
+ i.functionsExecutedState !== void 0 && e(i.functionsExecutedState);
123
123
  });
124
124
  }
125
125
  /**
@@ -139,10 +139,10 @@ let s = class extends f {
139
139
  * ```
140
140
  */
141
141
  whenComputingCompleteAsync(e) {
142
- const t = this._injector.get(x);
143
- return t.computingStatus ? Promise.resolve(!0) : g(E(
144
- t.computingStatus$.pipe(F((r) => r)),
145
- B(e != null ? e : 3e4).pipe(I(() => !1))
142
+ const t = this._injector.get(E);
143
+ return t.computingStatus ? Promise.resolve(!0) : L(P(
144
+ t.computingStatus$.pipe(w((i) => i)),
145
+ N(e != null ? e : 3e4).pipe(O(() => !1))
146
146
  ));
147
147
  }
148
148
  /**
@@ -151,10 +151,10 @@ let s = class extends f {
151
151
  */
152
152
  onCalculationEnd() {
153
153
  return new Promise((e, t) => {
154
- const r = setTimeout(() => {
154
+ const i = setTimeout(() => {
155
155
  t(new Error("Calculation end timeout"));
156
- }, 3e4), i = this.calculationEnd(() => {
157
- clearTimeout(r), i.dispose(), e();
156
+ }, 3e4), r = this.calculationEnd(() => {
157
+ clearTimeout(i), r.dispose(), e();
158
158
  });
159
159
  });
160
160
  }
@@ -173,10 +173,10 @@ let s = class extends f {
173
173
  */
174
174
  calculationProcessing(e) {
175
175
  return this._commandService.onCommandExecuted((t) => {
176
- if (t.id !== m.id)
176
+ if (t.id !== d.id)
177
177
  return;
178
- const r = t.params;
179
- r.stageInfo !== void 0 && e(r.stageInfo);
178
+ const i = t.params;
179
+ i.stageInfo !== void 0 && e(i.stageInfo);
180
180
  });
181
181
  }
182
182
  /**
@@ -192,21 +192,322 @@ let s = class extends f {
192
192
  * ```
193
193
  */
194
194
  setMaxIteration(e) {
195
- this._configService.setConfig(h, e);
195
+ this._configService.setConfig(y, e);
196
+ }
197
+ /**
198
+ * Listens for the moment when formula-calculation results are applied.
199
+ *
200
+ * This event fires after the engine completes a calculation cycle and
201
+ * dispatches a `SetFormulaCalculationResultMutation`.
202
+ * The callback is invoked during an idle frame to avoid blocking UI updates.
203
+ *
204
+ * @param {Function} callback - A function called with the calculation result payload
205
+ * once the result-application mutation is emitted.
206
+ * @returns {IDisposable} A disposable used to unsubscribe from the event.
207
+ *
208
+ * @example
209
+ * ```ts
210
+ * const formulaEngine = univerAPI.getFormula();
211
+ *
212
+ * const dispose = formulaEngine.calculationResultApplied((result) => {
213
+ * console.log('Calculation results applied:', result);
214
+ * });
215
+ *
216
+ * // Later…
217
+ * dispose.dispose();
218
+ * ```
219
+ */
220
+ calculationResultApplied(e) {
221
+ return this._commandService.onCommandExecuted((t) => {
222
+ if (t.id !== T.id)
223
+ return;
224
+ const i = t.params;
225
+ i !== void 0 && requestIdleCallback(() => {
226
+ e(i);
227
+ });
228
+ });
229
+ }
230
+ /**
231
+ * Waits for formula-calculation results to be applied.
232
+ *
233
+ * This method resolves under three conditions:
234
+ * 1. A real calculation runs and the engine emits a "calculation started" signal,
235
+ * followed by a "calculation result applied" signal.
236
+ * 2. No calculation actually starts within 500 ms — the method assumes there is
237
+ * nothing to wait for and resolves automatically.
238
+ * 3. A global 30 s timeout triggers, in which case the promise rejects.
239
+ *
240
+ * The API internally listens to both “calculation in progress” events and
241
+ * “calculation result applied” events, ensuring it behaves correctly whether
242
+ * formulas are recalculated or skipped due to cache/state.
243
+ *
244
+ * @returns {Promise<void>} A promise that resolves when calculation results are applied
245
+ * or when no calculation occurs within the start-detection window.
246
+ *
247
+ * @example
248
+ * ```ts
249
+ * const formulaEngine = univerAPI.getFormula();
250
+ *
251
+ * // Wait for formula updates to apply before reading values.
252
+ * await formulaEngine.onCalculationResultApplied();
253
+ *
254
+ * const value = sheet.getRange("C24").getValue();
255
+ * console.log("Updated value:", value);
256
+ * ```
257
+ */
258
+ onCalculationResultApplied() {
259
+ return new Promise((e, t) => {
260
+ let i = !1, r = !1;
261
+ const n = setTimeout(() => {
262
+ l(), t(new Error("Calculation end timeout"));
263
+ }, 3e4), a = setTimeout(() => {
264
+ i || (l(), e());
265
+ }, 500), o = this.calculationProcessing(() => {
266
+ i || (i = !0, clearTimeout(a));
267
+ }), S = this.calculationResultApplied(() => {
268
+ r || (r = !0, l(), e());
269
+ });
270
+ function l() {
271
+ clearTimeout(n), clearTimeout(a), o.dispose(), S.dispose();
272
+ }
273
+ });
274
+ }
275
+ /**
276
+ * Execute a batch of formulas asynchronously and receive computed results.
277
+ *
278
+ * Each formula cell is represented as a string array:
279
+ * [fullFormula, ...subFormulas]
280
+ *
281
+ * Where:
282
+ * - fullFormula (index 0) is the complete formula expression written in the cell.
283
+ * Example: "=SUM(A1:A10) + SQRT(D7)".
284
+ *
285
+ * - subFormulas (index 1+) are **optional decomposed expressions** extracted from
286
+ * the full formula. Each of them can be independently computed by the formula engine.
287
+ *
288
+ * These sub-expressions can include:
289
+ * - Single-cell references: "A2", "B2", "C5"
290
+ * - Range references: "A1:A10"
291
+ * - Function calls: "SQRT(D7)", "ABS(A2-B2)"
292
+ * - Any sub-formula that was parsed out of the original formula and can be
293
+ * evaluated on its own.
294
+ *
295
+ * The batch execution engine may use these sub-formulas for dependency resolution,
296
+ * incremental computation, or performance optimizations.
297
+ *
298
+ * @param {IFormulaStringMap} formulas
299
+ * Nested structure (unit → sheet → row → column) describing formulas and
300
+ * their decomposed sub-expressions.
301
+ *
302
+ * @param {(result: IFormulaExecuteResultMap) => void} callback
303
+ * Receives the computed value map mirroring the input structure.
304
+ *
305
+ * @returns {IDisposable}
306
+ * A disposer to stop listening for batch results.
307
+ *
308
+ * @example
309
+ * ```ts
310
+ * const formulaEngine = univerAPI.getFormula();
311
+ * const formulas = {
312
+ * Book1: {
313
+ * Sheet1: {
314
+ * 2: {
315
+ * 3: [
316
+ * // Full formula:
317
+ * "=SUM(A1:A10) + SQRT(D7)",
318
+ *
319
+ * // Decomposed sub-formulas (each one can be evaluated independently):
320
+ * "SUM(A1:A10)", // sub-formula 1
321
+ * "SQRT(D7)", // sub-formula 2
322
+ * "A1:A10", // range reference
323
+ * "D7", // single-cell reference
324
+ * ],
325
+ * },
326
+ * 4: {
327
+ * 5: [
328
+ * "=A2 + B2 + SQRT(C5)",
329
+ * "A2",
330
+ * "B2",
331
+ * "SQRT(C5)",
332
+ * ],
333
+ * }
334
+ * },
335
+ * },
336
+ * };
337
+ *
338
+ * const disposer = formulaEngine.executeFormulas(formulas, (result) => {
339
+ * console.log(result);
340
+ * });
341
+ *
342
+ * ```
343
+ */
344
+ executeFormulas(e, t) {
345
+ this._commandService.executeCommand(R.id, { formulas: e }, { onlyLocal: !0 });
346
+ const i = this._commandService.onCommandExecuted((r) => {
347
+ if (r.id !== M.id)
348
+ return;
349
+ const n = r.params;
350
+ n.result != null && t(n.result), i.dispose();
351
+ });
352
+ }
353
+ /**
354
+ * Retrieve all formula dependency trees that were produced during the latest
355
+ * dependency-analysis run. This triggers a local dependency-calculation command
356
+ * and returns the complete set of dependency trees once the calculation finishes.
357
+ *
358
+ * @param callback A function invoked with the resulting array of dependency trees.
359
+ *
360
+ * @returns {IDisposable} An object that disposes the internal event listener.
361
+ *
362
+ * @example
363
+ * ```ts
364
+ * const formulaEngine = univerAPI.getFormula();
365
+ *
366
+ * // Fetch all dependency trees generated for the current workbook.
367
+ * const disposable = formulaEngine.getAllDependencyTrees((trees) => {
368
+ * console.log('All dependency trees:', trees);
369
+ * });
370
+ *
371
+ * ```
372
+ */
373
+ getAllDependencyTrees(e) {
374
+ this._commandService.executeCommand(D.id, void 0, { onlyLocal: !0 });
375
+ const t = this._commandService.onCommandExecuted((i) => {
376
+ if (i.id !== I.id)
377
+ return;
378
+ const r = i.params;
379
+ r.result != null && e(r.result), t.dispose();
380
+ });
381
+ }
382
+ /**
383
+ * Retrieve the dependency tree of a specific cell. This triggers a local
384
+ * dependency-calculation command for the given unit, sheet, and cell location,
385
+ * and returns the computed dependency tree when the calculation is completed.
386
+ *
387
+ * @param param The target cell location:
388
+ * - `unitId` The workbook ID.
389
+ * - `sheetId` The sheet ID.
390
+ * - `row` The zero-based row index.
391
+ * - `column` The zero-based column index.
392
+ *
393
+ * @param callback A function invoked with the resulting dependency tree or
394
+ * `undefined` if no dependency tree exists for that cell.
395
+ *
396
+ * @returns {IDisposable} An object that disposes the internal event listener.
397
+ *
398
+ * @example
399
+ * ```ts
400
+ * const formulaEngine = univerAPI.getFormula();
401
+ *
402
+ * // Query the dependency tree for cell B2 in a specific sheet.
403
+ * const disposable = formulaEngine.getCellDependencyTree(
404
+ * { unitId: 'workbook1', sheetId: 'sheet1', row: 1, column: 1 },
405
+ * (tree) => {
406
+ * console.log('Cell dependency tree:', tree);
407
+ * }
408
+ * );
409
+ *
410
+ * ```
411
+ */
412
+ getCellDependencyTree(e, t) {
413
+ this._commandService.executeCommand(b.id, e, { onlyLocal: !0 });
414
+ const i = this._commandService.onCommandExecuted((r) => {
415
+ if (r.id !== B.id)
416
+ return;
417
+ const n = r.params;
418
+ n.result !== void 0 && t(n.result), i.dispose();
419
+ });
420
+ }
421
+ /**
422
+ * Retrieve the full dependency trees for all formulas that *depend on* the
423
+ * specified ranges. This triggers a local dependency-calculation command and
424
+ * invokes the callback once the calculation completes.
425
+ *
426
+ * @param unitRanges An array of workbook/sheet ranges to query. Each range
427
+ * includes:
428
+ * - `unitId` The workbook ID.
429
+ * - `sheetId` The sheet ID.
430
+ * - `range` The row/column boundaries.
431
+ *
432
+ * @param callback A function invoked with an array of `IFormulaDependencyTreeJson`
433
+ * results. Each entry represents a formula node and its parent/child
434
+ * relationships within the dependency graph.
435
+ *
436
+ * @example
437
+ * ```ts
438
+ * const formulaEngine = univerAPI.getFormula();
439
+ *
440
+ * // Query all formulas that depend on A1:B10 in Sheet1.
441
+ * formulaEngine.getRangeDependents(
442
+ * [{ unitId: 'workbook1', sheetId: 'sheet1', range: { startRow: 0, endRow: 9, startColumn: 0, endColumn: 1 } }],
443
+ * (result) => {
444
+ * console.log('Dependent formulas:', result);
445
+ * }
446
+ * );
447
+ * ```
448
+ */
449
+ getRangeDependents(e, t) {
450
+ this._commandService.executeCommand(p.id, { unitRanges: e }, { onlyLocal: !0 });
451
+ const i = this._commandService.onCommandExecuted((r) => {
452
+ if (r.id !== f.id)
453
+ return;
454
+ const n = r.params;
455
+ n.result != null && t(n.result), i.dispose();
456
+ });
457
+ }
458
+ /**
459
+ * Retrieve the dependency trees of all formulas *inside* the specified ranges.
460
+ * Unlike `getRangeDependents`, this API only returns formulas whose definitions
461
+ * physically reside within the queried ranges.
462
+ *
463
+ * Internally this triggers the same dependency-calculation command but with
464
+ * `isInRange = true`, and the callback is invoked when the results are ready.
465
+ *
466
+ * @param unitRanges An array of workbook/sheet ranges defining the lookup
467
+ * boundaries:
468
+ * - `unitId` The workbook ID.
469
+ * - `sheetId` The sheet ID.
470
+ * - `range` The zero-based grid range.
471
+ *
472
+ * @param callback Receives an array of `IFormulaDependencyTreeJson` describing
473
+ * every formula found in the provided ranges along with their parent/child
474
+ * relationships.
475
+ *
476
+ * @example
477
+ * ```ts
478
+ * const formulaEngine = univerAPI.getFormula();
479
+ *
480
+ * // Query all formulas that lie within A1:D20 in Sheet1.
481
+ * formulaEngine.getInRangeFormulas(
482
+ * [{ unitId: 'workbook1', sheetId: 'sheet1', range: { startRow: 0, endRow: 19, startColumn: 0, endColumn: 3 } }],
483
+ * (result) => {
484
+ * console.log('Formulas inside range:', result);
485
+ * }
486
+ * );
487
+ * ```
488
+ */
489
+ getInRangeFormulas(e, t) {
490
+ this._commandService.executeCommand(p.id, { unitRanges: e, isInRange: !0 }, { onlyLocal: !0 });
491
+ const i = this._commandService.onCommandExecuted((r) => {
492
+ if (r.id !== f.id)
493
+ return;
494
+ const n = r.params;
495
+ n.result != null && t(n.result), i.dispose();
496
+ });
196
497
  }
197
498
  };
198
- s = N([
199
- n(0, c(p)),
200
- n(1, c(_)),
201
- n(2, c(v)),
202
- n(3, C)
203
- ], s);
204
- class O extends d {
499
+ c = A([
500
+ s(0, u(v)),
501
+ s(1, u(h)),
502
+ s(2, u(g)),
503
+ s(3, x)
504
+ ], c);
505
+ class U extends C {
205
506
  getFormula() {
206
- return this._injector.createInstance(s);
507
+ return this._injector.createInstance(c);
207
508
  }
208
509
  }
209
- d.extend(O);
510
+ C.extend(U);
210
511
  export {
211
- s as FFormula
512
+ c as FFormula
212
513
  };