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(sheets-formula): invalidate affected worksheet references incrementally (#8110)

Univerdf03ff3357be
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index a60a25d877..31c7026b3f 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -254,6 +254,8 @@ export interface IUnitRowData {
}
export interface IFormulaDatasetConfig {
+ /** Sheet metadata changed; rebind and calculate affected references without forcing all formulas. */
+ dirtyReferenceUnits?: string[];
/** Recalculate iteration-sensitive groups and their dependents in these workbooks. */
dirtyIterationUnits?: string[];
/** Snapshot replay limits calculation to affected cycles and their required precedents. */
diff --git a/packages/engine-formula/src/controllers/calculate.controller.ts b/packages/engine-formula/src/controllers/calculate.controller.ts
index 1715cbad6f..3a834d1e4c 100644
--- a/packages/engine-formula/src/controllers/calculate.controller.ts
+++ b/packages/engine-formula/src/controllers/calculate.controller.ts
@@ -106,6 +106,7 @@ export class CalculateController extends Disposable {
private async _calculate(formulaDirtyData: Partial<IFormulaDirtyData>) {
const {
dirtyIterationUnits,
+ dirtyReferenceUnits,
forceCalculation: forceCalculate = false,
dirtyRanges = [],
dirtyNameMap = {},
@@ -127,6 +128,7 @@ export class CalculateController extends Disposable {
this._calculateFormulaService.execute({
dirtyIterationUnits,
+ dirtyReferenceUnits,
formulaData,
arrayFormulaCellData,
arrayFormulaRange,
diff --git a/packages/engine-formula/src/engine/ast-node/__tests__/function-node.spec.ts b/packages/engine-formula/src/engine/ast-node/__tests__/function-node.spec.ts
index 2556ded101..08c59dbc4a 100644
--- a/packages/engine-formula/src/engine/ast-node/__tests__/function-node.spec.ts
+++ b/packages/engine-formula/src/engine/ast-node/__tests__/function-node.spec.ts
@@ -15,9 +15,9 @@
*/
import type { IWorkbookData, Workbook } from '@univerjs/core';
-import type { LambdaValueObjectObject } from '../../value-object/lambda-value-object';
-import { DateSystem, LocaleType, UniverInstanceType } from '@univerjs/core';
+import { DateSystem, IUniverInstanceService, LocaleType, UniverInstanceType } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
+import type { LambdaValueObjectObject } from '../../value-object/lambda-value-object';
import { ErrorType } from '../../../basics/error-type';
import { createFunctionTestBed } from '../../../functions/__tests__/create-function-test-bed';
import { AsyncCustomFunction, CustomFunction } from '../../../functions/custom-function';
@@ -25,6 +25,7 @@ import { DateFunction } from '../../../functions/date/date';
import { FUNCTION_NAMES_DATE } from '../../../functions/date/function-names';
import { Accrint } from '../../../functions/financial/accrint';
import { FUNCTION_NAMES_FINANCIAL } from '../../../functions/financial/function-names';
+import { Sheet } from '../../../functions/information/sheet';
import { Abs } from '../../../functions/math/abs';
import { FUNCTION_NAMES_MATH } from '../../../functions/math/function-names';
import { FUNCTION_NAMES_META } from '../../../functions/meta/function-names';
@@ -72,6 +73,27 @@ function createDateSystemWorkbookData(id: string, dateSystem: DateSystem): IWork
}
describe('FunctionNode workbook context', () => {
+ it('refreshes worksheet metadata when reusing an AST after repeated moves', () => {
+ const data = createWorkbookData();
+ data.sheetOrder = ['sheet1', 'sheet2'];
+ data.sheets.sheet2 = { id: 'sheet2', name: 'Sheet2', rowCount: 1, columnCount: 1 };
+ const bed = createFunctionTestBed(data);
+ try {
+ const config = bed.get(IFormulaCurrentConfigService);
+ config.load({ formulaData: {}, arrayFormulaCellData: {}, arrayFormulaRange: {}, forceCalculate: false, dirtyRanges: [], dirtyNameMap: {}, dirtyDefinedNameMap: {}, dirtyUnitFeatureMap: {}, dirtyUnitOtherFormulaMap: {}, allUnitData: { [bed.unitId]: bed.sheetData } });
+ bed.get(IFunctionService).registerExecutors(new Sheet('SHEET'));
+ bed.get(IFormulaRuntimeService).setCurrent(0, 0, 1, 1, bed.sheetId, bed.unitId);
+ const lexerNode = bed.get(Lexer).treeBuilder('=SHEET("Sheet2")') as LexerNode;
+ const node = bed.get(AstTreeBuilder).parse(lexerNode) as BaseAstNode;
+ const book = bed.get(IUniverInstanceService).getUnit<Workbook>(bed.unitId, UniverInstanceType.UNIVER_SHEET)!;
+ for (const order of [['sheet1', 'sheet2'], ['sheet2', 'sheet1'], ['sheet1', 'sheet2']]) {
+ book.getConfig().sheetOrder = order;
+ node.resetCalculationState();
+ expect(getObjectValue(bed.get(Interpreter).execute(generateExecuteAstNodeData(node)))).toBe(order.indexOf('sheet2') + 1);
+ }
+ } finally { bed.univer.dispose(); }
+ });
+
it('does not use the executing workbook locale to parse formula text', () => {
const testBed = createFunctionTestBed(createWorkbookData());
const currentConfigService = testBed.get(IFormulaCurrentConfigService);
diff --git a/packages/engine-formula/src/engine/ast-node/function-node.ts b/packages/engine-formula/src/engine/ast-node/function-node.ts
index 744ab02b4a..0c5b3d5316 100644
--- a/packages/engine-formula/src/engine/ast-node/function-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/function-node.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import { DateSystem, Inject, Injector } from '@univerjs/core';
import type { BaseFunction } from '../../functions/base-function';
import type { LexerNode } from '../analysis/lexer-node';
import type {
@@ -25,7 +26,6 @@ import type {
} from '../reference-object/base-reference-object';
import type { BaseValueObject } from '../value-object/base-value-object';
import type { FormulaFunctionResultValueType } from '../value-object/primitive-object';
-import { DateSystem, Inject, Injector } from '@univerjs/core';
import { AstNodePromiseType } from '../../basics/common';
import { ErrorType } from '../../basics/error-type';
import { matchToken } from '../../basics/token';
@@ -68,10 +68,6 @@ export class FunctionNode extends BaseAstNode {
this._setLocale();
}
- if (this._functionExecutor.needsSheetsInfo) {
- this._setSheetsInfo();
- }
-
if (this._functionExecutor.needsFormulaDataModel) {
this._functionExecutor.setFormulaDataModel(this._formulaDataModel);
}
@@ -171,6 +167,11 @@ export class FunctionNode extends BaseAstNode {
return object.withDateSystem(dateSystem);
}
+ isAffectedBySheetMetadata(sheetOrderChanged: boolean, sheetSizeChanged: boolean): boolean {
+ return (sheetOrderChanged && this._functionExecutor.needsSheetsInfo) ||
+ (sheetSizeChanged && this._functionExecutor.needsSheetRowColumnCount);
+ }
+
isFunctionExecutorArgumentsIgnoreNumberPattern() {
return this._functionExecutor.isArgumentsIgnoreNumberPattern();
}
@@ -404,6 +405,10 @@ export class FunctionNode extends BaseAstNode {
this._functionExecutor.setRefInfo(currentUnitId, currentSubUnitId, currentRow, currentColumn, currentRowCount, currentColumnCount);
this._functionExecutor.setDateSystem(this._currentConfigService.getDateSystem(currentUnitId));
+ if (this._functionExecutor.needsSheetsInfo) {
+ this._setSheetsInfo();
+ }
+
if (this._functionExecutor.needsSheetRowColumnCount) {
const { rowCount, columnCount } = this._currentConfigService.getSheetRowColumnCount(currentUnitId, currentSubUnitId);
@@ -439,7 +444,7 @@ export class FunctionNode extends BaseAstNode {
}
private _setSheetsInfo() {
- this._functionExecutor.setSheetsInfo(this._currentConfigService.getSheetsInfo());
+ this._functionExecutor.setSheetsInfo(this._currentConfigService.getSheetsInfo(this._runtimeService.currentUnitId));
}
private _setFilteredOutRows(referenceObject: BaseReferenceObject) {
diff --git a/packages/engine-formula/src/engine/ast-node/union-node.ts b/packages/engine-formula/src/engine/ast-node/union-node.ts
index d7f5329836..055edabf93 100644
--- a/packages/engine-formula/src/engine/ast-node/union-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/union-node.ts
@@ -81,7 +81,7 @@ export class UnionNode extends BaseAstNode {
return;
}
- const { sheetOrder, sheetNameMap } = this._currentConfigService.getSheetsInfo();
+ const { sheetOrder, sheetNameMap } = this._currentConfigService.getSheetsInfo(source.getUnitId());
const sheetIdsByName = new Map(
Object.entries(sheetNameMap).map(([sheetId, sheetName]) => [sheetName.toLocaleLowerCase(), sheetId])
);
diff --git a/packages/engine-formula/src/engine/dependency/__tests__/reference-context.spec.ts b/packages/engine-formula/src/engine/dependency/__tests__/reference-context.spec.ts
new file mode 100644
index 0000000000..9c9d8f9b92
--- /dev/null
+++ b/packages/engine-formula/src/engine/dependency/__tests__/reference-context.spec.ts
@@ -0,0 +1,130 @@
+/**
+ * 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 { Workbook } from '@univerjs/core';
+import { IUniverInstanceService, LocaleType, ObjectMatrix, UniverInstanceType } from '@univerjs/core';
+import { expect, it } from 'vitest';
+import type { LexerNode } from '../../analysis/lexer-node';
+import { CustomFunction } from '../../../functions/custom-function';
+import { Sheet } from '../../../functions/information/sheet';
+import { Rows } from '../../../functions/lookup/rows';
+import { Sum } from '../../../functions/math/sum';
+import { ICalculateFormulaService } from '../../../services/calculate-formula.service';
+import { IFormulaCurrentConfigService } from '../../../services/current-data.service';
+import { IFeatureCalculationManagerService } from '../../../services/feature-calculation-manager.service';
+import { IFunctionService } from '../../../services/function.service';
+import { IFormulaRuntimeService } from '../../../services/runtime.service';
+import { createCommandTestBed } from '../../analysis/__tests__/create-command-test-bed';
+import { Lexer } from '../../analysis/lexer';
+import { AstTreeBuilder } from '../../analysis/parser';
+import { BaseAstNode } from '../../ast-node/base-ast-node';
+import { NodeType } from '../../ast-node/node-type';
+import { ReferenceContext } from '../reference-context';
+
+class CustomAstFunction extends BaseAstNode {
+ override get nodeType(): NodeType {
+ return NodeType.FUNCTION;
+ }
+}
+
+it('selects order and size sensitive references while retaining ordinary formula caches', () => {
+ const sheets = Object.fromEntries(['Main', 'Start', 'End', 'Middle'].map((name) => [name, {
+ id: name,
+ name,
+ rowCount: 4,
+ columnCount: 4,
+ }]));
+ const bed = createCommandTestBed({ id: 'test', name: 'test', appVersion: '1.3.1', locale: LocaleType.EN_US, styles: {}, sheetOrder: ['Main', 'Start', 'End', 'Middle'], sheets });
+ try {
+ bed.get(IFunctionService).registerExecutors(new Sum('SUM'), new Sheet('SHEET'), new Rows('ROWS'));
+ const custom = new CustomFunction('CUSTOMSHEETS');
+ custom.needsSheetsInfo = true;
+ const customSize = new CustomFunction('CUSTOMSIZE');
+ customSize.needsSheetRowColumnCount = true;
+ bed.get(IFunctionService).registerExecutors(custom, customSize);
+ const config = bed.get(IFormulaCurrentConfigService);
+ config.load({ formulaData: {}, arrayFormulaCellData: {}, arrayFormulaRange: {}, forceCalculate: false, dirtyRanges: [], dirtyNameMap: {}, dirtyDefinedNameMap: {}, dirtyUnitFeatureMap: {}, dirtyUnitOtherFormulaMap: {}, allUnitData: { test: bed.sheetData } });
+ bed.get(IFormulaRuntimeService).setCurrent(0, 0, 4, 4, 'Main', 'test');
+ const context = new ReferenceContext();
+ let order = ['Main', 'Start', 'End', 'Middle'];
+ const info = (unitId: string) => ({ ...config.getSheetsInfo(unitId), sheetOrder: order });
+ const affected = (formula: string) => {
+ const node = bed.get(AstTreeBuilder).parse(bed.get(Lexer).treeBuilder(formula) as LexerNode) as BaseAstNode;
+ return context.isAffected(node, 'test', 'Main');
+ };
+ expect(context.update({ test: bed.sheetData }, info)).toBe(false);
+ context.finish(true);
+ order = ['Main', 'Start', 'Middle', 'End'];
+ expect(context.update({ test: bed.sheetData }, info)).toBe(true);
+ expect(affected('=SUM(Start:End!A1)')).toBe(true);
+ expect(affected('=SHEET("Start")')).toBe(true);
+ expect(affected('=CUSTOMSHEETS()')).toBe(true);
+ expect(context.isAffected(new CustomAstFunction('CUSTOM_AST'), 'test', 'Main')).toBe(true);
+ expect(affected('=CUSTOMSIZE()')).toBe(false);
+ expect(affected('=SUM(Start!A1:A3)')).toBe(false);
+ expect(affected('=SUM("Start:End!A1")')).toBe(false);
+ expect(affected('=A1')).toBe(false);
+ context.finish(false);
+ expect(context.update({ test: bed.sheetData }, info)).toBe(true);
+ expect(affected('=SUM(Start:End!A1)')).toBe(true);
+ context.finish(true);
+ bed.sheetData.Start.rowCount = 6;
+ bed.sheetData.Start.columnCount = 6;
+ expect(context.update({ test: bed.sheetData }, info)).toBe(true);
+ expect(affected('=SUM(Start!A:A)')).toBe(true);
+ expect(affected('=ROWS(Start!A:A)')).toBe(true);
+ expect(affected('=SUM(Start!1:1)')).toBe(true);
+ expect(affected('=SUM(Start!A1:A6)')).toBe(true);
+ expect(affected('=SUM(Start!A1:A3)')).toBe(false);
+ expect(affected('=SUM(Start:End!A1)')).toBe(false);
+ expect(context.update({ test: bed.sheetData }, info)).toBe(false);
+ expect(affected('=SUM(Start!A:A)')).toBe(false);
+ bed.sheetData.Main.rowCount = 6;
+ expect(context.update({ test: bed.sheetData }, info)).toBe(true);
+ expect(affected('=CUSTOMSIZE()')).toBe(true);
+ } finally { bed.univer.dispose(); }
+});
+
+it('executes opaque features without parsing an empty formula or recalculating unrelated cells', async () => {
+ const bed = createCommandTestBed({ id: 'test', name: 'test', appVersion: '1.3.1', locale: LocaleType.EN_US, styles: {}, sheetOrder: ['s'], sheets: { s: { id: 's', name: 'Sheet', rowCount: 10, columnCount: 10 } } });
+ const service = bed.get(ICalculateFormulaService);
+ let featureValue = 41;
+ const observed: unknown[][] = [];
+ const subscription = service.executionCompleteListener$.subscribe((data) => {
+ observed.push([data.unitData.test?.s?.getValue(0, 0)?.v, data.unitData.test?.s?.getValue(0, 2)?.v]);
+ });
+ try {
+ bed.get(IFeatureCalculationManagerService).register('test', 's', 'feature', {
+ unitId: 'test',
+ subUnitId: 's',
+ dependencyRanges: [],
+ getDirtyData: (dirty) => ({
+ runtimeCellData: { test: { s: new ObjectMatrix({ 0: { 1: { v: featureValue } } }) } },
+ dirtyRanges: dirty.forceCalculation ? { test: { s: [{ startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 }] } } : {},
+ }),
+ });
+ const config = { formulaData: { test: { s: { 0: { 0: { f: '=B1' }, 2: { f: '=5' } } } } }, arrayFormulaCellData: {}, arrayFormulaRange: {}, forceCalculate: true, dirtyRanges: [], dirtyNameMap: {}, dirtyDefinedNameMap: {}, dirtyUnitFeatureMap: {}, dirtyUnitOtherFormulaMap: {} };
+ await service.execute(config);
+ featureValue = 42;
+ bed.get(IUniverInstanceService).getUnit<Workbook>(bed.unitId, UniverInstanceType.UNIVER_SHEET)!.getSheetBySheetId(bed.sheetId)!.setRowCount(11);
+ await service.execute({ ...config, forceCalculate: false, dirtyReferenceUnits: ['test'] });
+ expect(observed).toEqual([[41, 5], [42, undefined]]);
+ expect(bed.get(IFormulaCurrentConfigService).isForceCalculate()).toBe(false);
+ } finally {
+ subscription.unsubscribe();
+ bed.univer.dispose();
+ }
+});
diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
index 4ebb83157f..b98e44c883 100644
--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
@@ -77,6 +77,7 @@ import {
FormulaDependencyTreeType,
FormulaDependencyTreeVirtual,
} from './dependency-tree';
+import { ReferenceContext } from './reference-context';
export function generateRandomDependencyTreeId(dependencyManagerService: IDependencyManagerService): number {
const idNum = dependencyManagerService.getLastTreeId() || 0;
@@ -84,6 +85,8 @@ export function generateRandomDependencyTreeId(dependencyManagerService: IDepend
}
export interface IFormulaDependencyGenerator {
+ /** Keep structural dirty information available when a calculation is interrupted. */
+ finishReferenceContext?(completed: boolean): void;
generate(isCalculateTreeModel?: boolean): Promise<IFormulaDependencyTree[]>;
getAllDependencyJson(): Promise<IFormulaDependencyTreeJson[]>;
getCellDependencyJson(unitId: string, sheetId: string, row: number, column: number): Promise<IFormulaDependencyTreeFullJson | undefined>;
@@ -112,6 +115,7 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
// Sheet sizes take part in resolving open-ended references (`A:A`, `A1:`), and the AST
// cache does not invalidate on a resize, so the resolved ranges are only reusable while
// every sheet keeps the size it had when they were resolved.
+ private readonly _referenceContext = new ReferenceContext();
private _reusableSheetSignature: Nullable<string> = null;
constructor(
@@ -261,7 +265,7 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
FDtree.rangeList = dependencyRanges;
FDtree.getDirtyData = getDirtyData;
- const allDependency = getDirtyData(this._currentConfigService.getDirtyData() as IFormulaDirtyData, this._runtimeService.getAllRuntimeData() as IAllRuntimeData);
+ const allDependency = getDirtyData(this._currentConfigService.getDirtyData(true) as IFormulaDirtyData, this._runtimeService.getAllRuntimeData() as IAllRuntimeData);
const dirtyRanges = this._convertDirtyRangesToUnitRange(allDependency.dirtyRanges);
FDtree.featureDirtyRanges = dirtyRanges;
@@ -528,7 +532,7 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
return this._dependencyTreeCache.get(treeId);
}
- protected _getTreeNode(tree: IFormulaDependencyTree) {
+ protected _getTreeNode(tree: Pick<IFormulaDependencyTree, 'unitId' | 'subUnitId' | 'formula' | 'row' | 'column'>) {
return generateAstNode(
tree.unitId,
tree.formula,
@@ -764,6 +768,29 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
this._reusableRanges.set(node, [...rangeList]);
}
+ finishReferenceContext(completed: boolean): void {
+ this._referenceContext.finish(completed);
+ if (!completed) {
+ this._reusableSheetSignature = null;
+ }
+ }
+
+ protected _updateReferenceContext(unitData: IUnitData): boolean {
+ return this._referenceContext.update(unitData, (unitId) => this._currentConfigService.getSheetsInfo?.(unitId));
+ }
+
+ protected _isReferenceContextAffected(tree: Pick<IFormulaDependencyTree, 'unitId' | 'subUnitId' | 'formula' | 'row' | 'column' | 'rowCount' | 'columnCount' | 'refOffsetX' | 'refOffsetY'>, node?: BaseAstNode): boolean {
+ if (this._referenceContext.isSheetSizeChanged(tree.unitId, tree.subUnitId)) {
+ const arrayRange = this._currentConfigService.getArrayFormulaRange()?.[tree.unitId]?.[tree.subUnitId]?.[tree.row]?.[tree.column];
+ const cell = this._currentConfigService.getUnitData()[tree.unitId]?.[tree.subUnitId]?.cellData.getValue(tree.row, tree.column);
+ if (arrayRange || cell?.v === '#SPILL!' || cell?.v === '#REF!') {
+ return true;
+ }
+ }
+ this._runtimeService.setCurrent(tree.row, tree.column, tree.rowCount, tree.columnCount, tree.subUnitId, tree.unitId);
+ return this._referenceContext.isAffected(node ?? this._getTreeNode(tree), tree.unitId, tree.subUnitId, tree.refOffsetX, tree.refOffsetY);
+ }
+
/**
* Generate nodes for the dependency tree, where each node contains all the reference data ranges included in each formula.
* @param formulaData
@@ -773,6 +800,7 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
otherFormulaData: IOtherFormulaData,
unitData: IUnitData
) {
+ const referenceContextChanged = this._updateReferenceContext(unitData);
const formulaDataKeys = Object.keys(formulaData);
const otherFormulaDataKeys = Object.keys(otherFormulaData);
@@ -806,6 +834,7 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
// After entering the pivot table, no calculation is required if there is no formula
if (!tree.formula) {
+ tree.isDirty = referenceContextChanged && tree.type === FormulaDependencyTreeType.FEATURE_FORMULA;
continue;
}
@@ -819,7 +848,7 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
);
const node = this._getTreeNode(tree);
- tree.isDirty = this._includeTree(tree, node);
+ tree.isDirty = this._includeTree(tree, node) || (referenceContextChanged && this._isReferenceContextAffected(tree, node));
const addressFunctionNodes = this._getAddressFunctionNodeList(node);
if (addressFunctionNodes.length > 0) {
diff --git a/packages/engine-formula/src/engine/dependency/reference-context.ts b/packages/engine-formula/src/engine/dependency/reference-context.ts
new file mode 100644
index 0000000000..cd0ba82381
--- /dev/null
+++ b/packages/engine-formula/src/engine/dependency/reference-context.ts
@@ -0,0 +1,145 @@
+/**
+ * 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 { IUnitData } from '../../basics/common';
+import type { BaseAstNode } from '../ast-node/base-ast-node';
+import type { FunctionNode } from '../ast-node/function-node';
+import type { ReferenceNode } from '../ast-node/reference-node';
+import { NodeType } from '../ast-node/node-type';
+import { BaseReferenceObject } from '../reference-object/base-reference-object';
+
+interface ISheetSize {
+ rowCount: number;
+ columnCount: number;
+}
+
+interface IWorkbookReferenceContext {
+ order: string[];
+ sizes: Record<string, ISheetSize>;
+ names: string[];
+}
+
+/** Retains sheet metadata only; formulas and dependency ranges stay in the existing caches. */
+export class ReferenceContext {
+ private _stable: Record<string, IWorkbookReferenceContext> = {};
+ private _previous: Record<string, IWorkbookReferenceContext> = {};
+ private _current: Record<string, IWorkbookReferenceContext> = {};
+ private _orderChanged = false;
+ private _changed = false;
+
+ update(unitData: IUnitData, getSheetsInfo: (unitId: string) => { sheetOrder: string[]; sheetNameMap: Record<string, string> } | undefined): boolean {
+ this._previous = this._current;
+ this._current = {};
+ this._orderChanged = false;
+ this._changed = false;
+ for (const [unitId, sheets] of Object.entries(unitData)) {
+ const sizes = Object.fromEntries(Object.entries(sheets ?? {}).map(([sheetId, sheet]) => [
+ sheetId,
+ { rowCount: sheet.rowCount, columnCount: sheet.columnCount },
+ ]));
+ const info = getSheetsInfo(unitId);
+ const order = [...(info?.sheetOrder ?? Object.keys(sizes))];
+ const names = Object.values(info?.sheetNameMap ?? {}).map((name) => name.toLocaleLowerCase());
+ this._current[unitId] = { order, sizes, names };
+ }
+ if (Object.keys(this._previous).length === 0) {
+ this._stable = this._current;
+ return false;
+ }
+ for (const unitId of new Set([...Object.keys(this._previous), ...Object.keys(this._current)])) {
+ const before = this._previous[unitId];
+ const after = this._current[unitId];
+ if (JSON.stringify(before?.order) !== JSON.stringify(after?.order)) {
+ this._orderChanged = true;
+ this._changed = true;
+ }
+ if (JSON.stringify(before?.sizes) !== JSON.stringify(after?.sizes)) {
+ this._changed = true;
+ }
+ }
+ return this._changed;
+ }
+
+ finish(completed: boolean): void {
+ if (completed) {
+ this._stable = this._current;
+ } else {
+ this._current = this._stable;
+ }
+ }
+
+ isSheetSizeChanged(unitId: string, sheetId: string): boolean {
+ const before = this._previous[unitId]?.sizes[sheetId];
+ const after = this._current[unitId]?.sizes[sheetId];
+ return this._changed && Boolean(before && after &&
+ (before.rowCount !== after.rowCount || before.columnCount !== after.columnCount));
+ }
+
+ isAffected(node: BaseAstNode, unitId: string, sheetId: string, offsetX = 0, offsetY = 0): boolean {
+ if (!this._changed) {
+ return false;
+ }
+ const token = node.getToken().toUpperCase();
+ if (node.nodeType === NodeType.FUNCTION) {
+ // Dynamic addresses can hide an open-ended or three-dimensional reference.
+ if (token === 'INDIRECT' || token === 'OFFSET') {
+ return true;
+ }
+ if ((node as FunctionNode).isAffectedBySheetMetadata?.(this._orderChanged, this.isSheetSizeChanged(unitId, sheetId)) ?? true) {
+ return true;
+ }
+ }
+ if (node.nodeType === NodeType.UNION && this._orderChanged) {
+ // A 3D reference can retain the same members while their evaluation order changes.
+ const first = node.getChildren()[0]?.getToken().trim().replace(/^'|'$/g, '').replace(/''/g, "'").toLocaleLowerCase();
+ if (first && Object.values(this._current).some((book) => book.names.includes(first))) {
+ return true;
+ }
+ }
+ if (node.nodeType === NodeType.REFERENCE || node.nodeType === NodeType.UNION) {
+ const value = this._resolveStaticReference(node, offsetX, offsetY);
+ if (value === null) {
+ // An invalid reference can become valid after a resize or sheet insertion.
+ return true;
+ }
+ if (value && value.toUnitRanges().some(({ unitId, sheetId, range }) => {
+ const before = this._previous[unitId]?.sizes[sheetId];
+ const after = this._current[unitId]?.sizes[sheetId];
+ if (!before || !after) {
+ return true;
+ }
+ return (before.rowCount !== after.rowCount && (value.isColumn() || range.endRow >= Math.min(before.rowCount, after.rowCount) - 1)) ||
+ (before.columnCount !== after.columnCount && (value.isRow() || range.endColumn >= Math.min(before.columnCount, after.columnCount) - 1));
+ })) {
+ return true;
+ }
+ }
+ return node.getChildren().some((child) => this.isAffected(child, unitId, sheetId, offsetX, offsetY));
+ }
+
+ private _resolveStaticReference(node: BaseAstNode, offsetX: number, offsetY: number): BaseReferenceObject | null | undefined {
+ if (node.nodeType === NodeType.REFERENCE) {
+ (node as ReferenceNode).setRefOffset(offsetX, offsetY);
+ } else if (node.nodeType !== NodeType.UNION || node.getChildren().some((child) =>
+ this._resolveStaticReference(child, offsetX, offsetY) === undefined
+ )) {
+ return;
+ }
+ node.execute();
+ const value = node.getValue();
+ return value instanceof BaseReferenceObject ? value : null;
+ }
+}
diff --git a/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts b/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts
index 7bdc05a173..28cc46c52e 100644
--- a/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts
@@ -108,6 +108,18 @@ function createService(withCurrentWorkbook = true) {
}
describe('FormulaCurrentConfigService', () => {
+ it('keeps conservative feature invalidation separate from ordinary formula calculation', () => {
+ const bed = createFunctionTestBed();
+ try {
+ const service = bed.get(IFormulaCurrentConfigService);
+ service.load({ formulaData: {}, arrayFormulaCellData: {}, arrayFormulaRange: {}, forceCalculate: false, dirtyReferenceUnits: ['unit'], dirtyRanges: [], dirtyNameMap: {}, dirtyDefinedNameMap: {}, dirtyUnitFeatureMap: {}, dirtyUnitOtherFormulaMap: {}, allUnitData: {} });
+ expect(service.getDirtyData().forceCalculation).toBe(false);
+ expect(service.getDirtyData(true).forceCalculation).toBe(true);
+ service.loadDirtyRangesAndExcludedCell([]);
+ expect(service.getDirtyData(true).forceCalculation).toBe(false);
+ } finally { bed.univer.dispose(); }
+ });
+
it('distinguishes transported filter exclusions from manual hiding and clears stale exclusions', () => {
const testBed = createFunctionTestBed();
try {
@@ -240,6 +252,14 @@ describe('FormulaCurrentConfigService', () => {
expect(service.getDateSystem('missing')).toBe(DateSystem.Date1900);
});
+ it('resolves explicit workbook order independently of the focused workbook', () => {
+ const { service, workbookById } = createService();
+ workbookById.set('other', { getSnapshot: () => ({ id: 'other', sheetOrder: ['end', 'start'] }) });
+ expect(service.getSheetsInfo('other').sheetOrder).toEqual(['end', 'start']);
+ expect(service.getSheetsInfo().sheetOrder).toEqual(['sheet-current']);
+ expect(service.getSheetsInfo('missing')).toEqual({ sheetOrder: [], sheetNameMap: {} });
+ });
+
it('should resolve sheet size, filtered rows and lightweight data loading', () => {
const { service, workbookById, formulaDataModel } = createService();
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.ts
index 23cb6f5eb3..9c7cfd669a 100644
--- 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.ts
@@ -15,9 +15,9 @@
*/
import type { ICommandInfo, IExecutionOptions } from '@univerjs/core';
-import type { IDirtyConversionManagerParams } from '../active-dirty-manager.service';
import { CommandType, ICommandService, Univer } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { IDirtyConversionManagerParams } from '../active-dirty-manager.service';
import {
SetFormulaCalculationNotificationMutation,
SetFormulaCalculationStartMutation,
@@ -69,6 +69,26 @@ describe('FormulaCalculationTriggerService', () => {
vi.restoreAllMocks();
});
+ it('batches reference context changes and preserves explicit full calculation on restart', async () => {
+ const bed = createTestBed();
+ bed.conversions.set('structure', {
+ commandId: 'structure',
+ getDirtyData: (command) => command.params as ReturnType<IDirtyConversionManagerParams['getDirtyData']>,
+ });
+ try {
+ bed.emit({ id: 'structure', params: { dirtyReferenceUnits: ['first'] } });
+ bed.emit({ id: 'structure', params: { dirtyReferenceUnits: ['first', 'second'] } });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(bed.executed[0].params).toMatchObject({ dirtyReferenceUnits: ['first', 'second'], forceCalculation: false, dirtyRanges: [] });
+ bed.emit({ id: SetTriggerFormulaCalculationStartMutation.id, params: { forceCalculation: true } });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(bed.executed[1].id).toBe(SetFormulaCalculationStopMutation.id);
+ bed.emit({ id: SetFormulaCalculationNotificationMutation.id, params: { functionsExecutedState: FormulaExecutedStateType.STOP_EXECUTION } });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(bed.executed[2].params).toMatchObject({ dirtyReferenceUnits: ['first', 'second'], forceCalculation: true });
+ } finally { bed.service.dispose(); }
+ });
+
it('batches iteration settings changes and preserves them when restarting an active calculation', async () => {
const bed = createTestBed();
bed.conversions.set('iteration-settings', {
diff --git a/packages/engine-formula/src/services/active-dirty-manager.service.ts b/packages/engine-formula/src/services/active-dirty-manager.service.ts
index a9aaee0fda..0c6b57263d 100644
--- a/packages/engine-formula/src/services/active-dirty-manager.service.ts
+++ b/packages/engine-formula/src/services/active-dirty-manager.service.ts
@@ -15,6 +15,7 @@
*/
import type { ICommandInfo, IExecutionOptions, IUnitRange, Nullable } from '@univerjs/core';
+import { createIdentifier, Disposable } from '@univerjs/core';
import type {
IDirtyUnitDefinedNameMap,
IDirtyUnitFeatureMap,
@@ -22,13 +23,13 @@ import type {
IDirtyUnitSheetNameMap,
IDirtyUnitSuperTableMap,
} from '../basics/common';
-import { createIdentifier, Disposable } from '@univerjs/core';
export interface IDirtyConversionManagerParams {
commandId: string;
shouldTrigger?: (command: ICommandInfo, options?: IExecutionOptions) => boolean;
getDirtyData: (command: ICommandInfo) => {
dirtyIterationUnits?: string[];
+ dirtyReferenceUnits?: string[];
forceCalculation?: boolean;
dirtyRanges?: IUnitRange[];
dirtyNameMap?: IDirtyUnitSheetNameMap;
diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.ts
index 1258080f47..42607fa99f 100644
--- a/packages/engine-formula/src/services/calculate-formula.service.ts
+++ b/packages/engine-formula/src/services/calculate-formula.service.ts
@@ -275,7 +275,13 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
this._preserveCircularUnits = new Set(formulaDatasetConfig.preserveCircularUnits);
this._runtimeService.beginCircularReferences();
this._isCalculateTreeModel = formulaDatasetConfig.isCalculateTreeModel || false;
- await this._executeStep();
+ let completed = false;
+ try {
+ await this._executeStep();
+ completed = !this._runtimeService.isStopExecution();
+ } finally {
+ this._formulaDependencyGenerator.finishReferenceContext?.(completed);
+ }
this._runtimeService.completeCircularReferences();
this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CALCULATION_COMPLETED);
this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
@@ -473,35 +479,35 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
continue;
}
- const node = generateAstNode(
- tree.unitId,
- tree.formula,
- this._lexer,
- this._astTreeBuilder,
- this._currentConfigService,
- tree.subUnitId,
- tree.column,
- tree.row
- );
- const nodeData = {
- node,
- refOffsetX: tree.refOffsetX,
- refOffsetY: tree.refOffsetY,
- };
- let value: FunctionVariantType;
-
if (getDirtyData != null && tree.featureId != null) {
/**
* Execute the dependencies registered by the feature,
* and return the dirty area marked by the feature,
* so as to allow the formulas depending on the dirty area to continue the calculation.
*/
- const { runtimeCellData, dirtyRanges } = getDirtyData(this._currentConfigService.getDirtyData(), this._runtimeService.getAllRuntimeData());
+ const { runtimeCellData, dirtyRanges } = getDirtyData(this._currentConfigService.getDirtyData(true), this._runtimeService.getAllRuntimeData());
this._runtimeService.setRuntimeFeatureCellData(tree.featureId, runtimeCellData);
this._runtimeService.setRuntimeFeatureRange(tree.featureId, dirtyRanges);
- } else if (nodeData != null) {
+ } else {
+ const node = generateAstNode(
+ tree.unitId,
+ tree.formula,
+ this._lexer,
+ this._astTreeBuilder,
+ this._currentConfigService,
+ tree.subUnitId,
+ tree.column,
+ tree.row
+ );
+ const nodeData = {
+ node,
+ refOffsetX: tree.refOffsetX,
+ refOffsetY: tree.refOffsetY,
+ };
+ let value: FunctionVariantType;
+
if (interpreter.checkAsyncNode(nodeData.node)) {
value = await interpreter.executeAsync(nodeData);
} else {
@@ -513,10 +519,9 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
} else {
this._runtimeService.setRuntimeData(value);
}
+ node.resetCalculationState();
}
- node.resetCalculationState();
-
i++;
}
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index 4794567423..5cdacfa5d1 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -15,6 +15,16 @@
*/
import type { BaseDataModel, ITableSnapshot, IUnitRange, IWorkbookCalculationSettings, LocaleType, Nullable, Workbook } from '@univerjs/core';
+import {
+ createIdentifier,
+ DateSystem,
+ Disposable,
+ Inject,
+ IUniverInstanceService,
+ LocaleService,
+ ObjectMatrix,
+ UniverInstanceType,
+} from '@univerjs/core';
import type {
IArrayFormulaRangeType,
IDirtyUnitDefinedNameMap,
@@ -34,21 +44,12 @@ import type {
IUnitSheetNameMap,
IUnitStylesData,
} from '../basics/common';
-import {
- createIdentifier,
- DateSystem,
- Disposable,
- Inject,
- IUniverInstanceService,
- LocaleService,
- ObjectMatrix,
- UniverInstanceType,
-} from '@univerjs/core';
import { convertUnitDataToRuntime, copyUnitData } from '../basics/runtime';
import { FormulaDataModel } from '../models/formula-data.model';
import { ISheetRowFilteredService } from './sheet-row-filtered.service';
export interface IFormulaDirtyData {
+ dirtyReferenceUnits?: string[];
dirtyIterationUnits?: string[];
forceCalculation: boolean;
dirtyRanges: IUnitRange[];
@@ -122,14 +123,14 @@ export interface IFormulaCurrentConfigService {
setExecuteUnitId(unitId: string): void;
setExecuteSubUnitId(subUnitId: string): void;
- getDirtyData(): IFormulaDirtyData;
+ getDirtyData(forFeatureCalculation?: boolean): IFormulaDirtyData;
getClearDependencyTreeCache(): IDirtyUnitSheetNameMap;
getLocale(): LocaleType;
getDateSystem(unitId?: string): DateSystem;
- getSheetsInfo(): {
+ getSheetsInfo(unitId?: string): {
sheetOrder: string[];
sheetNameMap: { [sheetId: string]: string };
};
@@ -144,6 +145,7 @@ export interface IFormulaCurrentConfigService {
}
export class FormulaCurrentConfigService extends Disposable implements IFormulaCurrentConfigService {
+ private _dirtyReferenceUnits: string[] = [];
private _dirtyIterationUnits: string[] = [];
private _unitData: IUnitData = Object.create(null);
@@ -328,8 +330,10 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
return this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)?.getDateSystem() ?? DateSystem.Date1900;
}
- getSheetsInfo() {
- const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ getSheetsInfo(unitId?: string) {
+ const workbook = unitId
+ ? this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)
+ : this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
if (!workbook) {
return {
sheetOrder: [],
@@ -402,6 +406,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
this._formulaData = config.formulaData;
this._dirtyIterationUnits = config.dirtyIterationUnits ?? [];
+ this._dirtyReferenceUnits = config.dirtyReferenceUnits ?? [];
this._arrayFormulaCellData = convertUnitDataToRuntime(config.arrayFormulaCellData);
@@ -449,10 +454,12 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
rowData && this._applyUnitRowData(rowData);
}
- getDirtyData(): IFormulaDirtyData {
+ // Feature callbacks expose no formula metadata; keep their conservative invalidation local.
+ getDirtyData(forFeatureCalculation = false): IFormulaDirtyData {
return {
dirtyIterationUnits: this._dirtyIterationUnits,
- forceCalculation: this._forceCalculate,
+ dirtyReferenceUnits: this._dirtyReferenceUnits,
+ forceCalculation: this._forceCalculate || (forFeatureCalculation && this._dirtyReferenceUnits.length > 0),
dirtyRanges: this._dirtyRanges,
dirtyNameMap: this._dirtyNameMap,
dirtyDefinedNameMap: this._dirtyDefinedNameMap,
@@ -466,6 +473,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
loadDirtyRangesAndExcludedCell(dirtyRanges: IUnitRange[], excludedCell?: IUnitExcludedCell) {
this._dirtyIterationUnits = [];
+ this._dirtyReferenceUnits = [];
this._dirtyRanges = dirtyRanges;
this._excludedCell = excludedCell;
diff --git a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts b/packages/engine-formula/src/services/formula-calculation-trigger.service.ts
index a4a49c965f..4d80206cf3 100644
--- a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts
+++ b/packages/engine-formula/src/services/formula-calculation-trigger.service.ts
@@ -15,12 +15,12 @@
*/
import type { ICommandInfo, IUnitRange, Nullable } from '@univerjs/core';
+import { Disposable, ICommandService, Rectangle } 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, Rectangle } from '@univerjs/core';
import {
SetFormulaCalculationNotificationMutation,
SetFormulaCalculationStartMutation,
@@ -238,6 +238,9 @@ function appendDirtyData(target: IFormulaDirtyData, source: Partial<IFormulaDirt
if (source.dirtyIterationUnits?.length) {
target.dirtyIterationUnits = Array.from(new Set([...(target.dirtyIterationUnits ?? []), ...source.dirtyIterationUnits]));
}
+ if (source.dirtyReferenceUnits?.length) {
+ target.dirtyReferenceUnits = Array.from(new Set([...(target.dirtyReferenceUnits ?? []), ...source.dirtyReferenceUnits]));
+ }
mergeDirtyRanges(target.dirtyRanges, source.dirtyRanges ?? [], rangeKeys);
mergeDirtyUnitStringMap(target.dirtyNameMap, source.dirtyNameMap);
mergeDirtyUnitStringMap(target.dirtyDefinedNameMap, source.dirtyDefinedNameMap);
@@ -280,6 +283,7 @@ function mergeDirtyUnitNestedMap(target: IDirtyUnitFeatureMap, right?: IDirtyUni
function hasDirtyData(dirtyData: IFormulaDirtyData): boolean {
return dirtyData.forceCalculation ||
Boolean(dirtyData.dirtyIterationUnits?.length) ||
+ Boolean(dirtyData.dirtyReferenceUnits?.length) ||
dirtyData.dirtyRanges.length > 0 ||
hasNestedValue(dirtyData.dirtyNameMap) ||
hasNestedValue(dirtyData.dirtyDefinedNameMap) ||
@@ -300,7 +304,7 @@ function hasNestedValue(value: unknown): boolean {
}
function dirtyDataIntersects(left: IFormulaDirtyData, right: IFormulaDirtyData): boolean {
- if (left.forceCalculation || right.forceCalculation || left.dirtyIterationUnits?.length || right.dirtyIterationUnits?.length) {
+ if (left.forceCalculation || right.forceCalculation || left.dirtyReferenceUnits?.length || right.dirtyReferenceUnits?.length || left.dirtyIterationUnits?.length || right.dirtyIterationUnits?.length) {
return true;
}
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.ts
index a11ee6cc7f..bdd10f962d 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
@@ -36,7 +36,9 @@ import {
SetRowHiddenMutation,
SetStyleCommand,
SetWorkbookCalculationSettingsMutation,
+ SetWorksheetColumnCountMutation,
SetWorksheetOrderMutation,
+ SetWorksheetRowCountMutation,
} from '@univerjs/sheets';
import { afterEach, describe, expect, it } from 'vitest';
import type { ITestBed } from '../../facade/__tests__/create-test-bed';
@@ -94,15 +96,16 @@ describe('ActiveDirtyController', () => {
testBed?.univer.dispose();
});
- it('rebuilds dependencies across the workbook when sheet order changes', () => {
+ it('reports reference context changes without forcing every formula', () => {
testBed = createControllerTestBed();
testBed.injector.get(ActiveDirtyController);
const dirty = getDirtyData(testBed, {
id: SetWorksheetOrderMutation.id,
- params: { unitId: 'test', subUnitId: 'sheet1', fromOrder: 0, toOrder: 0 },
+ params: { unitId: 'test', subUnitId: 'sheet1', fromOrder: 0, toOrder: 1 },
});
- expect(dirty.forceCalculation).toBe(true);
- expect(dirty.clearDependencyTreeCache).toEqual({ test: { sheet1: 'Sheet1' } });
+ expect(dirty.forceCalculation).toBeUndefined();
+ expect(dirty.dirtyReferenceUnits).toEqual(['test']);
+ expect(dirty.clearDependencyTreeCache).toBeUndefined();
});
it('marks iteration-sensitive workbooks without making every sheet dirty', () => {
@@ -116,6 +119,12 @@ describe('ActiveDirtyController', () => {
expect(dirty.dirtyRanges ?? []).toEqual([]);
});
+ it.each([SetWorksheetRowCountMutation.id, SetWorksheetColumnCountMutation.id])('triggers calculation for direct dimension changes: %s', (id) => {
+ testBed = createControllerTestBed();
+ testBed.injector.get(ActiveDirtyController);
+ expect(getDirtyData(testBed, { id, params: { unitId: 'test', subUnitId: 'sheet1', rowCount: 12, columnCount: 16 } })).toEqual({ dirtyReferenceUnits: ['test'] });
+ });
+
it.each(['__proto__', 'constructor', 'prototype', 'toString'])('keeps dirty sheet names local for special unit identifiers (%s)', (key) => {
testBed = createControllerTestBed();
testBed.injector.get(ActiveDirtyController);
diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
index f609b6a608..f32c63918f 100644
--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts
+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
@@ -30,6 +30,7 @@ import type {
ISetRangeValuesMutationParams,
ISetRowHiddenMutationParams,
ISetRowVisibleMutationParams,
+ ISetWorksheetOrderMutationParams,
} from '@univerjs/sheets';
import {
Disposable,
@@ -57,7 +58,9 @@ import {
SetRowVisibleMutation,
SetStyleCommand,
SetWorkbookCalculationSettingsMutation,
+ SetWorksheetColumnCountMutation,
SetWorksheetOrderMutation,
+ SetWorksheetRowCountMutation,
} from '@univerjs/sheets';
export class ActiveDirtyController extends Disposable {
@@ -178,6 +181,15 @@ export class ActiveDirtyController extends Disposable {
}
private _initialRowAndColumn() {
+ for (const mutation of [SetWorksheetRowCountMutation, SetWorksheetColumnCountMutation]) {
+ this._activeDirtyManagerService.register(mutation.id, {
+ commandId: mutation.id,
+ getDirtyData: (command: ICommandInfo) => ({
+ dirtyReferenceUnits: [(command.params as { unitId: string }).unitId],
+ }),
+ });
+ }
+
this._activeDirtyManagerService.register(RemoveRowMutation.id, {
commandId: RemoveRowMutation.id,
getDirtyData: (command: ICommandInfo) => {
@@ -272,16 +284,8 @@ export class ActiveDirtyController extends Disposable {
this._activeDirtyManagerService.register(SetWorksheetOrderMutation.id, {
commandId: SetWorksheetOrderMutation.id,
getDirtyData: (command: ICommandInfo) => {
- const { unitId } = command.params as { unitId: string };
- const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
- const sheets: Record<string, string> = Object.create(null);
- for (const sheet of workbook?.getSheets() ?? []) {
- sheets[sheet.getSheetId()] = sheet.getName();
- }
- return {
- forceCalculation: true,
- clearDependencyTreeCache: { [unitId]: sheets },
- };
+ const { unitId, fromOrder, toOrder } = command.params as ISetWorksheetOrderMutationParams;
+ return { dirtyReferenceUnits: fromOrder === toOrder ? [] : [unitId] };
},
});
this._activeDirtyManagerService.register(RemoveSheetMutation.id, {