Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(facade): fix onCalculationResultApplied api used with worker (#6947)

wpxp123456105306d352d4
diff --git a/packages/engine-formula/src/facade/f-formula.ts b/packages/engine-formula/src/facade/f-formula.ts
index 5f120e8685..fe28e07b8d 100644
--- a/packages/engine-formula/src/facade/f-formula.ts
+++ b/packages/engine-formula/src/facade/f-formula.ts
@@ -204,7 +204,7 @@ export class FFormula extends FBase {
}
/**
- * @deprecated Use `onCalculationEnd` instead.
+ * @deprecated Use `onCalculationResultApplied` instead.
*/
whenComputingCompleteAsync(timeout?: number): Promise<boolean> {
const gcss = this._injector.get(GlobalComputingStatusService);
@@ -217,8 +217,7 @@ export class FFormula extends FBase {
}
/**
- * Waits for the formula calculation to complete.
- * @returns {Promise<void>} This method returns a promise that resolves when the calculation is complete.
+ * @deprecated Use `onCalculationResultApplied` instead.
*/
onCalculationEnd(): Promise<void> {
return new Promise((resolve, reject) => {
diff --git a/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.ts b/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.ts
index 557a1021c6..f10176f8d7 100644
--- a/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.ts
+++ b/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.ts
@@ -42,7 +42,7 @@ import {
SheetsSelectionsService,
} from '@univerjs/sheets';
import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';
-import { DescriptionService, IDescriptionService, IRegisterFunctionService, RegisterFunctionService } from '@univerjs/sheets-formula';
+import { DescriptionService, FormulaCalculationSessionController, FormulaCalculationSessionService, IDescriptionService, IRegisterFunctionService, RegisterFunctionService } from '@univerjs/sheets-formula';
import enUS from '@univerjs/sheets/locale/en-US';
import zhCN from '@univerjs/sheets/locale/zh-CN';
@@ -147,6 +147,8 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
injector.add([ISuperTableService, { useClass: SuperTableService }]);
injector.add([IDescriptionService, { useClass: DescriptionService }]);
injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);
+ injector.add([FormulaCalculationSessionService]);
+ injector.add([FormulaCalculationSessionController]);
// register feature modules
([
@@ -165,6 +167,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
dependencies?.forEach((d) => injector.add(d));
this._injector.get(SheetInterceptorService);
+ this._injector.get(FormulaCalculationSessionController);
this._injector.get(ConditionalFormattingService);
this._injector.get(ConditionalFormattingViewModel);
}
diff --git a/packages/sheets-conditional-formatting/src/facade/__tests__/f-conditional-formatting.spec.ts b/packages/sheets-conditional-formatting/src/facade/__tests__/f-conditional-formatting.spec.ts
index d1c0b45932..d88e09aeb0 100644
--- a/packages/sheets-conditional-formatting/src/facade/__tests__/f-conditional-formatting.spec.ts
+++ b/packages/sheets-conditional-formatting/src/facade/__tests__/f-conditional-formatting.spec.ts
@@ -17,7 +17,7 @@
import type { Injector, Univer } from '@univerjs/core';
import type { FUniver } from '@univerjs/core/facade';
import { ICommandService } from '@univerjs/core/services/command/command.service.js';
-import { FormulaExecuteStageType, RemoveOtherFormulaMutation, SetFormulaCalculationResultMutation } from '@univerjs/engine-formula';
+import { FormulaExecuteStageType, RemoveOtherFormulaMutation, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
import { SetSelectionsOperation } from '@univerjs/sheets';
import {
AddCfCommand,
@@ -63,6 +63,8 @@ describe('Test conditional formatting facade', () => {
SetCfCommand,
SetSelectionsOperation,
RemoveOtherFormulaMutation,
+ SetFormulaCalculationStartMutation,
+ SetFormulaCalculationNotificationMutation,
SetFormulaCalculationResultMutation,
].forEach((m) => {
commandService.registerCommand(m);
@@ -164,19 +166,6 @@ describe('Test conditional formatting facade', () => {
const subUnitId = worksheet.getSheetId();
const formula = univerAPI.getFormula();
- vi.spyOn(formula, 'calculationProcessing').mockImplementation((callback) => {
- callback({
- stage: FormulaExecuteStageType.START_CALCULATION,
- completedFormulasCount: 0,
- completedArrayFormulasCount: 0,
- formulaCycleIndex: 0,
- totalArrayFormulasToCalculate: 0,
- totalFormulasToCalculate: 1,
- });
-
- return { dispose: () => {} };
- });
-
await univerAPI.executeCommand('sheet.mutation.add-conditional-rule', {
unitId,
subUnitId,
@@ -215,6 +204,18 @@ describe('Test conditional formatting facade', () => {
const waitForResult = formula.onCalculationResultApplied();
+ await commandService.executeCommand(SetFormulaCalculationStartMutation.id, {}, { onlyLocal: true });
+ await commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {
+ stageInfo: {
+ stage: FormulaExecuteStageType.START_CALCULATION,
+ completedFormulasCount: 0,
+ completedArrayFormulasCount: 0,
+ formulaCycleIndex: 0,
+ totalArrayFormulasToCalculate: 0,
+ totalFormulasToCalculate: 1,
+ },
+ });
+
await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {
unitData: {},
unitOtherData: {
diff --git a/packages/sheets-data-validation/src/facade/__tests__/create-test-bed.ts b/packages/sheets-data-validation/src/facade/__tests__/create-test-bed.ts
index 2f499d2367..5ea18a2cdd 100644
--- a/packages/sheets-data-validation/src/facade/__tests__/create-test-bed.ts
+++ b/packages/sheets-data-validation/src/facade/__tests__/create-test-bed.ts
@@ -39,7 +39,7 @@ import {
SheetsSelectionsService,
} from '@univerjs/sheets';
import { DataValidationCacheService, DataValidationCustomFormulaService, DataValidationFormulaService, DataValidationListCacheService, SheetDataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
-import { DescriptionService, IDescriptionService, IRegisterFunctionService, RegisterFunctionService } from '@univerjs/sheets-formula';
+import { DescriptionService, FormulaCalculationSessionController, FormulaCalculationSessionService, IDescriptionService, IRegisterFunctionService, RegisterFunctionService } from '@univerjs/sheets-formula';
import enUS from '@univerjs/sheets/locale/en-US';
import zhCN from '@univerjs/sheets/locale/zh-CN';
import { DataValidationController } from '../../controllers/dv.controller';
@@ -130,6 +130,8 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
injector.add([ISuperTableService, { useClass: SuperTableService }]);
injector.add([IDescriptionService, { useClass: DescriptionService }]);
injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);
+ injector.add([FormulaCalculationSessionService]);
+ injector.add([FormulaCalculationSessionController]);
// register feature modules
([
@@ -151,6 +153,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
dependencies?.forEach((d) => injector.add(d));
this._injector.get(SheetInterceptorService);
+ this._injector.get(FormulaCalculationSessionController);
this._injector.get(DataValidationController);
}
diff --git a/packages/sheets-data-validation/src/facade/__tests__/f-range.spec.ts b/packages/sheets-data-validation/src/facade/__tests__/f-range.spec.ts
index de08b3dec0..fe2b973ac3 100644
--- a/packages/sheets-data-validation/src/facade/__tests__/f-range.spec.ts
+++ b/packages/sheets-data-validation/src/facade/__tests__/f-range.spec.ts
@@ -19,7 +19,7 @@
import type { Injector } from '@univerjs/core';
import type { FUniver } from '@univerjs/core/facade';
import { DataValidationType, ICommandService } from '@univerjs/core';
-import { FormulaExecuteStageType, SetFormulaCalculationResultMutation } from '@univerjs/engine-formula';
+import { FormulaExecuteStageType, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
import { AddSheetDataValidationCommand, DataValidationCustomFormulaService } from '@univerjs/sheets-data-validation';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createFacadeTestBed } from './create-test-bed';
@@ -39,6 +39,8 @@ describe('Test FRange', () => {
commandService = get(ICommandService);
commandService.registerCommand(AddSheetDataValidationCommand);
+ commandService.registerCommand(SetFormulaCalculationStartMutation);
+ commandService.registerCommand(SetFormulaCalculationNotificationMutation);
commandService.registerCommand(SetFormulaCalculationResultMutation);
vi.stubGlobal('requestIdleCallback', ((callback: IdleRequestCallback) => {
@@ -79,19 +81,6 @@ describe('Test FRange', () => {
const range = activeSheet.getRange(0, 0, 1, 1);
const formula = univerAPI.getFormula();
- vi.spyOn(formula, 'calculationProcessing').mockImplementation((callback) => {
- callback({
- stage: FormulaExecuteStageType.START_CALCULATION,
- completedFormulasCount: 0,
- completedArrayFormulasCount: 0,
- formulaCycleIndex: 0,
- totalArrayFormulasToCalculate: 0,
- totalFormulasToCalculate: 1,
- });
-
- return { dispose: () => {} };
- });
-
const rule = univerAPI.newDataValidation()
.requireFormulaSatisfied('=A1>0')
.build();
@@ -104,6 +93,18 @@ describe('Test FRange', () => {
const waitForResult = formula.onCalculationResultApplied();
+ await commandService.executeCommand(SetFormulaCalculationStartMutation.id, {}, { onlyLocal: true });
+ await commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {
+ stageInfo: {
+ stage: FormulaExecuteStageType.START_CALCULATION,
+ completedFormulasCount: 0,
+ completedArrayFormulasCount: 0,
+ formulaCycleIndex: 0,
+ totalArrayFormulasToCalculate: 0,
+ totalFormulasToCalculate: 1,
+ },
+ });
+
await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {
unitData: {},
unitOtherData: {
diff --git a/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts
index 4b241a9319..ff460e137d 100644
--- a/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts
@@ -42,6 +42,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from '../../config/config';
import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';
+import { FormulaCalculationSessionService } from '../../services/formula-calculation-session.service';
+import { FormulaCalculationSessionController } from '../formula-calculation-session.controller';
import { TriggerCalculationController } from '../trigger-calculation.controller';
function createWorkbookData(): IWorkbookData {
@@ -72,6 +74,8 @@ function createControllerTestBed() {
const dependencies: Dependency[] = [
[IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],
[RegisterOtherFormulaService],
+ [FormulaCalculationSessionService],
+ [FormulaCalculationSessionController],
[TriggerCalculationController],
];
@@ -118,6 +122,7 @@ function createControllerTestBed() {
});
});
+ injector.get(FormulaCalculationSessionController);
const controller = injector.get(TriggerCalculationController);
return {
diff --git a/packages/sheets-formula/src/controllers/formula-calculation-session.controller.ts b/packages/sheets-formula/src/controllers/formula-calculation-session.controller.ts
new file mode 100644
index 0000000000..aecce07916
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/formula-calculation-session.controller.ts
@@ -0,0 +1,79 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo } from '@univerjs/core';
+import type { ISetFormulaCalculationNotificationMutation, ISetFormulaCalculationResultMutation } from '@univerjs/engine-formula';
+import { Disposable, ICommandService, Inject } from '@univerjs/core';
+import {
+ SetFormulaCalculationNotificationMutation,
+ SetFormulaCalculationResultMutation,
+ SetFormulaCalculationStartMutation,
+} from '@univerjs/engine-formula';
+import { SetRangeValuesMutation } from '@univerjs/sheets';
+import { FormulaCalculationSessionService } from '../services/formula-calculation-session.service';
+
+export class FormulaCalculationSessionController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(FormulaCalculationSessionService) private readonly _sessionService: FormulaCalculationSessionService
+ ) {
+ super();
+
+ this._sessionService.initialize();
+ this._initialize();
+ }
+
+ private _initialize(): void {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo, options) => {
+ if (command.id === SetFormulaCalculationStartMutation.id) {
+ this._sessionService.start();
+ return;
+ }
+
+ if (command.id === SetFormulaCalculationNotificationMutation.id) {
+ const params = command.params as ISetFormulaCalculationNotificationMutation;
+ if (params.stageInfo != null) {
+ this._sessionService.updateProgress(params.stageInfo);
+ }
+
+ if (params.functionsExecutedState !== undefined) {
+ this._sessionService.markCompleted(params.functionsExecutedState);
+ }
+
+ return;
+ }
+
+ if (command.id === SetFormulaCalculationResultMutation.id) {
+ const params = command.params as ISetFormulaCalculationResultMutation;
+ this._sessionService.markResultEmitted(params, this._hasFormulaResultToApply(params));
+ return;
+ }
+
+ if (command.id === SetRangeValuesMutation.id && options?.applyFormulaCalculationResult) {
+ this._sessionService.markResultApplied();
+ }
+ })
+ );
+ }
+
+ private _hasFormulaResultToApply(result: ISetFormulaCalculationResultMutation): boolean {
+ const { unitData } = result;
+ return Object.values(unitData ?? {}).some((sheetData) =>
+ sheetData != null && Object.values(sheetData).some((cellData) => cellData != null)
+ );
+ }
+}
diff --git a/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts
index 9feb907643..a80edffef4 100644
--- a/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts
+++ b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts
@@ -16,11 +16,13 @@
import type { Injector } from '@univerjs/core';
import type { FUniver } from '@univerjs/core/facade';
-import { CommandType, ICommandService, IConfigService, LifecycleService, LifecycleStages } from '@univerjs/core';
-import { FormulaExecuteStageType, IFunctionService, ISuperTableService, SetFormulaCalculationResultMutation, SetTriggerFormulaCalculationStartMutation, SuperTableService } from '@univerjs/engine-formula';
+import { ICommandService, IConfigService, LifecycleService, LifecycleStages } from '@univerjs/core';
+import { FormulaExecutedStateType, FormulaExecuteStageType, IFunctionService, ISuperTableService, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation, SetTriggerFormulaCalculationStartMutation, SuperTableService } from '@univerjs/engine-formula';
import { SetRangeValuesMutation } from '@univerjs/sheets';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { FormulaCalculationSessionController } from '../../controllers/formula-calculation-session.controller';
import { CalculationMode, DescriptionService, IDescriptionService, IRegisterFunctionService, PLUGIN_CONFIG_KEY_BASE, RegisterFunctionService } from '../../index';
+import { FormulaCalculationSessionService } from '../../services/formula-calculation-session.service';
import { createFacadeTestBed } from './create-test-bed';
import '@univerjs/engine-formula/facade';
@@ -30,6 +32,7 @@ import '../../facade';
describe('sheets-formula facade mixins', () => {
let get: Injector['get'];
let univerAPI: FUniver;
+ let commandService: ICommandService;
let disposeUniver: () => void;
beforeEach(() => {
@@ -37,10 +40,20 @@ describe('sheets-formula facade mixins', () => {
testBed.injector.add([IDescriptionService, { useClass: DescriptionService }]);
testBed.injector.add([ISuperTableService, { useClass: SuperTableService }]);
testBed.injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);
+ testBed.injector.add([FormulaCalculationSessionService]);
+ testBed.injector.add([FormulaCalculationSessionController]);
+ testBed.injector.get(FormulaCalculationSessionService);
+ testBed.injector.get(FormulaCalculationSessionController);
get = testBed.get;
univerAPI = testBed.univerAPI;
disposeUniver = () => testBed.univer.dispose();
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetFormulaCalculationStartMutation);
+ commandService.registerCommand(SetFormulaCalculationNotificationMutation);
+ commandService.registerCommand(SetFormulaCalculationResultMutation);
+ commandService.registerCommand(SetRangeValuesMutation);
});
afterEach(() => {
@@ -52,7 +65,6 @@ describe('sheets-formula facade mixins', () => {
it('registers functions through FUniver and FFormula and triggers a debounced recalculation command', async () => {
vi.useFakeTimers();
- const commandService = get(ICommandService);
const functionService = get(IFunctionService);
const executeCommandSpy = vi.spyOn(commandService, 'executeCommand').mockResolvedValue(true);
@@ -118,10 +130,6 @@ describe('sheets-formula facade mixins', () => {
return 1;
}) as typeof requestIdleCallback);
- const commandService = get(ICommandService);
- commandService.registerCommand(SetFormulaCalculationResultMutation);
- commandService.registerCommand(SetRangeValuesMutation);
-
const formula = univerAPI.getFormula();
const resultPayload = {
unitData: {},
@@ -155,10 +163,6 @@ describe('sheets-formula facade mixins', () => {
return 1;
}) as typeof requestIdleCallback);
- const commandService = get(ICommandService);
- commandService.registerCommand(SetFormulaCalculationResultMutation);
- commandService.registerCommand(SetRangeValuesMutation);
-
const formula = univerAPI.getFormula();
const resultPayload = {
unitData: {
@@ -195,6 +199,58 @@ describe('sheets-formula facade mixins', () => {
});
});
+ it('fires calculationResultApplied once for repeated range apply notifications', async () => {
+ vi.stubGlobal('requestIdleCallback', ((callback: IdleRequestCallback) => {
+ callback({ didTimeout: false, timeRemaining: () => 16 } as IdleDeadline);
+ return 1;
+ }) as typeof requestIdleCallback);
+
+ const formula = univerAPI.getFormula();
+ const resultPayload = {
+ unitData: {
+ unit1: {
+ sheet1: {
+ 0: {
+ 0: { v: 1 },
+ },
+ },
+ },
+ },
+ unitOtherData: {},
+ };
+ const callback = vi.fn();
+ const disposable = formula.calculationResultApplied(callback);
+
+ await commandService.executeCommand(SetFormulaCalculationResultMutation.id, resultPayload);
+ await commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ {
+ unitId: 'unit1',
+ subUnitId: 'sheet1',
+ cellValue: {},
+ },
+ {
+ applyFormulaCalculationResult: true,
+ }
+ );
+ await commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ {
+ unitId: 'unit1',
+ subUnitId: 'sheet1',
+ cellValue: {},
+ },
+ {
+ applyFormulaCalculationResult: true,
+ }
+ );
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(callback).toHaveBeenCalledWith(resultPayload);
+
+ disposable.dispose();
+ });
+
it('resolves onCalculationResultApplied when no calculation actually starts', async () => {
vi.useFakeTimers();
@@ -213,25 +269,21 @@ describe('sheets-formula facade mixins', () => {
return 1;
}) as typeof requestIdleCallback);
- const commandService = get(ICommandService);
- commandService.registerCommand(SetFormulaCalculationResultMutation);
-
const formula = univerAPI.getFormula();
- vi.spyOn(formula, 'calculationProcessing').mockImplementation((callback) => {
- callback({
+ const waitForResult = formula.onCalculationResultApplied();
+
+ await commandService.executeCommand(SetFormulaCalculationStartMutation.id, {}, { onlyLocal: true });
+ await commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {
+ stageInfo: {
stage: FormulaExecuteStageType.START_CALCULATION,
completedFormulasCount: 0,
completedArrayFormulasCount: 0,
formulaCycleIndex: 0,
totalArrayFormulasToCalculate: 0,
totalFormulasToCalculate: 1,
- });
-
- return { dispose: () => {} };
+ },
});
- const waitForResult = formula.onCalculationResultApplied();
-
await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {
unitData: {},
unitOtherData: {
@@ -250,34 +302,85 @@ describe('sheets-formula facade mixins', () => {
await expect(waitForResult).resolves.toBeUndefined();
});
- it('rejects onCalculationResultApplied when the wait exceeds the global timeout', async () => {
+ it('resolves onCalculationResultApplied after the latest restarted calculation is applied', async () => {
vi.useFakeTimers();
- const commandService = get(ICommandService);
- commandService.registerCommand({
- id: SetFormulaCalculationResultMutation.id,
- type: CommandType.MUTATION,
- handler: () => true,
+ const formula = univerAPI.getFormula();
+ const waitForResult = formula.onCalculationResultApplied();
+ let resolved = false;
+ void waitForResult.then(() => {
+ resolved = true;
+ });
+
+ await commandService.executeCommand(SetFormulaCalculationStartMutation.id, {}, { onlyLocal: true });
+ await commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {
+ stageInfo: {
+ stage: FormulaExecuteStageType.CURRENTLY_CALCULATING,
+ completedFormulasCount: 0,
+ completedArrayFormulasCount: 0,
+ formulaCycleIndex: 0,
+ totalArrayFormulasToCalculate: 0,
+ totalFormulasToCalculate: 1,
+ },
+ });
+ await commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {
+ functionsExecutedState: FormulaExecutedStateType.STOP_EXECUTION,
+ });
+
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ await commandService.executeCommand(SetFormulaCalculationStartMutation.id, {}, { onlyLocal: true });
+ await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {
+ unitData: {
+ unit1: {
+ sheet1: {
+ 0: {
+ 0: { v: 1 },
+ },
+ },
+ },
+ },
+ unitOtherData: {},
});
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ await commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ {
+ unitId: 'unit1',
+ subUnitId: 'sheet1',
+ cellValue: {},
+ },
+ {
+ applyFormulaCalculationResult: true,
+ }
+ );
+
+ await expect(waitForResult).resolves.toBeUndefined();
+ });
+
+ it('rejects onCalculationResultApplied when an explicit timeout is exceeded', async () => {
+ vi.useFakeTimers();
+
const formula = univerAPI.getFormula();
- vi.spyOn(formula, 'calculationProcessing').mockImplementation((callback) => {
- callback({
+ const waitForResult = expect(formula.onCalculationResultApplied(1000)).rejects.toThrowError('Calculation end timeout');
+
+ await commandService.executeCommand(SetFormulaCalculationStartMutation.id, {}, { onlyLocal: true });
+ await commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {
+ stageInfo: {
stage: FormulaExecuteStageType.START_CALCULATION,
completedFormulasCount: 0,
completedArrayFormulasCount: 0,
formulaCycleIndex: 0,
totalArrayFormulasToCalculate: 1,
totalFormulasToCalculate: 1,
- });
-
- return { dispose: () => {} };
+ },
});
- vi.spyOn(formula, 'calculationResultApplied').mockReturnValue({ dispose: () => {} });
-
- const waitForResult = expect(formula.onCalculationResultApplied()).rejects.toThrowError('Calculation end timeout');
- await vi.advanceTimersByTimeAsync(60_000);
+ await vi.advanceTimersByTimeAsync(1000);
await waitForResult;
});
diff --git a/packages/sheets-formula/src/facade/f-formula.ts b/packages/sheets-formula/src/facade/f-formula.ts
index 2f295f4fcc..301b461e1c 100644
--- a/packages/sheets-formula/src/facade/f-formula.ts
+++ b/packages/sheets-formula/src/facade/f-formula.ts
@@ -14,14 +14,13 @@
* limitations under the License.
*/
-import type { ICommandInfo, IDisposable, ILocales } from '@univerjs/core';
+import type { IDisposable, ILocales } from '@univerjs/core';
import type { IFunctionInfo, ISetFormulaCalculationResultMutation } from '@univerjs/engine-formula';
import type { CalculationMode, IRegisterAsyncFunction, IRegisterFunction, ISingleFunctionRegisterParams, IUniverSheetsFormulaBaseConfig } from '@univerjs/sheets-formula';
import { debounce, IConfigService, ILogService, LifecycleService, LifecycleStages } from '@univerjs/core';
-import { FormulaExecuteStageType, SetFormulaCalculationResultMutation, SetTriggerFormulaCalculationStartMutation } from '@univerjs/engine-formula';
+import { SetTriggerFormulaCalculationStartMutation } from '@univerjs/engine-formula';
import { FFormula } from '@univerjs/engine-formula/facade';
-import { SetRangeValuesMutation } from '@univerjs/sheets';
-import { IRegisterFunctionService, PLUGIN_CONFIG_KEY_BASE, RegisterFunctionService } from '@univerjs/sheets-formula';
+import { FormulaCalculationSessionService, IRegisterFunctionService, PLUGIN_CONFIG_KEY_BASE, RegisterFunctionService } from '@univerjs/sheets-formula';
/**
* @ignore
@@ -300,17 +299,13 @@ export interface IFFormulaSheetsMixin {
/**
* Waits for formula-calculation results to be applied.
*
- * This method resolves under three conditions:
- * 1. A real calculation runs and the engine emits a "calculation started" signal,
- * followed by a "calculation result applied" signal.
- * 2. No calculation actually starts within 500 ms — the method assumes there is
- * nothing to wait for and resolves automatically.
- * 3. A global 30 s timeout triggers, in which case the promise rejects.
- *
- * The API internally listens to both “calculation in progress” events and
- * “calculation result applied” events, ensuring it behaves correctly whether
- * formulas are recalculated or skipped due to cache/state.
+ * The API follows the latest formula-calculation session. If a running
+ * calculation is stopped and immediately restarted, the promise waits for
+ * the restarted session to apply its results.
*
+ * @param {number} [timeout] Optional timeout in milliseconds. If omitted,
+ * the promise waits until calculation results are applied or no calculation
+ * occurs within the start-detection window.
* @returns {Promise<void>} A promise that resolves when calculation results are applied
* or when no calculation occurs within the start-detection window.
*
@@ -325,7 +320,7 @@ export interface IFFormulaSheetsMixin {
* console.log("Updated value:", value);
* ```
*/
- onCalculationResultApplied(): Promise<void>;
+ onCalculationResultApplied(timeout?: number): Promise<void>;
}
export class FFormulaSheetsMixin extends FFormula implements IFFormulaSheetsMixin {
@@ -427,95 +422,19 @@ export class FFormulaSheetsMixin extends FFormula implements IFFormulaSheetsMixi
}
override calculationResultApplied(callback: (result: ISetFormulaCalculationResultMutation) => void): IDisposable {
- let setFormulaCalculationResult = false;
- let applyFormulaCalculationResult = false;
- let result: ISetFormulaCalculationResultMutation | null = null;
-
- return this._commandService.onCommandExecuted((command: ICommandInfo, options) => {
- if (command.id !== SetFormulaCalculationResultMutation.id && command.id !== SetRangeValuesMutation.id) {
- return;
- }
-
- if (command.id === SetFormulaCalculationResultMutation.id) {
- setFormulaCalculationResult = true;
- result = command.params as ISetFormulaCalculationResultMutation;
- applyFormulaCalculationResult = applyFormulaCalculationResult || !this._hasFormulaResultToApply(result);
- }
-
- if (command.id === SetRangeValuesMutation.id && options?.applyFormulaCalculationResult) {
- applyFormulaCalculationResult = true;
- }
-
- if (!setFormulaCalculationResult || !applyFormulaCalculationResult) {
- return;
- }
-
+ const subscription = this._injector.get(FormulaCalculationSessionService).resultApplied$.subscribe((result) => {
requestIdleCallback(() => {
- callback(result!);
+ callback(result);
});
});
- }
- private _hasFormulaResultToApply(result: ISetFormulaCalculationResultMutation): boolean {
- const { unitData } = result;
- return Object.values(unitData ?? {}).some((sheetData) =>
- sheetData != null && Object.values(sheetData).some((cellData) => cellData != null)
- );
+ return {
+ dispose: () => subscription.unsubscribe(),
+ };
}
- override onCalculationResultApplied(): Promise<void> {
- return new Promise((resolve, reject) => {
- let started = false;
- let finished = false;
-
- // Global timeout: reject if the whole calculation hangs
- const mainTimer = setTimeout(() => {
- cleanup();
- reject(new Error('Calculation end timeout'));
- }, 60_000);
-
- // Watchdog: if no "calculation started" signal is received within 500ms,
- // assume there is no real calculation running and resolve immediately.
- const startWatchdog = setTimeout(() => {
- if (!started) {
- cleanup();
- resolve();
- }
- }, 500);
-
- // Listen for "calculation in progress" signal (stageInfo)
- const processingDisposable = this.calculationProcessing((stageInfo) => {
- // If no formulas to calculate, resolve immediately
- const { stage, totalArrayFormulasToCalculate, totalFormulasToCalculate } = stageInfo;
- if (stage === FormulaExecuteStageType.START_CALCULATION && totalArrayFormulasToCalculate + totalFormulasToCalculate === 0) {
- cleanup();
- resolve();
- return;
- }
-
- if (started) return;
- started = true;
-
- // A start signal is received → no need for the watchdog anymore
- clearTimeout(startWatchdog);
- });
-
- // Listen for the "calculation completed" signal
- const endDisposable = this.calculationResultApplied(() => {
- if (finished) return;
- finished = true;
-
- cleanup();
- resolve();
- });
-
- function cleanup(): void {
- clearTimeout(mainTimer);
- clearTimeout(startWatchdog);
- processingDisposable.dispose();
- endDisposable.dispose();
- }
- });
+ override onCalculationResultApplied(timeout?: number): Promise<void> {
+ return this._injector.get(FormulaCalculationSessionService).waitForLatestApplied(timeout);
}
}
diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.ts
index 22697c1412..17c7fc3d2a 100644
--- a/packages/sheets-formula/src/index.ts
+++ b/packages/sheets-formula/src/index.ts
@@ -19,6 +19,7 @@ export { QuickSumCommand } from './commands/commands/quick-sum.command';
export { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from './config/config';
export type { IUniverSheetsFormulaBaseConfig, IUniverSheetsFormulaRemoteConfig } from './config/config';
export { FormulaAutoFillController } from './controllers/formula-auto-fill.controller';
+export { FormulaCalculationSessionController } from './controllers/formula-calculation-session.controller';
export { ImageFormulaCellInterceptorController } from './controllers/image-formula-cell-interceptor.controller';
export { TriggerCalculationController } from './controllers/trigger-calculation.controller';
export { UpdateDefinedNameController } from './controllers/update-defined-name.controller';
@@ -26,6 +27,8 @@ export { UpdateFormulaController } from './controllers/update-formula.controller
export { UniverRemoteSheetsFormulaPlugin, UniverSheetsFormulaPlugin } from './plugin';
export { DescriptionService, IDescriptionService } from './services/description.service';
export type { ISearchItem, ISearchItemWithType } from './services/description.service';
+export { FormulaCalculationSessionService } from './services/formula-calculation-session.service';
+export type { IFormulaCalculationSessionState } from './services/formula-calculation-session.service';
export { FormulaRefRangeService } from './services/formula-ref-range.service';
export type { IRegisterAsyncFunction, IRegisterFunction, ISingleFunctionRegisterParams } from './services/register-function.service';
export type { IRegisterFunctionParams, IUnregisterFunctionParams } from './services/register-function.service';
diff --git a/packages/sheets-formula/src/plugin.ts b/packages/sheets-formula/src/plugin.ts
index 1b05fcfd05..ea3b60eb83 100644
--- a/packages/sheets-formula/src/plugin.ts
+++ b/packages/sheets-formula/src/plugin.ts
@@ -32,6 +32,7 @@ import { ActiveDirtyController } from './controllers/active-dirty.controller';
import { ArrayFormulaCellInterceptorController } from './controllers/array-formula-cell-interceptor.controller';
import { DefinedNameController } from './controllers/defined-name.controller';
import { FormulaAutoFillController } from './controllers/formula-auto-fill.controller';
+import { FormulaCalculationSessionController } from './controllers/formula-calculation-session.controller';
import { FormulaController } from './controllers/formula.controller';
import { ImageFormulaCellInterceptorController } from './controllers/image-formula-cell-interceptor.controller';
import { SuperTableController } from './controllers/super-table.controller';
@@ -39,6 +40,7 @@ import { TriggerCalculationController } from './controllers/trigger-calculation.
import { UpdateDefinedNameController } from './controllers/update-defined-name.controller';
import { UpdateFormulaController } from './controllers/update-formula.controller';
import { DescriptionService, IDescriptionService } from './services/description.service';
+import { FormulaCalculationSessionService } from './services/formula-calculation-session.service';
import { FormulaRefRangeService } from './services/formula-ref-range.service';
import { IRegisterFunctionService, RegisterFunctionService } from './services/register-function.service';
import { IRemoteRegisterFunctionService, RemoteRegisterFunctionService, RemoteRegisterFunctionServiceName } from './services/remote/remote-register-function.service';
@@ -103,6 +105,8 @@ export class UniverSheetsFormulaPlugin extends Plugin {
const dependencies: Dependency[] = [
[IRegisterFunctionService, { useClass: RegisterFunctionService }],
[IDescriptionService, { useClass: DescriptionService }],
+ [FormulaCalculationSessionService],
+ [FormulaCalculationSessionController],
[FormulaController],
[FormulaRefRangeService],
[ArrayFormulaCellInterceptorController],
@@ -143,6 +147,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {
if (isNodeEnv()) {
touchDependencies(this._injector, [
[TriggerCalculationController],
+ [FormulaCalculationSessionController],
]);
}
}
@@ -157,6 +162,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {
if (!isNodeEnv()) {
touchDependencies(this._injector, [
[TriggerCalculationController],
+ [FormulaCalculationSessionController],
]);
}
}
diff --git a/packages/sheets-formula/src/services/__tests__/formula-calculation-session.service.spec.ts b/packages/sheets-formula/src/services/__tests__/formula-calculation-session.service.spec.ts
new file mode 100644
index 0000000000..650fff4dd2
--- /dev/null
+++ b/packages/sheets-formula/src/services/__tests__/formula-calculation-session.service.spec.ts
@@ -0,0 +1,293 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ISetFormulaCalculationResultMutation } from '@univerjs/engine-formula';
+import { FormulaExecutedStateType, FormulaExecuteStageType } from '@univerjs/engine-formula';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { FormulaCalculationSessionService } from '../formula-calculation-session.service';
+
+describe('FormulaCalculationSessionService', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('waits for the latest restarted session to be applied', async () => {
+ vi.useFakeTimers();
+
+ const service = new FormulaCalculationSessionService();
+ service.initialize();
+ const waitForApplied = service.waitForLatestApplied();
+ let resolved = false;
+ void waitForApplied.then(() => {
+ resolved = true;
+ });
+
+ service.start();
+ service.updateProgress({
+ stage: FormulaExecuteStageType.CURRENTLY_CALCULATING,
+ totalFormulasToCalculate: 1,
+ completedFormulasCount: 0,
+ totalArrayFormulasToCalculate: 0,
+ completedArrayFormulasCount: 0,
+ formulaCycleIndex: 0,
+ });
+ service.markStopped();
+
+ await Promise.resolve();
+
+ service.start();
+ service.updateProgress({
+ stage: FormulaExecuteStageType.CURRENTLY_CALCULATING,
+ totalFormulasToCalculate: 1,
+ completedFormulasCount: 0,
+ totalArrayFormulasToCalculate: 0,
+ completedArrayFormulasCount: 0,
+ formulaCycleIndex: 0,
+ });
+
+ await Promise.resolve();
+
+ expect(resolved).toBe(false);
+
+ service.markResultEmitted({ unitData: {}, unitOtherData: {} }, true);
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ service.markResultApplied();
+ await expect(waitForApplied).resolves.toBeUndefined();
+ });
+
+ it('stores lifecycle flags and progress for the active session', () => {
+ const service = new FormulaCalculationSessionService();
+ service.initialize();
+
+ service.start();
+ const progress = {
+ stage: FormulaExecuteStageType.START_CALCULATION,
+ totalFormulasToCalculate: 2,
+ completedFormulasCount: 0,
+ totalArrayFormulasToCalculate: 0,
+ completedArrayFormulasCount: 0,
+ formulaCycleIndex: 0,
+ };
+
+ service.updateProgress(progress);
+ expect(service.state).toMatchObject({
+ started: true,
+ progress,
+ stopped: false,
+ completed: false,
+ resultApplied: false,
+ });
+
+ service.markCompleted(FormulaExecutedStateType.SUCCESS);
+ expect(service.state).toMatchObject({
+ completed: true,
+ stopped: false,
+ resultApplied: false,
+ });
+ });
+
+ it('does not resolve from an already applied previous session when a new session starts', async () => {
+ vi.useFakeTimers();
+
+ const service = new FormulaCalculationSessionService();
+ service.initialize();
+ service.start();
+ service.markResultEmitted({ unitData: {}, unitOtherData: {} }, false);
+
+ await Promise.resolve();
+
+ const waitForApplied = service.waitForLatestApplied();
+ let resolved = false;
+ void waitForApplied.then(() => {
+ resolved = true;
+ });
+
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ service.start();
+ service.markResultEmitted({ unitData: {}, unitOtherData: {} }, true);
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ service.markResultApplied();
+ await expect(waitForApplied).resolves.toBeUndefined();
+ });
+
+ it('emits result applied when value application is observed', async () => {
+ const service = new FormulaCalculationSessionService();
+ service.initialize();
+ const result = {
+ unitData: {
+ unit1: {
+ sheet1: {
+ 0: {
+ 0: { v: 1 },
+ },
+ },
+ },
+ },
+ unitOtherData: {},
+ };
+ const appliedResults: unknown[] = [];
+ const subscription = service.resultApplied$.subscribe((value) => appliedResults.push(value));
+
+ service.start();
+ service.markResultEmitted(result, true);
+ expect(appliedResults).toEqual([]);
+
+ service.markResultApplied();
+ expect(appliedResults).toEqual([result]);
+
+ subscription.unsubscribe();
+ });
+
+ it('emits result applied only once for repeated value application notifications', () => {
+ const service = new FormulaCalculationSessionService();
+ service.initialize();
+ const result = {
+ unitData: {
+ unit1: {
+ sheet1: {
+ 0: {
+ 0: { v: 1 },
+ },
+ },
+ },
+ },
+ unitOtherData: {},
+ };
+ const appliedResults: unknown[] = [];
+ const subscription = service.resultApplied$.subscribe((value) => appliedResults.push(value));
+
+ service.start();
+ service.markResultEmitted(result, true);
+ service.markResultApplied();
+ service.markResultApplied();
+
+ expect(appliedResults).toEqual([result]);
+
+ subscription.unsubscribe();
+ });
+
+ it('emits result applied once when result arrives after an application notification', () => {
+ const service = new FormulaCalculationSessionService();
+ service.initialize();
+ const result = {
+ unitData: {
+ unit1: {
+ sheet1: {
+ 0: {
+ 0: { v: 1 },
+ },
+ },
+ },
+ },
+ unitOtherData: {},
+ };
+ const appliedResults: unknown[] = [];
+ const subscription = service.resultApplied$.subscribe((value) => appliedResults.push(value));
+
+ service.start();
+ service.markResultApplied();
+ service.markResultEmitted(result, true);
+ service.markResultApplied();
+
+ expect(appliedResults).toEqual([result]);
+
+ subscription.unsubscribe();
+ });
+
+ it('emits result applied immediately when there is no sheet value to apply', () => {
+ const service = new FormulaCalculationSessionService();
+ service.initialize();
+ const result: ISetFormulaCalculationResultMutation = {
+ unitData: {},
+ unitOtherData: {},
+ };
+ const appliedResults: unknown[] = [];
+ const subscription = service.resultApplied$.subscribe((value) => appliedResults.push(value));
+
+ service.start();
+ service.markResultEmitted(result, false);
+
+ expect(appliedResults).toEqual([result]);
+
+ subscription.unsubscribe();
+ });
+
+ it('does not start the no-calculation watchdog until the session controller is initialized', async () => {
+ vi.useFakeTimers();
+
+ const service = new FormulaCalculationSessionService();
+ const waitForApplied = service.waitForLatestApplied();
+ let resolved = false;
+ void waitForApplied.then(() => {
+ resolved = true;
+ });
+
+ await vi.advanceTimersByTimeAsync(500);
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ service.initialize();
+ await vi.advanceTimersByTimeAsync(499);
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(1);
+ await expect(waitForApplied).resolves.toBeUndefined();
+ });
+
+ it('does not reject long-running calculations unless a timeout is provided', async () => {
+ vi.useFakeTimers();
+
+ const service = new FormulaCalculationSessionService();
+ service.initialize();
+ service.start();
+
+ const waitForApplied = service.waitForLatestApplied();
+ let settled = false;
+ void waitForApplied.then(() => {
+ settled = true;
+ });
+
+ await vi.advanceTimersByTimeAsync(60_000);
+ await Promise.resolve();
+
+ expect(settled).toBe(false);
+
+ service.markResultEmitted({ unitData: {}, unitOtherData: {} }, false);
+
+ await expect(waitForApplied).resolves.toBeUndefined();
+ });
+
+ it('rejects long-running calculations when a timeout is provided', async () => {
+ vi.useFakeTimers();
+
+ const service = new FormulaCalculationSessionService();
+ service.initialize();
+ service.start();
+
+ const waitForApplied = expect(service.waitForLatestApplied(1000)).rejects.toThrow('Calculation end timeout');
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ await waitForApplied;
+ });
+});
diff --git a/packages/sheets-formula/src/services/formula-calculation-session.service.ts b/packages/sheets-formula/src/services/formula-calculation-session.service.ts
new file mode 100644
index 0000000000..f0de720b94
--- /dev/null
+++ b/packages/sheets-formula/src/services/formula-calculation-session.service.ts
@@ -0,0 +1,301 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { FormulaExecutedStateType, IExecutionInProgressParams, ISetFormulaCalculationResultMutation } from '@univerjs/engine-formula';
+import { Disposable } from '@univerjs/core';
+import { FormulaExecutedStateType as FormulaExecutedState, FormulaExecuteStageType } from '@univerjs/engine-formula';
+import { BehaviorSubject, Subject } from 'rxjs';
+
+export interface IFormulaCalculationSessionState {
+ id: number;
+ initialized: boolean;
+ started: boolean;
+ progress: IExecutionInProgressParams | null;
+ stopped: boolean;
+ completed: boolean;
+ resultEmitted: boolean;
+ resultApplied: boolean;
+}
+
+const INITIAL_SESSION_STATE: IFormulaCalculationSessionState = {
+ id: 0,
+ initialized: false,
+ started: false,
+ progress: null,
+ stopped: false,
+ completed: false,
+ resultEmitted: false,
+ resultApplied: true,
+};
+
+export class FormulaCalculationSessionService extends Disposable {
+ private readonly _state$ = new BehaviorSubject<IFormulaCalculationSessionState>(INITIAL_SESSION_STATE);
+
+ private readonly _resultApplied$ = new Subject<ISetFormulaCalculationResultMutation>();
+
+ private _currentResult: ISetFormulaCalculationResultMutation | null = null;
+
+ private _hasEmittedCurrentResultApplied = false;
+
+ readonly state$ = this._state$.asObservable();
+
+ readonly resultApplied$ = this._resultApplied$.asObservable();
+
+ get state(): IFormulaCalculationSessionState {
+ return this._state$.getValue();
+ }
+
+ override dispose(): void {
+ super.dispose();
+ this._state$.complete();
+ this._resultApplied$.complete();
+ }
+
+ initialize(): void {
+ this._emit({
+ ...this.state,
+ initialized: true,
+ });
+ }
+
+ start(): void {
+ this._emit({
+ id: this.state.id + 1,
+ initialized: this.state.initialized,
+ started: true,
+ progress: null,
+ stopped: false,
+ completed: false,
+ resultEmitted: false,
+ resultApplied: false,
+ });
+ this._currentResult = null;
+ this._hasEmittedCurrentResultApplied = false;
+ }
+
+ updateProgress(progress: IExecutionInProgressParams): void {
+ if (!this.state.started) {
+ this.start();
+ }
+
+ const noCalculation = (
+ progress.stage === FormulaExecuteStageType.START_CALCULATION ||
+ progress.stage === FormulaExecuteStageType.START_CALCULATION_ARRAY_FORMULA
+ ) && progress.totalFormulasToCalculate + progress.totalArrayFormulasToCalculate === 0;
+
+ this._emit({
+ ...this.state,
+ progress,
+ completed: this.state.completed || progress.stage === FormulaExecuteStageType.CALCULATION_COMPLETED || noCalculation,
+ resultApplied: this.state.resultApplied || noCalculation,
+ });
+ }
+
+ markStopped(): void {
+ this._emit({
+ ...this.state,
+ stopped: true,
+ completed: true,
+ resultApplied: true,
+ });
+ }
+
+ markCompleted(state: FormulaExecutedStateType): void {
+ const noResultToApply = state === FormulaExecutedState.NOT_EXECUTED || state === FormulaExecutedState.INITIAL;
+ this._emit({
+ ...this.state,
+ stopped: state === FormulaExecutedState.STOP_EXECUTION,
+ completed: state !== FormulaExecutedState.INITIAL,
+ resultApplied: this.state.resultApplied || noResultToApply || state === FormulaExecutedState.STOP_EXECUTION,
+ });
+ }
+
+ markResultEmitted(result: ISetFormulaCalculationResultMutation, hasResultToApply: boolean): void {
+ if (this._currentResult !== result) {
+ this._hasEmittedCurrentResultApplied = false;
+ }
+
+ this._currentResult = result;
+ const resultApplied = this.state.resultApplied || !hasResultToApply;
+ this._emit({
+ ...this.state,
+ resultEmitted: true,
+ resultApplied,
+ });
+
+ if (resultApplied) {
+ this._emitResultApplied();
+ }
+ }
+
+ markResultApplied(): void {
+ this._emit({
+ ...this.state,
+ resultApplied: true,
+ });
+ this._emitResultApplied();
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ waitForLatestApplied(timeout?: number, startWatchdog = 500): Promise<void> {
+ const initialState = this.state;
+ const initialId = initialState.id;
+ const waitForInitialization = !initialState.initialized;
+ const waitForExistingSession = initialState.started && !this._isAppliedTerminalState(initialState);
+
+ // eslint-disable-next-line max-lines-per-function
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ let pendingResolveId: number | null = null;
+ let stoppedResolveTimer: ReturnType<typeof setTimeout> | null = null;
+ let timeoutTimer: ReturnType<typeof setTimeout> | null = null;
+
+ const cleanup = () => {
+ if (timeoutTimer != null) {
+ clearTimeout(timeoutTimer);
+ timeoutTimer = null;
+ }
+ clearStartTimer();
+ if (stoppedResolveTimer != null) {
+ clearTimeout(stoppedResolveTimer);
+ stoppedResolveTimer = null;
+ }
+ subscription.unsubscribe();
+ };
+
+ const settleResolve = () => {
+ if (settled) return;
+ settled = true;
+ cleanup();
+ resolve();
+ };
+
+ const settleReject = (error: Error) => {
+ if (settled) return;
+ settled = true;
+ cleanup();
+ reject(error);
+ };
+
+ const scheduleResolveIfApplied = (state: IFormulaCalculationSessionState) => {
+ if (!this._isAppliedTerminalState(state)) {
+ return;
+ }
+
+ const resolvingId = state.id;
+ pendingResolveId = resolvingId;
+
+ const resolveIfStillLatest = () => {
+ if (settled || pendingResolveId !== resolvingId || this.state.id !== resolvingId || !this._isAppliedTerminalState(this.state)) {
+ return;
+ }
+
+ settleResolve();
+ };
+
+ if (state.stopped && !state.resultEmitted) {
+ if (stoppedResolveTimer != null) {
+ clearTimeout(stoppedResolveTimer);
+ }
+
+ stoppedResolveTimer = setTimeout(resolveIfStillLatest, 0);
+ return;
+ }
+
+ Promise.resolve().then(resolveIfStillLatest);
+ };
+
+ if (timeout != null) {
+ timeoutTimer = setTimeout(() => {
+ settleReject(new Error('Calculation end timeout'));
+ }, timeout);
+ }
+
+ let startTimer: ReturnType<typeof setTimeout> | null = null;
+
+ const clearStartTimer = () => {
+ if (startTimer != null) {
+ clearTimeout(startTimer);
+ startTimer = null;
+ }
+ };
+
+ const scheduleStartTimer = () => {
+ clearStartTimer();
+ startTimer = setTimeout(() => {
+ if (this.state.id === initialId && !waitForExistingSession) {
+ settleResolve();
+ }
+ }, startWatchdog);
+ };
+
+ if (!waitForExistingSession && !waitForInitialization) {
+ scheduleStartTimer();
+ }
+
+ const subscription = this.state$.subscribe((state) => {
+ if (state.id !== initialId || waitForExistingSession) {
+ clearStartTimer();
+ }
+
+ if (waitForInitialization && state.initialized && state.id === initialId && !state.started) {
+ scheduleStartTimer();
+ return;
+ }
+
+ if (state.id === initialId && !waitForExistingSession) {
+ return;
+ }
+
+ if (pendingResolveId !== state.id) {
+ pendingResolveId = null;
+ }
+
+ if (stoppedResolveTimer != null && pendingResolveId !== state.id) {
+ clearTimeout(stoppedResolveTimer);
+ stoppedResolveTimer = null;
+ }
+
+ scheduleResolveIfApplied(state);
+ });
+
+ if (waitForExistingSession) {
+ scheduleResolveIfApplied(this.state);
+ }
+ });
+ }
+
+ private _emit(state: IFormulaCalculationSessionState): void {
+ this._state$.next(state);
+ }
+
+ private _emitResultApplied(): void {
+ if (this._currentResult == null || this._hasEmittedCurrentResultApplied) {
+ return;
+ }
+
+ this._hasEmittedCurrentResultApplied = true;
+ this._resultApplied$.next(this._currentResult);
+ }
+
+ private _isAppliedTerminalState(state: IFormulaCalculationSessionState): boolean {
+ if (!state.started || !state.resultApplied) {
+ return false;
+ }
+
+ return state.stopped || state.completed || state.resultEmitted;
+ }
+}