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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(sheets-formula): cancel progress timer on disposal (#8118)
白熱9e29a8483c96
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.tsindex 88e61522b0..b1c1795e0a 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@@ -374,4 +374,51 @@ describe('TriggerCalculationController', () => {testBed.executedDisposable.dispose();testBed.testBed.univer.dispose();});++ it.each([0, 250, 999, 1000])('should cancel delayed progress when Univer is disposed after %d ms', async (delay) => {+ const testBed = createControllerTestBed(CalculationMode.NO_CALCULATION);++ await testBed.commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {+ stageInfo: {+ stage: FormulaExecuteStageType.START,+ totalFormulasToCalculate: 0,+ completedFormulasCount: 0,+ totalArrayFormulasToCalculate: 0,+ completedArrayFormulasCount: 0,+ formulaCycleIndex: 0,+ } satisfies IExecutionInProgressParams,+ });+ vi.advanceTimersByTime(delay);++ testBed.testBed.univer.dispose();++ expect(() => vi.advanceTimersByTime(1000)).not.toThrow();+ });++ it('should release the latest progress timer when disposed after successive starts', async () => {+ const testBed = createControllerTestBed(CalculationMode.NO_CALCULATION);+ const controller = testBed.testBed.injector.get(TriggerCalculationController);++ try {+ for (let index = 0; index < 3; index++) {+ await testBed.commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {+ stageInfo: {+ stage: FormulaExecuteStageType.START,+ totalFormulasToCalculate: 0,+ completedFormulasCount: 0,+ totalArrayFormulasToCalculate: 0,+ completedArrayFormulasCount: 0,+ formulaCycleIndex: 0,+ } satisfies IExecutionInProgressParams,+ });+ vi.advanceTimersByTime(100);+ }++ controller.dispose();++ expect(vi.getTimerCount()).toBe(0);+ } finally {+ testBed.testBed.univer.dispose();+ }+ });});diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.tsindex 88c1b1690d..0e5fb76459 100644--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts@@ -16,8 +16,6 @@import type { ICommandInfo, IUnitRange, Nullable, Workbook } from '@univerjs/core';import type { IDirtyUnitDefinedNameMap, IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetNameMap, IDirtyUnitSuperTableMap, IExecutionInProgressParams, IFormulaDirtyData, ISetFormulaCalculationNotificationMutation, ISetFormulaCalculationStartMutation } from '@univerjs/engine-formula';-import type { IUniverSheetsFormulaBaseConfig } from '../config/config';-import type { LocaleKey } from '../locale/types';import {Disposable,ICommandService,@@ -40,6 +38,8 @@ import {SetTriggerFormulaCalculationStartMutation,} from '@univerjs/engine-formula';import { BehaviorSubject } from 'rxjs';+import type { IUniverSheetsFormulaBaseConfig } from '../config/config';+import type { LocaleKey } from '../locale/types';import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from '../config/config';/**@@ -170,15 +170,19 @@ export class TriggerCalculationController extends Disposable {);}- // eslint-disable-next-line max-lines-per-functionprivate _initialExecuteFormulaProcessListener() {- // Assignment operation after formula calculation.let startDependencyTimer: NodeJS.Timeout | null = null;- let calculationProcessCount = 0; // Multiple calculations are performed in parallel, but only one progress bar is displayed, and the progress is only closed after the last calculation is completed.+ // Concurrent calculations share one progress bar until the last calculation finishes.+ let calculationProcessCount = 0;- this.disposeWithMe(+ this.disposeWithMe(() => {+ if (startDependencyTimer !== null) {+ clearTimeout(startDependencyTimer);+ startDependencyTimer = null;+ }+ });- // eslint-disable-next-line max-lines-per-function, complexity+ this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {if (command.id === SetFormulaCalculationStopMutation.id) {this.clearProgress();@@ -194,9 +198,7 @@ export class TriggerCalculationController extends Disposable {}if (params.stageInfo != null) {- const {- stage,- } = params.stageInfo;+ const { stage } = params.stageInfo;if (stage === FormulaExecuteStageType.START) {// When calculations are started multiple times in succession, only the first time is recognized@@ -204,10 +206,8 @@ export class TriggerCalculationController extends Disposable {this._startExecutionTime = performance.now();}- // Increment the calculation process count and assign a new IDcalculationProcessCount++;- // Clear any existing timer to prevent duplicate executionsif (startDependencyTimer !== null) {clearTimeout(startDependencyTimer);startDependencyTimer = null;@@ -218,55 +218,13 @@ export class TriggerCalculationController extends Disposable {startDependencyTimer = null;this._startProgress();}, 1000);- } else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING) {- this._executionInProgressParams = params.stageInfo;-- if (startDependencyTimer === null) {- const calculating = this._localeService.t<LocaleKey>('sheets-formula.progress.calculating');- this._calculateProgress(calculating);- }- } else if (stage === FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA) {- this._executionInProgressParams = params.stageInfo;-- if (startDependencyTimer === null) {- const arrayAnalysis = this._localeService.t<LocaleKey>('sheets-formula.progress.array-analysis');- this._calculateProgress(arrayAnalysis);- }- } else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA) {- this._executionInProgressParams = params.stageInfo;-- if (startDependencyTimer === null) {- const arrayCalculation = this._localeService.t<LocaleKey>('sheets-formula.progress.array-calculation');- this._calculateProgress(arrayCalculation);- }+ } else {+ this._updateCalculationProgress(params.stageInfo, startDependencyTimer === null);}} else {const state = params.functionsExecutedState;- let result = '';-- // Decrement the calculation process count- calculationProcessCount--;-- switch (state) {- case FormulaExecutedStateType.NOT_EXECUTED:- result = 'No tasks are being executed anymore';- break;- case FormulaExecutedStateType.STOP_EXECUTION:- result = 'The execution of the formula has been stopped';- calculationProcessCount = 0;- break;- case FormulaExecutedStateType.SUCCESS:- result = 'Formula calculation succeeded';-- // When the calculation is stopped and then a successful calculation is triggered, the value is -1- if (calculationProcessCount === 0 || calculationProcessCount === -1) {- result += `. Total time consumed: ${performance.now() - this._startExecutionTime} ms`;- }- break;- case FormulaExecutedStateType.INITIAL:- result = 'Waiting for calculation';- break;- }+ calculationProcessCount = state === FormulaExecutedStateType.STOP_EXECUTION ? 0 : calculationProcessCount - 1;+ const result = this._getCalculationResultMessage(state, calculationProcessCount);// When the calculation is stopped and then a successful calculation is triggered, the value is -1if (calculationProcessCount === 0 || calculationProcessCount === -1) {@@ -293,6 +251,47 @@ export class TriggerCalculationController extends Disposable {);}+ private _updateCalculationProgress(stageInfo: IExecutionInProgressParams, showProgress: boolean): void {+ let label: LocaleKey;+ switch (stageInfo.stage) {+ case FormulaExecuteStageType.CURRENTLY_CALCULATING:+ label = 'sheets-formula.progress.calculating';+ break;+ case FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA:+ label = 'sheets-formula.progress.array-analysis';+ break;+ case FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA:+ label = 'sheets-formula.progress.array-calculation';+ break;+ default:+ return;+ }++ this._executionInProgressParams = stageInfo;+ if (showProgress) {+ this._calculateProgress(this._localeService.t<LocaleKey>(label));+ }+ }++ private _getCalculationResultMessage(state: FormulaExecutedStateType | undefined, calculationProcessCount: number): string {+ switch (state) {+ case FormulaExecutedStateType.NOT_EXECUTED:+ return 'No tasks are being executed anymore';+ case FormulaExecutedStateType.STOP_EXECUTION:+ return 'The execution of the formula has been stopped';+ case FormulaExecutedStateType.SUCCESS:+ // A success notification after stopping a calculation can leave the count at -1.+ if (calculationProcessCount === 0 || calculationProcessCount === -1) {+ return `Formula calculation succeeded. Total time consumed: ${performance.now() - this._startExecutionTime} ms`;+ }+ return 'Formula calculation succeeded';+ case FormulaExecutedStateType.INITIAL:+ return 'Waiting for calculation';+ default:+ return '';+ }+ }+private _initialExecuteFormula() {const calculationMode = this._getCalculationMode();if (calculationMode !== CalculationMode.NO_CALCULATION) {