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.

feat(sheet): restart formula calculation (#2646)

Univerb1be75c576dc
diff --git a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
index f6384cf6fd..9a90ad7358 100644
--- a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
+++ b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
@@ -27,12 +27,15 @@ import type {
} from '../../basics/common';
import type { FormulaExecutedStateType, IExecutionInProgressParams } from '../../services/runtime.service';
-export interface ISetFormulaCalculationStartMutation {
+export interface IFormulaDirtyData {
dirtyRanges: IUnitRange[];
dirtyNameMap: IDirtyUnitSheetNameMap;
dirtyDefinedNameMap: IDirtyUnitSheetDefinedNameMap;
dirtyUnitFeatureMap: IDirtyUnitFeatureMap;
dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap;
+}
+
+export interface ISetFormulaCalculationStartMutation extends IFormulaDirtyData {
options: Nullable<IExecutionOptions>;
forceCalculation?: boolean;
}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index e021fe8ccc..df14b39158 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -139,6 +139,7 @@ export {
type ISetFormulaCalculationStartMutation,
type ISetFormulaCalculationNotificationMutation,
type ISetFormulaCalculationResultMutation,
+ type IFormulaDirtyData,
} from './commands/mutations/set-formula-calculation.mutation';
export { SetFormulaDataMutation, type ISetFormulaDataMutationParams } from './commands/mutations/set-formula-data.mutation';
export { SetOtherFormulaMutation, RemoveOtherFormulaMutation, type ISetOtherFormulaMutationParams, type IRemoveOtherFormulaMutationParams } from './commands/mutations/set-other-formula.mutation';
diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.ts
index f48ea386b2..7960e8c635 100644
--- a/packages/engine-formula/src/services/calculate-formula.service.ts
+++ b/packages/engine-formula/src/services/calculate-formula.service.ts
@@ -111,6 +111,7 @@ export class CalculateFormulaService extends Disposable {
DEFAULT_CYCLE_REFERENCE_COUNT) as number;
for (let i = 0; i < cycleReferenceCount; i++) {
+ this._runtimeService.setFormulaCycleIndex(i);
await this._execute();
const isCycleDependency = this._runtimeService.isCycleDependency();
if (!isCycleDependency) {
@@ -216,6 +217,7 @@ export class CalculateFormulaService extends Disposable {
return { dirtyRanges, excludedCell };
}
+ // eslint-disable-next-line max-lines-per-function
private async _apply(isArrayFormulaState = false) {
if (isArrayFormulaState) {
this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA);
@@ -248,8 +250,8 @@ export class CalculateFormulaService extends Disposable {
* For every functions, execute a setTimeout to wait for external command input.
*/
await new Promise((resolve) => {
- const calcelTask = requestImmediateMacroTask(resolve);
- pendingTasks.push(calcelTask);
+ const calCancelTask = requestImmediateMacroTask(resolve);
+ pendingTasks.push(calCancelTask);
});
if (this._runtimeService.isStopExecution()) {
diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.ts
index e10c90d1f6..67d9fa3bb4 100644
--- a/packages/engine-formula/src/services/runtime.service.ts
+++ b/packages/engine-formula/src/services/runtime.service.ts
@@ -79,6 +79,8 @@ export interface IExecutionInProgressParams {
totalArrayFormulasToCalculate: number;
completedArrayFormulasCount: number;
+ formulaCycleIndex: number;
+
stage: FormulaExecuteStageType;
}
@@ -118,6 +120,8 @@ export interface IFormulaRuntimeService {
setFormulaExecuteStage(type: FormulaExecuteStageType): void;
+ setFormulaCycleIndex(index: number): void;
+
isStopExecution(): boolean;
getFormulaExecuteStage(): FormulaExecuteStageType;
@@ -212,6 +216,8 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
private _completedArrayFormulasCount: number = 0;
+ private _formulaCycleIndex: number = 0;
+
private _isCycleDependency: boolean = false;
constructor(@IFormulaCurrentConfigService private readonly _currentConfigService: IFormulaCurrentConfigService) {
@@ -292,6 +298,14 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
return this._completedFormulasCount;
}
+ setFormulaCycleIndex(index: number) {
+ this._formulaCycleIndex = index;
+ }
+
+ getFormulaCycleIndex() {
+ return this._formulaCycleIndex;
+ }
+
markedAsSuccessfullyExecuted() {
this._functionsExecutedState = FormulaExecutedStateType.SUCCESS;
}
@@ -340,6 +354,8 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
this._functionDefinitionPrivacyVar.clear();
this.markedAsInitialFunctionsExecuted();
+ this._stopState = false;
+
this._isCycleDependency = false;
this._totalFormulasToCalculate = 0;
@@ -409,6 +425,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
subComponentData![formulaId] = cellDatas;
}
+ // eslint-disable-next-line max-lines-per-function
setRuntimeData(functionVariant: FunctionVariantType) {
const row = this._currentRow;
const column = this._currentColumn;
@@ -597,6 +614,8 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
completedArrayFormulasCount: this.getCompletedArrayFormulasCount(),
stage: this.getFormulaExecuteStage(),
+
+ formulaCycleIndex: this.getFormulaCycleIndex(),
};
}
diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
index 2d356f6301..106d717a5d 100644
--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-import type { ICommandInfo, IUnitRange } from '@univerjs/core';
+import type { ICommandInfo, IUnitRange, Nullable } from '@univerjs/core';
import { Disposable, ICommandService, LifecycleStages, OnLifecycle, throttle } from '@univerjs/core';
import type {
IDirtyUnitFeatureMap,
IDirtyUnitOtherFormulaMap,
IDirtyUnitSheetNameMap,
+ IExecutionInProgressParams,
+ IFormulaDirtyData,
ISetFormulaCalculationNotificationMutation,
} from '@univerjs/engine-formula';
import {
@@ -29,6 +31,7 @@ import {
IActiveDirtyManagerService,
SetFormulaCalculationNotificationMutation,
SetFormulaCalculationStartMutation,
+ SetFormulaCalculationStopMutation,
} from '@univerjs/engine-formula';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import {
@@ -46,7 +49,13 @@ import { Inject } from '@wendellhu/redi';
export class TriggerCalculationController extends Disposable {
private _waitingCommandQueue: ICommandInfo[] = [];
- private _executingCommandQueue: ICommandInfo[] = [];
+ private _executingDirtyData: IFormulaDirtyData = {
+ dirtyRanges: [],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ };
private _setTimeoutKey: NodeJS.Timeout | number = -1;
@@ -56,6 +65,10 @@ export class TriggerCalculationController extends Disposable {
private _arrayFormulaCalculationDoneCount: number = 0;
+ private _executionInProgressParams: Nullable<IExecutionInProgressParams> = null;
+
+ private _restartCalculation = false;
+
constructor(
@ICommandService private readonly _commandService: ICommandService,
@IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService,
@@ -115,20 +128,26 @@ export class TriggerCalculationController extends Disposable {
clearTimeout(this._setTimeoutKey);
this._setTimeoutKey = setTimeout(() => {
- this._commandService.executeCommand(
- SetFormulaCalculationStartMutation.id,
- {
- ...this._generateDirty(this._waitingCommandQueue),
- },
- {
- onlyLocal: true,
- }
- );
+ const dirtyData = this._generateDirty(this._waitingCommandQueue);
+ this._executingDirtyData = this._mergeDirty(this._executingDirtyData, dirtyData);
+
+ if (this._executionInProgressParams == null) {
+ this._commandService.executeCommand(
+ SetFormulaCalculationStartMutation.id,
+ {
+ ...this._executingDirtyData,
+ },
+ {
+ onlyLocal: true,
+ }
+ );
+ } else {
+ this._restartCalculation = true;
+ this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {});
+ }
this._startExecutionTime = performance.now();
- this._executingCommandQueue = this._waitingCommandQueue;
-
this._waitingCommandQueue = [];
}, 100);
})
@@ -186,6 +205,27 @@ export class TriggerCalculationController extends Disposable {
};
}
+ private _mergeDirty(dirtyData1: IFormulaDirtyData, dirtyData2: IFormulaDirtyData) {
+ const allDirtyRanges: IUnitRange[] = [...dirtyData1.dirtyRanges, ...dirtyData2.dirtyRanges];
+ const allDirtyNameMap: IDirtyUnitSheetNameMap = { ...dirtyData1.dirtyNameMap };
+ const allDirtyDefinedNameMap: IDirtyUnitSheetNameMap = { ...dirtyData1.dirtyDefinedNameMap };
+ const allDirtyUnitFeatureMap: IDirtyUnitFeatureMap = { ...dirtyData1.dirtyUnitFeatureMap };
+ const allDirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = { ...dirtyData1.dirtyUnitOtherFormulaMap };
+
+ this._mergeDirtyNameMap(allDirtyNameMap, dirtyData2.dirtyNameMap);
+ this._mergeDirtyNameMap(allDirtyDefinedNameMap, dirtyData2.dirtyDefinedNameMap);
+ this._mergeDirtyUnitFeatureOrOtherFormulaMap(allDirtyUnitFeatureMap, dirtyData2.dirtyUnitFeatureMap);
+ this._mergeDirtyUnitFeatureOrOtherFormulaMap(allDirtyUnitOtherFormulaMap, dirtyData2.dirtyUnitOtherFormulaMap);
+
+ return {
+ dirtyRanges: allDirtyRanges,
+ dirtyNameMap: allDirtyNameMap,
+ dirtyDefinedNameMap: allDirtyDefinedNameMap,
+ dirtyUnitFeatureMap: allDirtyUnitFeatureMap,
+ dirtyUnitOtherFormulaMap: allDirtyUnitOtherFormulaMap,
+ };
+ }
+
private _mergeDirtyNameMap(allDirtyNameMap: IDirtyUnitSheetNameMap, dirtyNameMap: IDirtyUnitSheetNameMap) {
Object.keys(dirtyNameMap).forEach((unitId) => {
if (allDirtyNameMap[unitId] == null) {
@@ -223,6 +263,7 @@ export class TriggerCalculationController extends Disposable {
});
}
+ // eslint-disable-next-line max-lines-per-function
private _initialExecuteFormulaProcessListener() {
/**
* Assignment operation after formula calculation.
@@ -237,6 +278,7 @@ export class TriggerCalculationController extends Disposable {
let needStartArrayFormulaProgress = false;
this.disposeWithMe(
+ // eslint-disable-next-line complexity, max-lines-per-function
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (command.id !== SetFormulaCalculationNotificationMutation.id) {
return;
@@ -304,6 +346,8 @@ export class TriggerCalculationController extends Disposable {
}
}
+ this._executionInProgressParams = params.stageInfo;
+
// if (totalArrayFormulasToCalculate > 0) {
// console.warn(
// `Stage ${stage} Array formula.There are ${totalArrayFormulasToCalculate} functions to be executed, ${completedArrayFormulasCount} complete.`
@@ -316,31 +360,32 @@ export class TriggerCalculationController extends Disposable {
} 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';
- // this._waitingCommandQueue.unshift(...this._executingCommandQueue);
- this._executingCommandQueue = [];
+ this._resetExecutingDirtyData();
break;
case FormulaExecutedStateType.STOP_EXECUTION:
result = 'The execution of the formula has been stopped';
- this._waitingCommandQueue.unshift(...this._executingCommandQueue);
- this._executingCommandQueue = [];
+ // this._executingCommandQueue = [];
+ this._progressService.stop();
+ calculationProcessCount = 0;
break;
case FormulaExecutedStateType.SUCCESS:
result = `Formula calculation succeeded, Total time consumed: ${performance.now() - this._startExecutionTime
} ms`;
- this._executingCommandQueue = [];
+ this._resetExecutingDirtyData();
break;
case FormulaExecutedStateType.INITIAL:
result = 'Waiting for calculation';
- this._executingCommandQueue = [];
+ this._resetExecutingDirtyData();
break;
}
- // Decrement the calculation process count
- calculationProcessCount--;
-
if (calculationProcessCount === 0) {
if (startDependencyTimer) {
// The total calculation time does not exceed 1s, and the progress bar is not displayed.
@@ -350,8 +395,6 @@ export class TriggerCalculationController extends Disposable {
// Manually hide the progress bar only if no other calculations are in process
if (state === FormulaExecutedStateType.SUCCESS) {
this._progressService.complete();
- } else if (state === FormulaExecutedStateType.STOP_EXECUTION) {
- this._progressService.stop();
}
}
@@ -361,12 +404,37 @@ export class TriggerCalculationController extends Disposable {
needStartArrayFormulaProgress = false;
}
+ if (state === FormulaExecutedStateType.STOP_EXECUTION && this._restartCalculation) {
+ this._restartCalculation = false;
+ this._commandService.executeCommand(
+ SetFormulaCalculationStartMutation.id,
+ {
+ ...this._executingDirtyData,
+ },
+ {
+ onlyLocal: true,
+ }
+ );
+ } else {
+ this._executionInProgressParams = null;
+ }
+
console.warn(`execution result${result}`);
}
})
);
}
+ private _resetExecutingDirtyData() {
+ this._executingDirtyData = {
+ dirtyRanges: [],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ };
+ }
+
private _initialExecuteFormula() {
this._commandService.executeCommand(
SetFormulaCalculationStartMutation.id,
diff --git a/packages/sheets/src/services/ref-range/ref-range.service.ts b/packages/sheets/src/services/ref-range/ref-range.service.ts
index 5fa6cb8175..2efc818895 100644
--- a/packages/sheets/src/services/ref-range/ref-range.service.ts
+++ b/packages/sheets/src/services/ref-range/ref-range.service.ts
@@ -65,7 +65,7 @@ class WatchRange extends Disposable {
}
onMutation(mutation: IMutationInfo<ISheetCommandSharedParams>) {
- if (mutation.params.unitId !== this._unitId || mutation.params.subUnitId !== this._subUnitId) {
+ if (mutation.params?.unitId !== this._unitId || mutation.params?.subUnitId !== this._subUnitId) {
return;
}
if (!this._range) {