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(engine-formula): refresh table AST cache (#7242)
Univerd2b09831da87
diff --git a/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts b/packages/engine-formula/src/commands/mutations/set-super-table.mutation.tsindex 7ba5d6b6a4..e50bab0b3b 100644--- a/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts+++ b/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts@@ -25,6 +25,10 @@ export interface ISetSuperTableMutationSearchParam {tableName: string;}+export interface IRemoveSuperTableMutationParam extends ISetSuperTableMutationSearchParam {+ reference?: Pick<ISuperTable, 'sheetId' | 'range'>;+}+export interface ISetSuperTableMutationParam extends ISetSuperTableMutationSearchParam {oldTableName?: string;reference: ISuperTable;@@ -44,7 +48,7 @@ export const SetSuperTableMutation: IMutation<ISetSuperTableMutationParam> = {},};-export const RemoveSuperTableMutation: IMutation<ISetSuperTableMutationSearchParam> = {+export const RemoveSuperTableMutation: IMutation<IRemoveSuperTableMutationParam> = {id: 'formula.mutation.remove-super-table',type: CommandType.MUTATION,handler: (accessor, params) => {diff --git a/packages/engine-formula/src/controllers/__tests__/super-table-active-dirty.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/super-table-active-dirty.controller.spec.tsnew file mode 100644index 0000000000..63cab9b577--- /dev/null+++ b/packages/engine-formula/src/controllers/__tests__/super-table-active-dirty.controller.spec.ts@@ -0,0 +1,77 @@+/**+ * 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 { IDirtyConversionManagerParams } from '../../services/active-dirty-manager.service';+import { describe, expect, it, vi } from 'vitest';+import { RemoveSuperTableMutation, SetSuperTableMutation } from '../../commands/mutations/set-super-table.mutation';+import { SuperTableActiveDirtyController } from '../super-table-active-dirty.controller';++describe('SuperTableActiveDirtyController', () => {+ it('invalidates both the old and new table name when a registration changes', () => {+ const conversions = new Map<string, IDirtyConversionManagerParams>();+ const activeDirtyManagerService = {+ register: vi.fn((id: string, conversion: IDirtyConversionManagerParams) => conversions.set(id, conversion)),+ remove: vi.fn((id: string) => conversions.delete(id)),+ };+ const controller = new SuperTableActiveDirtyController(activeDirtyManagerService as never);++ const dirtyData = conversions.get(SetSuperTableMutation.id)?.getDirtyData({+ id: SetSuperTableMutation.id,+ params: {+ unitId: 'base-1',+ tableName: 'Costs',+ oldTableName: 'Pricing',+ reference: {+ sheetId: 'table-1',+ range: { startRow: 0, startColumn: 0, endRow: 9, endColumn: 2 },+ },+ },+ });++ expect(dirtyData).toEqual({+ dirtyRanges: [{+ unitId: 'base-1',+ sheetId: 'table-1',+ range: { startRow: 0, startColumn: 0, endRow: 9, endColumn: 2 },+ }],+ dirtySuperTableMap: { 'base-1': { Costs: '1', Pricing: '1' } },+ clearDependencyTreeCache: { 'base-1': { 'table-1': '1' } },+ });++ expect(conversions.get(RemoveSuperTableMutation.id)?.getDirtyData({+ id: RemoveSuperTableMutation.id,+ params: {+ unitId: 'base-1',+ tableName: 'Pricing',+ reference: {+ sheetId: 'table-1',+ range: { startRow: 0, startColumn: 0, endRow: 9, endColumn: 2 },+ },+ },+ })).toEqual({+ dirtyRanges: [{+ unitId: 'base-1',+ sheetId: 'table-1',+ range: { startRow: 0, startColumn: 0, endRow: 9, endColumn: 2 },+ }],+ dirtySuperTableMap: { 'base-1': { Pricing: '1' } },+ clearDependencyTreeCache: { 'base-1': { 'table-1': '1' } },+ });++ controller.dispose();+ expect(conversions.size).toBe(0);+ });+});diff --git a/packages/engine-formula/src/controllers/super-table-active-dirty.controller.ts b/packages/engine-formula/src/controllers/super-table-active-dirty.controller.tsnew file mode 100644index 0000000000..619621267c--- /dev/null+++ b/packages/engine-formula/src/controllers/super-table-active-dirty.controller.ts@@ -0,0 +1,74 @@+/**+ * 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 { IRemoveSuperTableMutationParam, ISetSuperTableMutationParam } from '../commands/mutations/set-super-table.mutation';+import { Disposable, toDisposable } from '@univerjs/core';+import { RemoveSuperTableMutation, SetSuperTableMutation } from '../commands/mutations/set-super-table.mutation';+import { IActiveDirtyManagerService } from '../services/active-dirty-manager.service';++export class SuperTableActiveDirtyController extends Disposable {+ constructor(@IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService) {+ super();+ this._initialize();+ }++ private _initialize(): void {+ this._activeDirtyManagerService.register(SetSuperTableMutation.id, {+ commandId: SetSuperTableMutation.id,+ getDirtyData: (command: ICommandInfo) => {+ const params = command.params as ISetSuperTableMutationParam;+ const tableNames = [params.tableName, params.oldTableName].filter((name): name is string => Boolean(name));+ return {+ dirtyRanges: [{ unitId: params.unitId, sheetId: params.reference.sheetId, range: params.reference.range }],+ dirtySuperTableMap: {+ [params.unitId]: Object.fromEntries(tableNames.map((name) => [name, '1'])),+ },+ clearDependencyTreeCache: {+ [params.unitId]: {+ [params.reference.sheetId]: '1',+ },+ },+ };+ },+ });++ this._activeDirtyManagerService.register(RemoveSuperTableMutation.id, {+ commandId: RemoveSuperTableMutation.id,+ getDirtyData: (command: ICommandInfo) => {+ const params = command.params as IRemoveSuperTableMutationParam;+ return {+ dirtyRanges: params.reference+ ? [{ unitId: params.unitId, sheetId: params.reference.sheetId, range: params.reference.range }]+ : undefined,+ dirtySuperTableMap: {+ [params.unitId]: {+ [params.tableName]: '1',+ },+ },+ clearDependencyTreeCache: params.reference+ ? { [params.unitId]: { [params.reference.sheetId]: '1' } }+ : undefined,+ };+ },+ });++ this.disposeWithMe(toDisposable(() => {+ this._activeDirtyManagerService.remove(SetSuperTableMutation.id);+ this._activeDirtyManagerService.remove(RemoveSuperTableMutation.id);+ }));+ }+}diff --git a/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.tsindex d2dea04196..ffc9dc22a1 100644--- a/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.ts+++ b/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.ts@@ -113,6 +113,33 @@ describe('generateAstNode defined name cache invalidation', () => {expect(harness.getParseCount()).toBe(2);});+ it('reuses the refreshed defined name AST after the dirty map is cleared', () => {+ const dirtyDefinedNameMap: Record<string, Record<string, string>> = {+ 'unit-1': {+ 'SUM(A1)': 'another formula text',+ },+ };+ const harness = createHarness(dirtyDefinedNameMap);++ generateAstNode(+ 'unit-1',+ '=SUM(A1)',+ harness.lexer as never,+ harness.astTreeBuilder as never,+ harness.currentConfigService as never+ );+ delete dirtyDefinedNameMap['unit-1'];+ generateAstNode(+ 'unit-1',+ '=SUM(A1)',+ harness.lexer as never,+ harness.astTreeBuilder as never,+ harness.currentConfigService as never+ );++ expect(harness.getParseCount()).toBe(1);+ });+it('reuses cache when dirty defined name key matches another unit', () => {const harness = createHarness({'unit-2': {@@ -188,6 +215,33 @@ describe('generateAstNode defined name cache invalidation', () => {expect(harness.getParseCount()).toBe(2);});+ it('reuses the refreshed super table AST after the dirty map is cleared', () => {+ const dirtySuperTableMap: Record<string, Record<string, string>> = {+ 'unit-1': {+ Table1: '1',+ },+ };+ const harness = createHarness({}, dirtySuperTableMap);++ generateAstNode(+ 'unit-1',+ '=SUM(Table1[col1])',+ harness.lexer as never,+ harness.astTreeBuilder as never,+ harness.currentConfigService as never+ );+ delete dirtySuperTableMap['unit-1'];+ generateAstNode(+ 'unit-1',+ '=SUM(Table1[col1])',+ harness.lexer as never,+ harness.astTreeBuilder as never,+ harness.currentConfigService as never+ );++ expect(harness.getParseCount()).toBe(1);+ });+it('treats dirty super table names as literal text when building cache invalidation patterns', () => {const harness = createHarness({}, {'unit-1': {@@ -220,6 +274,31 @@ describe('generateAstNode defined name cache invalidation', () => {expect(harness.getParseCount()).toBe(2);});+ it('invalidates table references whose names contain spaces', () => {+ const harness = createHarness({}, {+ 'unit-1': {+ 'Regional Costs': '1',+ },+ });++ generateAstNode(+ 'unit-1',+ '=SUM(Regional Costs[[#This Row],[Freight]])',+ harness.lexer as never,+ harness.astTreeBuilder as never,+ harness.currentConfigService as never+ );+ generateAstNode(+ 'unit-1',+ '=SUM(Regional Costs[[#This Row],[Freight]])',+ harness.lexer as never,+ harness.astTreeBuilder as never,+ harness.currentConfigService as never+ );++ expect(harness.getParseCount()).toBe(2);+ });+it('reuses cache when formula references a dirty super table in another unit', () => {const harness = createHarness({}, {'unit-2': {diff --git a/packages/engine-formula/src/engine/utils/generate-ast-node.ts b/packages/engine-formula/src/engine/utils/generate-ast-node.tsindex dd1dd23f03..d74240ff13 100644--- a/packages/engine-formula/src/engine/utils/generate-ast-node.ts+++ b/packages/engine-formula/src/engine/utils/generate-ast-node.ts@@ -55,9 +55,13 @@ export function generateAstNode(// refOffsetX and refOffsetY are separated by -, otherwise x:1 y:10 will be repeated with x:11 y:0let astNode: Nullable<AstRootNode> = FORMULA_AST_CACHE.get(cacheKey);- const noCache = checkIsChangedByDefinedName(unitId, formulaString, currentConfigService) || checkIsChangedBySuperTable(unitId, formulaString, currentConfigService);+ // Dirty registry metadata invalidates the cached AST for this calculation because+ // defined names and SuperTable references are resolved while the AST is built.+ const shouldRebuildAst =+ checkIsChangedByDefinedName(unitId, formulaString, currentConfigService) ||+ checkIsChangedBySuperTable(unitId, formulaString, currentConfigService);- if (!noCache && astNode && !isDirtyDefinedForNode(astNode, currentConfigService, unitId)) {+ if (!shouldRebuildAst && astNode && !isDirtyDefinedForNode(astNode, currentConfigService, unitId)) {// astNode.setRefOffset(refOffsetX, refOffsetY);return astNode;}@@ -78,9 +82,11 @@ export function generateAstNode(}// astNode.setRefOffset(refOffsetX, refOffsetY);- if (!noCache) {- FORMULA_AST_CACHE.set(cacheKey, astNode);- }+ // Rebuilding and caching are separate concerns: dirty metadata prevents reading+ // the old AST, while the newly parsed AST reflects the current registry and must+ // replace it. Otherwise, after the dirty map is cleared, an ordinary range+ // recalculation can fall back to the stale pre-registration AST.+ FORMULA_AST_CACHE.set(cacheKey, astNode);return astNode;}diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex 3c8b09b87a..8a5c8548dd 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -124,6 +124,7 @@ export {SetSuperTableOptionMutation,} from './commands/mutations/set-super-table.mutation';export type {+ IRemoveSuperTableMutationParam,ISetSuperTableMutationParam,ISetSuperTableMutationSearchParam,} from './commands/mutations/set-super-table.mutation';@@ -135,6 +136,7 @@ export {} from './config/config';export type { IUniverEngineFormulaConfig } from './config/config';export { CalculateController } from './controllers/calculate.controller';+export { SuperTableActiveDirtyController } from './controllers/super-table-active-dirty.controller';export { Lexer } from './engine/analysis/lexer';export { LexerNode } from './engine/analysis/lexer-node';export { LexerTreeBuilder } from './engine/analysis/lexer-tree-builder';@@ -272,6 +274,7 @@ export {IFeatureCalculationManagerService,} from './services/feature-calculation-manager.service';export type { IFeatureCalculationManagerParam } from './services/feature-calculation-manager.service';+export { FormulaCalculationTriggerService } from './services/formula-calculation-trigger.service';export type { IFormulaInfo, IOtherFormulaResult } from './services/formula-common';export { FormulaResultStatus } from './services/formula-common';export { FunctionService } from './services/function.service';diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.tsindex 61e271313e..f8af4b137d 100644--- a/packages/engine-formula/src/plugin.ts+++ b/packages/engine-formula/src/plugin.ts@@ -25,6 +25,7 @@ import { FormulaController } from './controllers/formula.controller';import { SetDependencyController } from './controllers/set-dependency.controller';import { SetFeatureCalculationController } from './controllers/set-feature-calculation.controller';import { SetOtherFormulaController } from './controllers/set-other-formula.controller';+import { SuperTableActiveDirtyController } from './controllers/super-table-active-dirty.controller';// import { SetSuperTableController } from './controllers/set-super-table.controller';import { Lexer } from './engine/analysis/lexer';import { LexerTreeBuilder } from './engine/analysis/lexer-tree-builder';@@ -51,6 +52,7 @@ import {FeatureCalculationManagerService,IFeatureCalculationManagerService,} from './services/feature-calculation-manager.service';+import { FormulaCalculationTriggerService } from './services/formula-calculation-trigger.service';import { FunctionService, IFunctionService } from './services/function.service';import { GlobalComputingStatusService } from './services/global-computing-status.service';import {@@ -92,6 +94,7 @@ export class UniverFormulaEnginePlugin extends Plugin {override onReady(): void {touchDependencies(this._injector, [[FormulaController],+ [SuperTableActiveDirtyController],// [SetSuperTableController],]);@@ -122,6 +125,7 @@ export class UniverFormulaEnginePlugin extends Plugin {[IFunctionService, { useClass: FunctionService }],[IDefinedNamesService, { useClass: DefinedNamesService }],[IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],+ [FormulaCalculationTriggerService],[RegisterOtherFormulaService],[IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }],[ISheetRowFilteredService, { useClass: SheetRowFilteredService }],@@ -131,6 +135,7 @@ export class UniverFormulaEnginePlugin extends Plugin {[FormulaDataModel],//Controllers[FormulaController],+ [SuperTableActiveDirtyController],// [SetSuperTableController],[ComputingStatusReporterController],];diff --git a/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts b/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.tsnew file mode 100644index 0000000000..153721cb33--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts@@ -0,0 +1,134 @@+/**+ * 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, ICommandService, IExecutionOptions } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationStartMutation,+ SetFormulaCalculationStopMutation,+} from '../../commands/mutations/set-formula-calculation.mutation';+import { FormulaCalculationTriggerService } from '../formula-calculation-trigger.service';+import { FormulaExecutedStateType } from '../runtime.service';++function createTestBed() {+ let listener: ((command: ICommandInfo, options?: IExecutionOptions) => void) | undefined;+ const executed: Array<{ id: string; params: unknown; options: unknown }> = [];+ const conversions = new Map<string, { commandId: string; shouldTrigger?: () => boolean; getDirtyData: (command: ICommandInfo) => object }>();+ const commandService = {+ onCommandExecuted: vi.fn((callback: typeof listener) => {+ listener = callback;+ return { dispose: vi.fn() };+ }),+ executeCommand: vi.fn(async (id: string, params: unknown, options?: IExecutionOptions) => {+ executed.push({ id, params, options });+ listener?.({ id, params } as ICommandInfo, options);+ return true;+ }),+ } as unknown as ICommandService;+ const activeDirtyManagerService = {+ get: (id: string) => conversions.get(id),+ };+ const service = new FormulaCalculationTriggerService(commandService, activeDirtyManagerService as never);++ return {+ service,+ executed,+ conversions,+ emit: (command: ICommandInfo, options?: IExecutionOptions) => listener?.(command, options),+ };+}++describe('FormulaCalculationTriggerService', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('merges dirty data from different unit types into one calculation', async () => {+ const testBed = createTestBed();+ testBed.conversions.set('sheet-dirty', {+ commandId: 'sheet-dirty',+ getDirtyData: () => ({+ dirtyRanges: [{ unitId: 'sheet-unit', sheetId: 'sheet-1', range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } }],+ }),+ });+ testBed.conversions.set('base-dirty', {+ commandId: 'base-dirty',+ getDirtyData: () => ({+ dirtyRanges: [{ unitId: 'base-unit', sheetId: 'table-1', range: { startRow: 1, startColumn: 2, endRow: 1, endColumn: 2 } }],+ }),+ });++ testBed.emit({ id: 'sheet-dirty' } as ICommandInfo);+ testBed.emit({ id: 'base-dirty' } as ICommandInfo);+ await vi.advanceTimersByTimeAsync(100);++ expect(testBed.executed).toHaveLength(1);+ expect(testBed.executed[0]).toMatchObject({+ id: SetFormulaCalculationStartMutation.id,+ options: { onlyLocal: true },+ params: {+ dirtyRanges: [+ { unitId: 'sheet-unit', sheetId: 'sheet-1' },+ { unitId: 'base-unit', sheetId: 'table-1' },+ ],+ },+ });+ testBed.service.dispose();+ });++ it('keeps all pending dirty data when an active calculation is stopped and restarted', async () => {+ const testBed = createTestBed();+ testBed.conversions.set('base-dirty', {+ commandId: 'base-dirty',+ getDirtyData: () => ({ dirtySuperTableMap: { 'base-unit': { Pricing: '1' } } }),+ });++ testBed.emit({ id: SetFormulaCalculationStartMutation.id, params: {} } as ICommandInfo);+ testBed.emit({ id: 'base-dirty' } as ICommandInfo);+ await vi.advanceTimersByTimeAsync(100);++ expect(testBed.executed[0]).toMatchObject({ id: SetFormulaCalculationStopMutation.id });++ testBed.emit({+ id: SetFormulaCalculationNotificationMutation.id,+ params: { functionsExecutedState: FormulaExecutedStateType.STOP_EXECUTION },+ } as ICommandInfo);++ expect(testBed.executed[1]).toMatchObject({+ id: SetFormulaCalculationStartMutation.id,+ params: { dirtySuperTableMap: { 'base-unit': { Pricing: '1' } } },+ });+ testBed.service.dispose();+ });++ it('honors conversion trigger predicates before scheduling', async () => {+ const testBed = createTestBed();+ testBed.conversions.set('local-result', {+ commandId: 'local-result',+ shouldTrigger: () => false,+ getDirtyData: () => ({ forceCalculation: true }),+ });++ testBed.emit({ id: 'local-result' } as ICommandInfo);+ await vi.advanceTimersByTimeAsync(100);++ expect(testBed.executed).toEqual([]);+ testBed.service.dispose();+ });+});diff --git a/packages/engine-formula/src/services/active-dirty-manager.service.ts b/packages/engine-formula/src/services/active-dirty-manager.service.tsindex 70f4558047..398e046298 100644--- a/packages/engine-formula/src/services/active-dirty-manager.service.ts+++ b/packages/engine-formula/src/services/active-dirty-manager.service.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICommandInfo, IUnitRange, Nullable } from '@univerjs/core';+import type { ICommandInfo, IExecutionOptions, IUnitRange, Nullable } from '@univerjs/core';import type {IDirtyUnitDefinedNameMap,IDirtyUnitFeatureMap,@@ -26,6 +26,7 @@ import { createIdentifier, Disposable } from '@univerjs/core';export interface IDirtyConversionManagerParams {commandId: string;+ shouldTrigger?: (command: ICommandInfo, options?: IExecutionOptions) => boolean;getDirtyData: (command: ICommandInfo) => {forceCalculation?: boolean;dirtyRanges?: IUnitRange[];diff --git a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts b/packages/engine-formula/src/services/formula-calculation-trigger.service.tsnew file mode 100644index 0000000000..2b4ecc0989--- /dev/null+++ b/packages/engine-formula/src/services/formula-calculation-trigger.service.ts@@ -0,0 +1,228 @@+/**+ * 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, IUnitRange, Nullable } from '@univerjs/core';+import type { IDirtyUnitFeatureMap } from '../basics/common';+import type { ISetFormulaCalculationNotificationMutation } from '../commands/mutations/set-formula-calculation.mutation';+import type { IFormulaDirtyData } from './current-data.service';+import { Disposable, ICommandService } from '@univerjs/core';+import {+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationStartMutation,+ SetFormulaCalculationStopMutation,+} from '../commands/mutations/set-formula-calculation.mutation';+import { IActiveDirtyManagerService } from './active-dirty-manager.service';+import { FormulaExecutedStateType } from './runtime.service';++const LOCAL_ONLY = { onlyLocal: true };+const CALCULATION_DEBOUNCE_TIME = 100;++type IDirtyUnitStringMap = Record<string, Nullable<Record<string, string>>>;++/**+ * Converts commands registered in ActiveDirtyManagerService into one formula+ * calculation stream. Product packages register dirty conversions, while this+ * service owns batching and restart semantics for every unit type.+ */+export class FormulaCalculationTriggerService extends Disposable {+ private _waitingCommandQueue: ICommandInfo[] = [];+ private _executingDirtyData = createEmptyDirtyData();+ private _timer: ReturnType<typeof setTimeout> | undefined;+ private _executionInProgress = false;+ private _restartCalculation = false;++ constructor(+ @ICommandService private readonly _commandService: ICommandService,+ @IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService+ ) {+ super();+ this._initialize();+ }++ override dispose(): void {+ clearTimeout(this._timer);+ this._waitingCommandQueue = [];+ this._executingDirtyData = createEmptyDirtyData();+ super.dispose();+ }++ private _initialize(): void {+ this.disposeWithMe(this._commandService.onCommandExecuted((command, options) => {+ if (command.id === SetFormulaCalculationStartMutation.id) {+ this._executionInProgress = true;+ return;+ }++ if (command.id === SetFormulaCalculationNotificationMutation.id) {+ this._handleCalculationNotification(command.params as ISetFormulaCalculationNotificationMutation);+ return;+ }++ const conversion = this._activeDirtyManagerService.get(command.id);+ if (!conversion) {+ return;+ }+ if (conversion.shouldTrigger?.(command, options) === false) {+ return;+ }++ this._waitingCommandQueue.push(command);+ clearTimeout(this._timer);+ this._timer = setTimeout(() => this._flush(), CALCULATION_DEBOUNCE_TIME);+ }));+ }++ private _flush(): void {+ const dirtyData = this._generateDirty(this._waitingCommandQueue);+ this._waitingCommandQueue = [];+ this._timer = undefined;+ if (!hasDirtyData(dirtyData)) {+ return;+ }++ this._executingDirtyData = mergeDirtyData(this._executingDirtyData, dirtyData);+ if (this._executionInProgress) {+ this._restartCalculation = true;+ void this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {}, LOCAL_ONLY);+ return;+ }++ this._startCalculation();+ }++ private _startCalculation(): void {+ this._executionInProgress = true;+ void this._commandService.executeCommand(+ SetFormulaCalculationStartMutation.id,+ { ...this._executingDirtyData },+ LOCAL_ONLY+ );+ }++ private _handleCalculationNotification(params: ISetFormulaCalculationNotificationMutation): void {+ if (params.stageInfo != null) {+ this._executionInProgress = true;+ return;+ }++ const state = params.functionsExecutedState;+ if (state == null) {+ return;+ }++ this._executionInProgress = false;+ if (state === FormulaExecutedStateType.STOP_EXECUTION && this._restartCalculation) {+ this._restartCalculation = false;+ this._startCalculation();+ return;+ }++ this._restartCalculation = false;+ this._executingDirtyData = createEmptyDirtyData();+ }++ private _generateDirty(commands: ICommandInfo[]): IFormulaDirtyData {+ return commands.reduce<IFormulaDirtyData>((result, command) => {+ const conversion = this._activeDirtyManagerService.get(command.id);+ return conversion ? mergeDirtyData(result, conversion.getDirtyData(command)) : result;+ }, createEmptyDirtyData());+ }+}++function createEmptyDirtyData(): IFormulaDirtyData {+ return {+ forceCalculation: false,+ dirtyRanges: [],+ dirtyNameMap: {},+ dirtyDefinedNameMap: {},+ dirtySuperTableMap: {},+ dirtyUnitFeatureMap: {},+ dirtyUnitOtherFormulaMap: {},+ clearDependencyTreeCache: {},+ };+}++function mergeDirtyData(left: IFormulaDirtyData, right: Partial<IFormulaDirtyData>): IFormulaDirtyData {+ const dirtyRanges = [...left.dirtyRanges];+ mergeDirtyRanges(dirtyRanges, right.dirtyRanges ?? []);+ return {+ dirtyRanges,+ dirtyNameMap: mergeDirtyUnitStringMap(left.dirtyNameMap, right.dirtyNameMap),+ dirtyDefinedNameMap: mergeDirtyUnitStringMap(left.dirtyDefinedNameMap, right.dirtyDefinedNameMap),+ dirtySuperTableMap: mergeDirtyUnitStringMap(left.dirtySuperTableMap ?? {}, right.dirtySuperTableMap),+ dirtyUnitFeatureMap: mergeDirtyUnitNestedMap(left.dirtyUnitFeatureMap, right.dirtyUnitFeatureMap),+ dirtyUnitOtherFormulaMap: mergeDirtyUnitNestedMap(left.dirtyUnitOtherFormulaMap, right.dirtyUnitOtherFormulaMap),+ clearDependencyTreeCache: mergeDirtyUnitStringMap(left.clearDependencyTreeCache, right.clearDependencyTreeCache),+ forceCalculation: left.forceCalculation || Boolean(right.forceCalculation),+ };+}++function mergeDirtyRanges(target: IUnitRange[], source: IUnitRange[]): void {+ source.forEach((range) => {+ const duplicate = target.some((item) =>+ item.unitId === range.unitId &&+ item.sheetId === range.sheetId &&+ item.range.startRow === range.range.startRow &&+ item.range.startColumn === range.range.startColumn &&+ item.range.endRow === range.range.endRow &&+ item.range.endColumn === range.range.endColumn+ );+ if (!duplicate) {+ target.push(range);+ }+ });+}++function mergeDirtyUnitStringMap(left: IDirtyUnitStringMap, right?: IDirtyUnitStringMap): IDirtyUnitStringMap {+ const result: IDirtyUnitStringMap = { ...left };+ Object.entries(right ?? {}).forEach(([unitId, values]) => {+ result[unitId] = { ...result[unitId], ...values };+ });+ return result;+}++function mergeDirtyUnitNestedMap(left: IDirtyUnitFeatureMap, right?: IDirtyUnitFeatureMap): IDirtyUnitFeatureMap {+ const result: IDirtyUnitFeatureMap = { ...left };+ Object.entries(right ?? {}).forEach(([unitId, sheets]) => {+ const unitResult: NonNullable<IDirtyUnitFeatureMap[string]> = { ...result[unitId] };+ Object.entries(sheets ?? {}).forEach(([sheetId, values]) => {+ unitResult[sheetId] = { ...unitResult[sheetId], ...values };+ });+ result[unitId] = unitResult;+ });+ return result;+}++function hasDirtyData(dirtyData: IFormulaDirtyData): boolean {+ return dirtyData.forceCalculation ||+ dirtyData.dirtyRanges.length > 0 ||+ hasNestedValue(dirtyData.dirtyNameMap) ||+ hasNestedValue(dirtyData.dirtyDefinedNameMap) ||+ hasNestedValue(dirtyData.dirtySuperTableMap) ||+ hasNestedValue(dirtyData.dirtyUnitFeatureMap) ||+ hasNestedValue(dirtyData.dirtyUnitOtherFormulaMap) ||+ hasNestedValue(dirtyData.clearDependencyTreeCache);+}++function hasNestedValue(value: unknown): boolean {+ if (value == null) {+ return false;+ }+ if (typeof value !== 'object') {+ return true;+ }+ return Object.values(value as Record<string, unknown>).some(hasNestedValue);+}diff --git a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.tsindex 7db7306504..5e7991b4bb 100644--- a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts@@ -25,7 +25,6 @@ import {IActiveDirtyManagerService,RemoveDefinedNameMutation,SetDefinedNameMutation,- SetSuperTableMutation,SetTriggerFormulaCalculationStartMutation,} from '@univerjs/engine-formula';import {@@ -81,6 +80,12 @@ function getDirtyData(testBed: ITestBed, command: ICommandInfo) {return conversion!.getDirtyData(command);}+function shouldTrigger(testBed: ITestBed, command: ICommandInfo) {+ const conversion = testBed.injector.get(IActiveDirtyManagerService).get(command.id);+ expect(conversion).toBeDefined();+ return conversion!.shouldTrigger?.(command);+}+describe('ActiveDirtyController', () => {let testBed: ITestBed;@@ -110,7 +115,7 @@ describe('ActiveDirtyController', () => {testBed.injector.get(ActiveDirtyController);- expect(getDirtyData(testBed, {+ expect(shouldTrigger(testBed, {id: SetRangeValuesMutation.id,params: {unitId: 'test',@@ -122,7 +127,7 @@ describe('ActiveDirtyController', () => {},},},- } as ICommandInfo)).toEqual({});+ } as ICommandInfo)).toBe(false);expect(getDirtyData(testBed, {id: SetRangeValuesMutation.id,@@ -408,53 +413,4 @@ describe('ActiveDirtyController', () => {},});});-- it('should dirty the table range and clear dependency cache when a super table changes', () => {- testBed = createControllerTestBed();- testBed.injector.get(ActiveDirtyController);-- expect(getDirtyData(testBed, {- id: SetSuperTableMutation.id,- params: {- unitId: 'test',- tableName: 'Table1',- reference: {- sheetId: 'sheet1',- range: {- startRow: 0,- startColumn: 1,- endRow: 5,- endColumn: 2,- },- titleMap: new Map([- ['Column1', 0],- ['Column3', 1],- ]),- },- },- } as ICommandInfo)).toEqual({- dirtyRanges: [- {- unitId: 'test',- sheetId: 'sheet1',- range: {- startRow: 0,- startColumn: 1,- endRow: 5,- endColumn: 2,- },- },- ],- dirtySuperTableMap: {- test: {- Table1: '1',- },- },- clearDependencyTreeCache: {- test: {- sheet1: '1',- },- },- });- });});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 a9cddb6337..9c3c65bfcc 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@@ -26,6 +26,7 @@ import {ActiveDirtyManagerService,ENGINE_FORMULA_CYCLE_REFERENCE_COUNT,ENGINE_FORMULA_RETURN_DEPENDENCY_TREE,+ FormulaCalculationTriggerService,FormulaDataModel,FormulaExecutedStateType,FormulaExecuteStageType,@@ -73,6 +74,7 @@ function createWorkbookData(): IWorkbookData {function createControllerTestBed() {const dependencies: Dependency[] = [[IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],+ [FormulaCalculationTriggerService],[RegisterOtherFormulaService],[FormulaCalculationSessionService],[FormulaCalculationSessionController],@@ -206,6 +208,7 @@ describe('TriggerCalculationController', () => {});testBed.activeDirtyManagerService.register(SetRangeValuesMutation.id, {commandId: SetRangeValuesMutation.id,+ shouldTrigger: (command) => (command.params as { trigger?: string })?.trigger !== SetStyleCommand.id,getDirtyData: () => ({dirtyRanges: [{ unitId: 'test', sheetId: 'sheet1', range: { startRow: 9, startColumn: 9, endRow: 9, endColumn: 9 } }],}),diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.tsindex f7c7b606e2..5ec928c09c 100644--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts@@ -15,7 +15,7 @@*/import type { ICellData, ICommandInfo, IObjectMatrixPrimitiveType, IRange, IUnitRange, Nullable } from '@univerjs/core';-import type { IDirtyUnitDefinedNameMap, IDirtyUnitSheetNameMap, IFormulaDirtyData, ISetDefinedNameMutationParam, ISetSuperTableMutationParam } from '@univerjs/engine-formula';+import type { IDirtyUnitDefinedNameMap, IDirtyUnitSheetNameMap, IFormulaDirtyData, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';import type {IInsertColMutationParams,IInsertRowMutationParams,@@ -37,8 +37,9 @@ import {IUniverInstanceService,ObjectMatrix,} from '@univerjs/core';-import { FormulaDataModel, IActiveDirtyManagerService, RemoveDefinedNameMutation, SetDefinedNameMutation, SetSuperTableMutation, SetTriggerFormulaCalculationStartMutation } from '@univerjs/engine-formula';+import { FormulaDataModel, IActiveDirtyManagerService, RemoveDefinedNameMutation, SetDefinedNameMutation, SetTriggerFormulaCalculationStartMutation } from '@univerjs/engine-formula';import {+ ClearSelectionFormatCommand,InsertColMutation,InsertRowMutation,InsertSheetMutation,@@ -49,6 +50,7 @@ import {RemoveRowMutation,RemoveSheetMutation,ReorderRangeMutation,+ SetBorderCommand,SetRangeValuesMutation,SetRowHiddenMutation,SetRowVisibleMutation,@@ -73,16 +75,15 @@ export class ActiveDirtyController extends Disposable {private _initialConversion() {this._activeDirtyManagerService.register(SetRangeValuesMutation.id, {commandId: SetRangeValuesMutation.id,+ shouldTrigger: (command, options) => {+ const params = command.params as ISetRangeValuesMutationParams;+ return !options?.onlyLocal &&+ params.trigger !== SetStyleCommand.id &&+ params.trigger !== SetBorderCommand.id &&+ params.trigger !== ClearSelectionFormatCommand.id;+ },getDirtyData: (command: ICommandInfo) => {const params = command.params as ISetRangeValuesMutationParams;- /**- * Changes in the cell value caused by the formula or style- * will not trigger the formula to be marked as dirty for calculation.- */- if (params.trigger === SetStyleCommand.id) {- return {};- }-return {dirtyRanges: this._getSetRangeValuesMutationDirtyRange(params),};@@ -98,8 +99,6 @@ export class ActiveDirtyController extends Disposable {this._initialSheet();this._initialDefinedName();-- this._initialSuperTable();}private _initialMove() {@@ -311,31 +310,6 @@ export class ActiveDirtyController extends Disposable {});}- private _initialSuperTable() {- this._activeDirtyManagerService.register(SetSuperTableMutation.id, {- commandId: SetSuperTableMutation.id,- getDirtyData: (command: ICommandInfo) => {- const params = command.params as ISetSuperTableMutationParam;- const { unitId, reference } = params;- const { sheetId, range } = reference;-- return {- dirtyRanges: [{ unitId, sheetId, range }],- dirtySuperTableMap: {- [unitId]: {- [params.tableName]: '1',- },- },- clearDependencyTreeCache: {- [unitId]: {- [sheetId]: '1',- },- },- };- },- });- }-private _getDefinedNameMutation(definedName: ISetDefinedNameMutationParam | null | undefined): IDirtyUnitDefinedNameMap {if (definedName == null) {return {};diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.tsindex fd24a3ec55..5e81973e6f 100644--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts@@ -26,7 +26,6 @@ import type {ISetFormulaCalculationNotificationMutation,ISetFormulaCalculationStartMutation,} from '@univerjs/engine-formula';-import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';import type { IUniverSheetsFormulaBaseConfig } from '../config/config';import type { LocaleKey } from '../locale/types';import {@@ -42,10 +41,10 @@ import {import {ENGINE_FORMULA_CYCLE_REFERENCE_COUNT,ENGINE_FORMULA_RETURN_DEPENDENCY_TREE,+ FormulaCalculationTriggerService,FormulaDataModel,FormulaExecutedStateType,FormulaExecuteStageType,- IActiveDirtyManagerService,RegisterOtherFormulaService,SetFormulaCalculationNotificationMutation,SetFormulaCalculationStartMutation,@@ -53,12 +52,6 @@ import {SetFormulaStringBatchCalculationMutation,SetTriggerFormulaCalculationStartMutation,} from '@univerjs/engine-formula';-import {- ClearSelectionFormatCommand,- SetBorderCommand,- SetRangeValuesMutation,- SetStyleCommand,-} from '@univerjs/sheets';import { BehaviorSubject } from 'rxjs';import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from '../config/config';@@ -78,24 +71,7 @@ const NilProgress: ICalculationProgress = { done: 0, count: 0 };const lo = { onlyLocal: true };-type IDirtyUnitStringMap = Record<string, Nullable<Record<string, string>>>;-export class TriggerCalculationController extends Disposable {- private _waitingCommandQueue: ICommandInfo[] = [];-- private _executingDirtyData: IFormulaDirtyData = {- forceCalculation: false,- dirtyRanges: [],- dirtyNameMap: {},- dirtyDefinedNameMap: {},- dirtySuperTableMap: {},- dirtyUnitFeatureMap: {},- dirtyUnitOtherFormulaMap: {},- clearDependencyTreeCache: {},- };-- private _setTimeoutKey: NodeJS.Timeout | number = -1;-private _startExecutionTime: number = 0;private _totalCalculationTaskCount: number = 0;@@ -104,8 +80,6 @@ export class TriggerCalculationController extends Disposable {private _executionInProgressParams: Nullable<IExecutionInProgressParams> = null;- private _restartCalculation = false;-private readonly _progress$ = new BehaviorSubject<ICalculationProgress>(NilProgress);readonly progress$ = this._progress$.asObservable();@@ -152,7 +126,7 @@ export class TriggerCalculationController extends Disposable {constructor(@ICommandService private readonly _commandService: ICommandService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService,+ @Inject(FormulaCalculationTriggerService) formulaCalculationTriggerService: FormulaCalculationTriggerService,@ILogService private readonly _logService: ILogService,@IConfigService private readonly _configService: IConfigService,@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,@@ -161,6 +135,8 @@ export class TriggerCalculationController extends Disposable {) {super();+ void formulaCalculationTriggerService;+this._commandExecutedListener();this._initialExecuteFormulaProcessListener();@@ -178,8 +154,6 @@ export class TriggerCalculationController extends Disposable {this._progress$.next(NilProgress);this._progress$.complete();- // clear timer when disposed- clearTimeout(this._setTimeoutKey);}private _getCalculationMode(): CalculationMode {@@ -203,207 +177,6 @@ export class TriggerCalculationController extends Disposable {}}));-- this.disposeWithMe(- this._commandService.onCommandExecuted((command: ICommandInfo, options) => {- if (!this._activeDirtyManagerService.get(command.id)) {- return;- }-- if (command.id === SetRangeValuesMutation.id) {- const params = command.params as ISetRangeValuesMutationParams;-- if (- (options && options.onlyLocal === true) ||- params.trigger === SetStyleCommand.id ||- params.trigger === SetBorderCommand.id ||- params.trigger === ClearSelectionFormatCommand.id- ) {- return;- }- }-- this._waitingCommandQueue.push(command);-- clearTimeout(this._setTimeoutKey);-- this._setTimeoutKey = setTimeout(() => {- const dirtyData = this._generateDirty(this._waitingCommandQueue);- this._executingDirtyData = this._mergeDirty(this._executingDirtyData, dirtyData);-- if (this._executionInProgressParams == null) {- this._commandService.executeCommand(SetFormulaCalculationStartMutation.id, { ...this._executingDirtyData }, lo);- } else {- this._restartCalculation = true;- this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {});- }-- this._waitingCommandQueue = [];- }, 100);- })- );- }-- private _generateDirty(commands: ICommandInfo[]) {- const allDirtyRanges: IUnitRange[] = [];- const allDirtyNameMap: IDirtyUnitSheetNameMap = {};- const allDirtyDefinedNameMap: IDirtyUnitDefinedNameMap = {};- const allDirtySuperTableMap: IDirtyUnitSuperTableMap = {};- const allDirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};- const allDirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = {};- const allClearDependencyTreeCache: IDirtyUnitSheetNameMap = {};- let allForceCalculation = false;-- // const numfmtItemMap: INumfmtItemMap = Tools.deepClone(this._formulaDataModel.getNumfmtItemMap());-- for (const command of commands) {- const conversion = this._activeDirtyManagerService.get(command.id);-- if (conversion == null) {- continue;- }-- const params = conversion.getDirtyData(command);-- const { dirtyRanges, dirtyNameMap, dirtyDefinedNameMap, dirtySuperTableMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap, clearDependencyTreeCache, forceCalculation = false } = params;-- if (dirtyRanges != null) {- this._mergeDirtyRanges(allDirtyRanges, dirtyRanges);- }-- if (dirtyNameMap != null) {- this._mergeDirtyUnitStringMap(allDirtyNameMap, dirtyNameMap);- }-- if (dirtyDefinedNameMap != null) {- this._mergeDirtyUnitStringMap(allDirtyDefinedNameMap, dirtyDefinedNameMap);- }-- if (dirtySuperTableMap != null) {- this._mergeDirtyUnitStringMap(allDirtySuperTableMap, dirtySuperTableMap);- }-- if (dirtyUnitFeatureMap != null) {- this._mergeDirtyUnitFeatureOrOtherFormulaMap(allDirtyUnitFeatureMap, dirtyUnitFeatureMap);- }-- if (dirtyUnitOtherFormulaMap != null) {- this._mergeDirtyUnitFeatureOrOtherFormulaMap(allDirtyUnitOtherFormulaMap, dirtyUnitOtherFormulaMap);- }-- if (clearDependencyTreeCache != null) {- this._mergeDirtyUnitStringMap(allClearDependencyTreeCache, clearDependencyTreeCache);- }-- allForceCalculation = allForceCalculation || forceCalculation;- }-- return {- dirtyRanges: allDirtyRanges,- dirtyNameMap: allDirtyNameMap,- dirtyDefinedNameMap: allDirtyDefinedNameMap,- dirtySuperTableMap: allDirtySuperTableMap,- dirtyUnitFeatureMap: allDirtyUnitFeatureMap,- dirtyUnitOtherFormulaMap: allDirtyUnitOtherFormulaMap,- forceCalculation: allForceCalculation,- clearDependencyTreeCache: allClearDependencyTreeCache,- // numfmtItemMap,- };- }-- private _mergeDirty(dirtyData1: IFormulaDirtyData, dirtyData2: IFormulaDirtyData) {- const allDirtyRanges: IUnitRange[] = [...dirtyData1.dirtyRanges, ...dirtyData2.dirtyRanges];- const allDirtyNameMap: IDirtyUnitSheetNameMap = { ...dirtyData1.dirtyNameMap };- const allDirtyDefinedNameMap: IDirtyUnitDefinedNameMap = { ...dirtyData1.dirtyDefinedNameMap };- const allDirtySuperTableMap: IDirtyUnitSuperTableMap = { ...dirtyData1.dirtySuperTableMap };- const allDirtyUnitFeatureMap: IDirtyUnitFeatureMap = { ...dirtyData1.dirtyUnitFeatureMap };- const allDirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = { ...dirtyData1.dirtyUnitOtherFormulaMap };- const allClearDependencyTreeCache: IDirtyUnitSheetNameMap = { ...dirtyData1.clearDependencyTreeCache };-- this._mergeDirtyUnitStringMap(allDirtyNameMap, dirtyData2.dirtyNameMap);- this._mergeDirtyUnitStringMap(allDirtyDefinedNameMap, dirtyData2.dirtyDefinedNameMap);- this._mergeDirtyUnitStringMap(allDirtySuperTableMap, dirtyData2.dirtySuperTableMap || {});- this._mergeDirtyUnitFeatureOrOtherFormulaMap(allDirtyUnitFeatureMap, dirtyData2.dirtyUnitFeatureMap);- this._mergeDirtyUnitFeatureOrOtherFormulaMap(allDirtyUnitOtherFormulaMap, dirtyData2.dirtyUnitOtherFormulaMap);- this._mergeDirtyUnitStringMap(allClearDependencyTreeCache, dirtyData2.clearDependencyTreeCache);-- const allForceCalculating = dirtyData1.forceCalculation || dirtyData2.forceCalculation;-- return {- dirtyRanges: allDirtyRanges,- dirtyNameMap: allDirtyNameMap,- dirtyDefinedNameMap: allDirtyDefinedNameMap,- dirtySuperTableMap: allDirtySuperTableMap,- dirtyUnitFeatureMap: allDirtyUnitFeatureMap,- dirtyUnitOtherFormulaMap: allDirtyUnitOtherFormulaMap,- forceCalculation: allForceCalculating,- clearDependencyTreeCache: allClearDependencyTreeCache,- };- }-- /**- * dirtyRanges may overlap with the ranges in allDirtyRanges and need to be deduplicated- * @param allDirtyRanges- * @param dirtyRanges- */- private _mergeDirtyRanges(allDirtyRanges: IUnitRange[], dirtyRanges: IUnitRange[]) {- for (const range of dirtyRanges) {- let isDuplicate = false;- for (const existingRange of allDirtyRanges) {- // Check if the ranges are in the same unit and sheet- if (range.unitId === existingRange.unitId && range.sheetId === existingRange.sheetId) {- // Check if the ranges overlap- const { startRow, startColumn, endRow, endColumn } = range.range;- const { startRow: existingStartRow, startColumn: existingStartColumn, endRow: existingEndRow, endColumn: existingEndColumn } = existingRange.range;- if (- startRow === existingStartRow &&- startColumn === existingStartColumn &&- endRow === existingEndRow &&- endColumn === existingEndColumn- ) {- isDuplicate = true;- break;- }- }- }- if (!isDuplicate) {- allDirtyRanges.push(range);- }- }- }-- private _mergeDirtyUnitStringMap(allDirtyMap: IDirtyUnitStringMap, dirtyMap: IDirtyUnitStringMap) {- Object.keys(dirtyMap).forEach((unitId) => {- if (allDirtyMap[unitId] == null) {- allDirtyMap[unitId] = {};- }-- Object.keys(dirtyMap[unitId]!).forEach((dirtyKey) => {- if (dirtyMap[unitId]?.[dirtyKey]) {- allDirtyMap[unitId]![dirtyKey] = dirtyMap[unitId]![dirtyKey];- }- });- });- }-- private _mergeDirtyUnitFeatureOrOtherFormulaMap(- allDirtyUnitFeatureOrOtherFormulaMap: IDirtyUnitFeatureMap | IDirtyUnitOtherFormulaMap,- dirtyUnitFeatureOrOtherFormulaMap: IDirtyUnitFeatureMap | IDirtyUnitOtherFormulaMap- ) {- Object.keys(dirtyUnitFeatureOrOtherFormulaMap).forEach((unitId) => {- if (allDirtyUnitFeatureOrOtherFormulaMap[unitId] == null) {- allDirtyUnitFeatureOrOtherFormulaMap[unitId] = {};- }- Object.keys(dirtyUnitFeatureOrOtherFormulaMap[unitId]!).forEach((sheetId) => {- if (allDirtyUnitFeatureOrOtherFormulaMap[unitId]![sheetId] == null) {- allDirtyUnitFeatureOrOtherFormulaMap[unitId]![sheetId] = {};- }- Object.keys(dirtyUnitFeatureOrOtherFormulaMap[unitId]![sheetId]).forEach((featureIdOrFormulaId) => {- allDirtyUnitFeatureOrOtherFormulaMap[unitId]![sheetId][featureIdOrFormulaId] =- dirtyUnitFeatureOrOtherFormulaMap[unitId]![sheetId]![featureIdOrFormulaId] || false;- });- });- });}// eslint-disable-next-line max-lines-per-function@@ -483,7 +256,6 @@ export class TriggerCalculationController extends Disposable {switch (state) {case FormulaExecutedStateType.NOT_EXECUTED:result = 'No tasks are being executed anymore';- this._resetExecutingDirtyData();break;case FormulaExecutedStateType.STOP_EXECUTION:result = 'The execution of the formula has been stopped';@@ -496,12 +268,9 @@ export class TriggerCalculationController extends Disposable {if (calculationProcessCount === 0 || calculationProcessCount === -1) {result += `. Total time consumed: ${performance.now() - this._startExecutionTime} ms`;}-- this._resetExecutingDirtyData();break;case FormulaExecutedStateType.INITIAL:result = 'Waiting for calculation';- this._resetExecutingDirtyData();break;}@@ -522,18 +291,7 @@ export class TriggerCalculationController extends Disposable {this._totalCalculationTaskCount = 0;}- if (state === FormulaExecutedStateType.STOP_EXECUTION && this._restartCalculation) {- this._restartCalculation = false;- this._commandService.executeCommand(- SetFormulaCalculationStartMutation.id,- {- ...this._executingDirtyData,- },- lo- );- } else {- this._executionInProgressParams = null;- }+ this._executionInProgressParams = null;this._logService.debug('[TriggerCalculationController]', result);}@@ -541,19 +299,6 @@ export class TriggerCalculationController extends Disposable {);}- private _resetExecutingDirtyData() {- this._executingDirtyData = {- dirtyRanges: [],- dirtyNameMap: {},- dirtyDefinedNameMap: {},- dirtySuperTableMap: {},- dirtyUnitFeatureMap: {},- dirtyUnitOtherFormulaMap: {},- forceCalculation: false,- clearDependencyTreeCache: {},- };- }-private _initialExecuteFormula() {const calculationMode = this._getCalculationMode();const params = this._getDirtyDataByCalculationMode(calculationMode);diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.tsindex a9450433bb..fae030ae1c 100644--- a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts@@ -76,10 +76,19 @@ describe('SheetTableFormulaController', () => {});expect(executeCommand).toHaveBeenCalledTimes(4);- tableDelete$.next({ unitId: 'u1', tableName: 'Orders' });+ tableDelete$.next({+ unitId: 'u1',+ subUnitId: 's1',+ tableName: 'Orders',+ range: { startRow: 0, endRow: 5, startColumn: 0, endColumn: 2 },+ });expect(executeCommand).toHaveBeenLastCalledWith(RemoveSuperTableMutation.id, {unitId: 'u1',tableName: 'Orders',+ reference: {+ sheetId: 's1',+ range: { startRow: 0, endRow: 5, startColumn: 0, endColumn: 2 },+ },});controller.dispose();diff --git a/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts b/packages/sheets-table/src/controllers/sheet-table-formula.controller.tsindex 995f286000..621e8fc734 100644--- a/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts+++ b/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ISetSuperTableMutationParam, ISetSuperTableMutationSearchParam } from '@univerjs/engine-formula';+import type { IRemoveSuperTableMutationParam, ISetSuperTableMutationParam, ISetSuperTableMutationSearchParam } from '@univerjs/engine-formula';import type { Table } from '../models/table';import { Disposable, ICommandService, Inject } from '@univerjs/core';import { RemoveSuperTableMutation, SetSuperTableMutation } from '@univerjs/engine-formula';@@ -52,10 +52,14 @@ export class SheetTableFormulaController extends Disposable {);this.disposeWithMe(this._tableManager.tableDelete$.subscribe((event) => {- const { unitId, tableName } = event;- this._commandService.executeCommand<ISetSuperTableMutationSearchParam>(RemoveSuperTableMutation.id, {+ const { unitId, subUnitId, tableName, range } = event;+ this._commandService.executeCommand<IRemoveSuperTableMutationParam>(RemoveSuperTableMutation.id, {unitId,tableName,+ reference: {+ sheetId: subUnitId,+ range,+ },});}));