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(formula): trigger persisted formulas with standard Base references (#7435)

Univerf9748943de07
diff --git a/packages/engine-formula/src/controllers/__tests__/formula-calculation-trigger.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/formula-calculation-trigger.controller.spec.ts
index 40b45f02d4..fa0df7564b 100644
--- a/packages/engine-formula/src/controllers/__tests__/formula-calculation-trigger.controller.spec.ts
+++ b/packages/engine-formula/src/controllers/__tests__/formula-calculation-trigger.controller.spec.ts
@@ -18,7 +18,6 @@ import * as core from '@univerjs/core';
import { BehaviorSubject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { FormulaCalculationTriggerService } from '../../services/formula-calculation-trigger.service';
-import { RegisterOtherFormulaService } from '../../services/register-other-formula.service';
import { FormulaCalculationTriggerController } from '../formula-calculation-trigger.controller';
describe('FormulaCalculationTriggerController', () => {
@@ -27,39 +26,32 @@ describe('FormulaCalculationTriggerController', () => {
it('starts immediately in Node.js', () => {
vi.spyOn(core, 'isNodeEnv').mockReturnValue(true);
const start = vi.fn();
- const calculateStarted$ = new BehaviorSubject(false);
const lifecycle$ = new BehaviorSubject(core.LifecycleStages.Ready);
const injector = new core.Injector([
[FormulaCalculationTriggerService, { useValue: { start } }],
- [RegisterOtherFormulaService, { useValue: { calculateStarted$ } }],
[core.LifecycleService, { useValue: { lifecycle$ } }],
]);
const controller = injector.createInstance(FormulaCalculationTriggerController);
expect(start).toHaveBeenCalledOnce();
- expect(calculateStarted$.getValue()).toBe(true);
controller.dispose();
});
it('starts after rendering in the browser', () => {
vi.spyOn(core, 'isNodeEnv').mockReturnValue(false);
const start = vi.fn();
- const calculateStarted$ = new BehaviorSubject(false);
const lifecycle$ = new BehaviorSubject(core.LifecycleStages.Ready);
const injector = new core.Injector([
[FormulaCalculationTriggerService, { useValue: { start } }],
- [RegisterOtherFormulaService, { useValue: { calculateStarted$ } }],
[core.LifecycleService, { useValue: { lifecycle$ } }],
]);
const controller = injector.createInstance(FormulaCalculationTriggerController);
expect(start).not.toHaveBeenCalled();
- expect(calculateStarted$.getValue()).toBe(false);
lifecycle$.next(core.LifecycleStages.Rendered);
expect(start).toHaveBeenCalledOnce();
- expect(calculateStarted$.getValue()).toBe(true);
lifecycle$.next(core.LifecycleStages.Steady);
expect(start).toHaveBeenCalledOnce();
diff --git a/packages/engine-formula/src/controllers/formula-calculation-trigger.controller.ts b/packages/engine-formula/src/controllers/formula-calculation-trigger.controller.ts
index 29110e0672..0a577a639d 100644
--- a/packages/engine-formula/src/controllers/formula-calculation-trigger.controller.ts
+++ b/packages/engine-formula/src/controllers/formula-calculation-trigger.controller.ts
@@ -17,20 +17,15 @@
import { Disposable, Inject, isNodeEnv, LifecycleService, LifecycleStages } from '@univerjs/core';
import { filter, take } from 'rxjs';
import { FormulaCalculationTriggerService } from '../services/formula-calculation-trigger.service';
-import { RegisterOtherFormulaService } from '../services/register-other-formula.service';
export class FormulaCalculationTriggerController extends Disposable {
constructor(
@Inject(FormulaCalculationTriggerService) formulaCalculationTriggerService: FormulaCalculationTriggerService,
- @Inject(RegisterOtherFormulaService) registerOtherFormulaService: RegisterOtherFormulaService,
@Inject(LifecycleService) lifecycleService: LifecycleService
) {
super();
- const start = () => {
- formulaCalculationTriggerService.start();
- registerOtherFormulaService.calculateStarted$.next(true);
- };
+ const start = () => formulaCalculationTriggerService.start();
if (isNodeEnv()) {
start();
diff --git a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
index 64ee9039ec..c6c8d96c2a 100644
--- a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
+++ b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
@@ -1090,7 +1090,7 @@ describe('Test formula data model', () => {
expect(formulaData['base-test']?.['table-main']).toEqual({
0: {
7: {
- f: '=SUM(table-main[[#This Row],[Amount]], table-main[[#This Row],[Qty]], tableOther[[#Data],[External]])',
+ f: '=SUM(_T_table_x2d_main[[#This Row],[Amount]], _T_table_x2d_main[[#This Row],[Qty]], _T_tableOther[[#Data],[External]])',
si: 'total',
},
},
@@ -1104,6 +1104,8 @@ describe('Test formula data model', () => {
unitType: UniverInstanceType.UNIVER_BASE,
});
expect(calculateData.unitSheetNameMap['base-test']?.Sales).toBe('tableOther');
+ expect(calculateData.unitSheetNameMap['base-test']?._T_table_x2d_main).toBe('table-main');
+ expect(calculateData.unitSheetNameMap['base-test']?._T_tableOther).toBe('tableOther');
expect(tableData?.rowCount).toBe(1);
expect(tableData?.columnCount).toBe(8);
expect(tableData?.cellData.getValue(0, 0)).toEqual({ v: 'record-1', t: CellValueType.STRING });
@@ -1114,6 +1116,55 @@ describe('Test formula data model', () => {
expect(tableData?.cellData.getValue(0, 6)).toEqual({ v: '', t: CellValueType.STRING });
});
+ it('preserves explicit current-row scope and expands qualified columns to #Data', () => {
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.registerCtorForType(UniverInstanceType.UNIVER_BASE, BaseDataModel);
+ const snapshot = structuredClone(TEST_BASE_DATA);
+ snapshot.id = 'base-structured-scope';
+ snapshot.tables!['table-main'].name = 'Orders';
+ snapshot.tables!.tableOther.name = 'Pricing';
+ snapshot.tables!['table-main'].fields.total.config = {
+ formula: '=Orders[@[Amount]]+[@[Qty]]+SUM(Pricing[External])',
+ };
+ univer.createUnit(UniverInstanceType.UNIVER_BASE, snapshot);
+
+ expect(formulaDataModel.getFormulaData()['base-structured-scope']?.['table-main']?.[0]?.[7]?.f).toBe(
+ '=Orders[[#This Row],[Amount]]+Orders[[#This Row],[Qty]]+SUM(Pricing[[#Data],[External]])'
+ );
+ });
+
+ it('does not reinterpret an unresolved table identifier as the current Base table', () => {
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.registerCtorForType(UniverInstanceType.UNIVER_BASE, BaseDataModel);
+ const snapshot = structuredClone(TEST_BASE_DATA);
+ snapshot.id = 'base-unresolved-table';
+ snapshot.tables!['table-main'].name = 'Orders';
+ snapshot.tables!['table-main'].fields.total.config = {
+ formula: '=SUM(table[Amount])+table[[#This Row],[Qty]]',
+ };
+ univer.createUnit(UniverInstanceType.UNIVER_BASE, snapshot);
+
+ expect(formulaDataModel.getFormulaData()['base-unresolved-table']?.['table-main']?.[0]?.[7]?.f).toBe(
+ '=SUM(table[Amount])+table[[#This Row],[Qty]]'
+ );
+ });
+
+ it('resolves table when it is the real Base table name', () => {
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.registerCtorForType(UniverInstanceType.UNIVER_BASE, BaseDataModel);
+ const snapshot = structuredClone(TEST_BASE_DATA);
+ snapshot.id = 'base-real-table-name';
+ snapshot.tables!['table-main'].name = 'table';
+ snapshot.tables!['table-main'].fields.total.config = {
+ formula: '=SUM(table[Amount])+table[[#This Row],[Qty]]',
+ };
+ univer.createUnit(UniverInstanceType.UNIVER_BASE, snapshot);
+
+ expect(formulaDataModel.getFormulaData()['base-real-table-name']?.['table-main']?.[0]?.[7]?.f).toBe(
+ '=SUM(table[[#Data],[Amount]])+table[[#This Row],[Qty]]'
+ );
+ });
+
it('should preserve workbook-qualified A1 references in Base formulas', () => {
const univerInstanceService = get(IUniverInstanceService);
univerInstanceService.registerCtorForType(UniverInstanceType.UNIVER_BASE, BaseDataModel);
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index 9a6786a6b3..1fde87d8b6 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -416,7 +416,7 @@ export class FormulaDataModel extends Disposable {
rowData: {},
columnData: {},
};
- tableNameMap[table.name] = table.id;
+ addEngineBaseTableNameMappings(tableNameMap, table, snapshot);
}
allUnitData[unitId] = baseData;
@@ -942,8 +942,12 @@ export function initSheetFormulaData(
}
const BASE_LEGACY_FIELD_REF_PATTERN = /\{([^}]+)\}/g;
-const BASE_TABLE_FIELD_REF_PATTERN = /\b([A-Z_]\w*)\[([^\]]+)\]/gi;
-const BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^A-Za-z0-9_\]\[])\[([^\]]+)\]/g;
+const BASE_TABLE_SCOPED_FIELD_REF_PATTERN = /\b([A-Z_][\w.]*)\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]/gi;
+const BASE_TABLE_CURRENT_ROW_FIELD_REF_PATTERN = /\b([A-Z_][\w.]*)\[@\[([^\]]+)\]\]/gi;
+const BASE_TABLE_FIELD_REF_PATTERN = /\b([A-Z_][\w.]*)\[([^\[\]#]+)\]/gi;
+const BASE_SCOPED_FIELD_REF_PATTERN = /(^|[^\w\[])\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]/gi;
+const BASE_CURRENT_ROW_FIELD_REF_PATTERN = /(^|[^\w\[])\[@\[([^\]]+)\]\](?!\])/g;
+const BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^\w\[])\[@?([^\[\]#]+)\](?!\])/g;
const BASE_EXTERNAL_A1_REF_PATTERN = /(?:'\[[^\]]+\](?:[^']|'')+'|\[[^\]]+\][^\s'!]+)!\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?/gi;
const BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX = /(?:'((?:[^']|'')+)'|\[[^\]]+\]|[A-Za-z0-9_.-]+)![^\s!\[\]]+\[/g;
@@ -953,11 +957,32 @@ function normalizeBaseFormulaForEngine(formula: string, currentTable: ITableSnap
const index = refs.push(ref) - 1;
return `__BASE_FORMULA_REF_${index}__`;
};
- const normalized = protectBaseExternalReferences(formula, hold)
+ const normalized = protectBaseFormulaParts(formula, hold)
.replace(BASE_LEGACY_FIELD_REF_PATTERN, (_match, fieldName: string) => hold(createEngineThisRowRef(currentTable, fieldName, snapshot)))
+ .replace(BASE_TABLE_SCOPED_FIELD_REF_PATTERN, (_match, sourceTableName: string, scope: string, fieldName: string) => {
+ const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot);
+ if (!targetTable) return `${sourceTableName}[[#${scope}],[${fieldName}]]`;
+ return hold(scope.toLowerCase() === 'data'
+ ? createEngineColumnRef(targetTable, fieldName, snapshot)
+ : createEngineThisRowRef(targetTable, fieldName, snapshot));
+ })
+ .replace(BASE_TABLE_CURRENT_ROW_FIELD_REF_PATTERN, (_match, sourceTableName: string, fieldName: string) => {
+ const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot);
+ return targetTable
+ ? hold(createEngineThisRowRef(targetTable, fieldName, snapshot))
+ : `${sourceTableName}[@[${fieldName}]]`;
+ })
+ .replace(BASE_SCOPED_FIELD_REF_PATTERN, (_match, prefix: string, scope: string, fieldName: string) => `${prefix}${hold(
+ scope.toLowerCase() === 'data'
+ ? createEngineColumnRef(currentTable, fieldName, snapshot)
+ : createEngineThisRowRef(currentTable, fieldName, snapshot)
+ )}`)
+ .replace(BASE_CURRENT_ROW_FIELD_REF_PATTERN, (_match, prefix: string, fieldName: string) =>
+ `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, snapshot))}`)
.replace(BASE_TABLE_FIELD_REF_PATTERN, (_match, sourceTableName: string, fieldName: string) => {
const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot);
- return targetTable ? hold(createEngineColumnRef(targetTable, fieldName, snapshot)) : `${sourceTableName}[${fieldName}]`;
+ if (targetTable) return hold(createEngineColumnRef(targetTable, fieldName, snapshot));
+ return `${sourceTableName}[${fieldName}]`;
})
.replace(BASE_BRACKET_FIELD_REF_PATTERN, (_match, prefix: string, fieldName: string) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, snapshot))}`);
return normalized.replace(/__BASE_FORMULA_REF_(\d+)__/g, (_match, index: string) => refs[Number(index)] ?? '');
@@ -969,14 +994,23 @@ function protectBaseExternalReferences(formula: string, replace: (reference: str
return protectBaseExternalStructuredReferences(withProtectedA1, replace);
}
+function protectBaseFormulaParts(formula: string, replace: (reference: string) => string): string {
+ return protectBaseFormulaStrings(protectBaseExternalReferences(formula, replace), replace);
+}
+
+function protectBaseFormulaStrings(formula: string, replace: (reference: string) => string): string {
+ return formula.replace(/"(?:""|[^"])*"/g, replace);
+}
+
function protectBaseExternalStructuredReferences(
formula: string,
replace: (reference: string) => string
): string {
const spans: Array<{ start: number; end: number }> = [];
BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.lastIndex = 0;
- let match: RegExpExecArray | null;
- while ((match = BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.exec(formula)) != null) {
+ while (true) {
+ const match = BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.exec(formula);
+ if (match == null) break;
if (isInsideBaseFormulaString(formula, match.index)) continue;
const openBracket = BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.lastIndex - 1;
let depth = 0;
@@ -1029,14 +1063,41 @@ function getEngineBaseTableName(table: ITableSnapshot, snapshot: IBaseSnapshot):
let sameNameCount = 0;
for (let i = 0; i < tables.length; i++) {
const item = tables[i];
- if (item.name === table.name) {
+ if (item.name.trim().toLowerCase() === table.name.trim().toLowerCase()) {
sameNameCount++;
if (sameNameCount > 1) {
break;
}
}
}
- return sameNameCount === 1 ? table.name : table.id;
+ return sameNameCount === 1 && isExcelTableName(table.name)
+ ? table.name
+ : createStableExcelTableName(table.id);
+}
+
+function addEngineBaseTableNameMappings(
+ tableNameMap: Record<string, string>,
+ table: ITableSnapshot,
+ snapshot: IBaseSnapshot
+): void {
+ tableNameMap[table.name] = table.id;
+ tableNameMap[getEngineBaseTableName(table, snapshot)] = table.id;
+}
+
+function isExcelTableName(name: string): boolean {
+ if (name.length === 0 || name.length > 255 || !/^[A-Za-z_][A-Za-z0-9_.]*$/.test(name)) {
+ return false;
+ }
+ return !/^[RC]$/i.test(name)
+ && !/^[A-Za-z]{1,3}[1-9]\d*$/.test(name)
+ && !/^R(?:\d+)?C(?:\d+)?$/i.test(name);
+}
+
+function createStableExcelTableName(tableId: string): string {
+ const encoded = Array.from(tableId, (character) => /[A-Za-z0-9]/.test(character)
+ ? character
+ : `_x${character.codePointAt(0)?.toString(16) ?? '0'}_`).join('');
+ return `_T_${encoded}`;
}
function buildBaseRuntimeCellData(table: ITableSnapshot): Record<number, Record<number, IBaseCellData>> {
@@ -1144,7 +1205,7 @@ function isBaseCellData(value: unknown): value is IBaseCellData {
}
function resolveBaseFormulaTable(tableName: string | undefined, currentTable: ITableSnapshot, snapshot: IBaseSnapshot): ITableSnapshot | undefined {
- if (!tableName || tableName === 'table' || tableName === currentTable.id || tableName === currentTable.name) {
+ if (!tableName || tableName === currentTable.id || tableName === currentTable.name) {
return currentTable;
}
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 242ae96cef..19251aae27 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
@@ -94,6 +94,36 @@ describe('FormulaCalculationTriggerService', () => {
testBed.service.dispose();
});
+ it('queues Other Formula dirty data before start and flushes it after start', async () => {
+ const testBed = createTestBed(false);
+ testBed.conversions.set('other-formula-dirty', {
+ commandId: 'other-formula-dirty',
+ getDirtyData: () => ({
+ dirtyUnitOtherFormulaMap: {
+ 'doc-unit': { 'shape-unit': { 'formula-1': true } },
+ },
+ }),
+ });
+
+ testBed.emit({ id: 'other-formula-dirty' } as ICommandInfo);
+ await vi.advanceTimersByTimeAsync(10);
+ expect(testBed.executed).toEqual([]);
+
+ testBed.service.start();
+ await vi.advanceTimersByTimeAsync(10);
+
+ expect(testBed.executed).toHaveLength(1);
+ expect(testBed.executed[0]).toMatchObject({
+ id: SetFormulaCalculationStartMutation.id,
+ params: {
+ dirtyUnitOtherFormulaMap: {
+ 'doc-unit': { 'shape-unit': { 'formula-1': true } },
+ },
+ },
+ });
+ testBed.service.dispose();
+ });
+
it('merges dirty data from different unit types into one calculation', async () => {
const testBed = createTestBed();
testBed.conversions.set('sheet-dirty', {
diff --git a/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts b/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts
index cdb54d9ded..aabc95a725 100644
--- a/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts
@@ -23,6 +23,7 @@ import {
ILogService,
Injector,
LifecycleService,
+ LifecycleStages,
} from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { OtherFormulaMarkDirty } from '../../commands/mutations/formula.mutation';
@@ -34,10 +35,11 @@ import { OtherFormulaBizType, RegisterOtherFormulaService } from '../register-ot
type FormulaResultMatrix = Record<number, Record<number, Array<{ v?: unknown }>>>;
-function createService(): {
+function createService(registerCommands = true): {
service: RegisterOtherFormulaService;
commandService: ICommandService;
activeDirtyManagerService: IActiveDirtyManagerService;
+ lifecycleService: LifecycleService;
} {
const injector = new Injector();
injector.add([ILogService, { useClass: DesktopLogService }]);
@@ -47,15 +49,19 @@ function createService(): {
injector.add([LifecycleService]);
injector.add([RegisterOtherFormulaService]);
const commandService = injector.get(ICommandService);
- commandService.registerCommand(SetOtherFormulaMutation);
- commandService.registerCommand(RemoveOtherFormulaMutation);
- commandService.registerCommand(OtherFormulaMarkDirty);
- commandService.registerCommand(SetFormulaCalculationResultMutation);
+ const service = injector.get(RegisterOtherFormulaService);
+ if (registerCommands) {
+ commandService.registerCommand(SetOtherFormulaMutation);
+ commandService.registerCommand(RemoveOtherFormulaMutation);
+ commandService.registerCommand(OtherFormulaMarkDirty);
+ commandService.registerCommand(SetFormulaCalculationResultMutation);
+ }
return {
- service: injector.get(RegisterOtherFormulaService),
+ service,
commandService,
activeDirtyManagerService: injector.get(IActiveDirtyManagerService),
+ lifecycleService: injector.get(LifecycleService),
};
}
@@ -73,32 +79,45 @@ describe('RegisterOtherFormulaService', () => {
expect(activeDirtyManagerService.get(OtherFormulaMarkDirty.id)?.commandId).toBe(OtherFormulaMarkDirty.id);
});
- it('should buffer register requests until calculation starts', async () => {
+ it('should register immediately and leave pre-start scheduling to the calculation trigger', async () => {
const { service, commandService } = createService();
const executedIds: string[] = [];
commandService.onCommandExecuted((command) => executedIds.push(command.id));
const formulaId = service.registerFormulaWithRange('unit-1', 'sheet-1', '=A1');
expect(formulaId.startsWith('formula.unit-1_sheet-1_default_')).toBe(true);
- expect(executedIds).not.toContain(SetOtherFormulaMutation.id);
-
- service.calculateStarted$.next(true);
await flushCommandChain();
expect(executedIds).toEqual([SetOtherFormulaMutation.id, OtherFormulaMarkDirty.id]);
});
- it('should register immediately after calculation started', async () => {
+ it('should register every formula once without a second lifecycle gate', async () => {
const { service, commandService } = createService();
const executedIds: string[] = [];
commandService.onCommandExecuted((command) => executedIds.push(command.id));
- service.calculateStarted$.next(true);
service.registerFormulaWithRange('unit-2', 'sheet-2', '=SUM(A1:A5)', [], { source: 'test' }, OtherFormulaBizType.DOC, 'doc-1');
await flushCommandChain();
- expect(executedIds).toContain(SetOtherFormulaMutation.id);
+ expect(executedIds).toEqual([SetOtherFormulaMutation.id, OtherFormulaMarkDirty.id]);
+ });
+
+ it('should defer registration until formula commands are available', async () => {
+ const { service, commandService, lifecycleService } = createService(false);
+ const executedIds: string[] = [];
+ commandService.onCommandExecuted((command) => executedIds.push(command.id));
+
+ service.registerFormulaWithRange('unit-3', 'sheet-3', '=A1');
+ await flushCommandChain();
+ expect(executedIds).toEqual([]);
+
+ commandService.registerCommand(SetOtherFormulaMutation);
+ commandService.registerCommand(OtherFormulaMarkDirty);
+ lifecycleService.stage = LifecycleStages.Ready;
+ await flushCommandChain();
+
+ expect(executedIds).toEqual([SetOtherFormulaMutation.id, OtherFormulaMarkDirty.id]);
});
it('should expose all registered formulas for host-level dirty propagation', () => {
diff --git a/packages/engine-formula/src/services/register-other-formula.service.ts b/packages/engine-formula/src/services/register-other-formula.service.ts
index 25cabb8541..d05f054ec1 100644
--- a/packages/engine-formula/src/services/register-other-formula.service.ts
+++ b/packages/engine-formula/src/services/register-other-formula.service.ts
@@ -28,9 +28,10 @@ import {
ICommandService,
Inject,
LifecycleService,
+ LifecycleStages,
ObjectMatrix,
} from '@univerjs/core';
-import { BehaviorSubject, bufferWhen, filter, skip, Subject } from 'rxjs';
+import { Subject } from 'rxjs';
import { OtherFormulaMarkDirty } from '../commands/mutations/formula.mutation';
import { SetFormulaCalculationResultMutation } from '../commands/mutations/set-formula-calculation.mutation';
import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../commands/mutations/set-other-formula.mutation';
@@ -60,8 +61,6 @@ export class RegisterOtherFormulaService extends Disposable {
private _otherFormulaResultApplied$ = new Subject<ISetFormulaCalculationResultMutation>();
public otherFormulaResultApplied$ = this._otherFormulaResultApplied$.asObservable();
- public calculateStarted$ = new BehaviorSubject(false);
-
constructor(
@ICommandService private readonly _commandService: ICommandService,
@IActiveDirtyManagerService private _activeDirtyManagerService: IActiveDirtyManagerService,
@@ -78,7 +77,6 @@ export class RegisterOtherFormulaService extends Disposable {
this._formulaChangeWithRange$.complete();
this._formulaResult$.complete();
this._otherFormulaResultApplied$.complete();
- this.calculateStarted$.complete();
}
private _ensureCacheMap(unitId: string, subUnitId: string) {
@@ -149,17 +147,21 @@ export class RegisterOtherFormulaService extends Disposable {
});
};
- this.disposeWithMe(
- this._formulaChangeWithRange$
- .pipe(bufferWhen(() => this.calculateStarted$.pipe(skip(1), filter((calculateStarted) => calculateStarted))))
- .subscribe((options) => options.forEach(handleRegister))
- );
+ this.disposeWithMe(this._formulaChangeWithRange$.subscribe((option) => {
+ if (
+ this._commandService.hasCommand(SetOtherFormulaMutation.id)
+ && this._commandService.hasCommand(OtherFormulaMarkDirty.id)
+ ) {
+ handleRegister(option);
+ return;
+ }
- this.disposeWithMe(
- this._formulaChangeWithRange$
- .pipe(filter(() => this.calculateStarted$.getValue()))
- .subscribe(handleRegister)
- );
+ this._lifecycleService.onStage(LifecycleStages.Ready).then(() => {
+ if (!this._disposed) {
+ handleRegister(option);
+ }
+ });
+ }));
}
private _initFormulaCalculationResultChange() {
diff --git a/packages/sheets-formula/src/controllers/__tests__/sheet-formula-trigger.integration.spec.ts b/packages/sheets-formula/src/controllers/__tests__/sheet-formula-trigger.integration.spec.ts
new file mode 100644
index 0000000000..cc4fb8e975
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/__tests__/sheet-formula-trigger.integration.spec.ts
@@ -0,0 +1,117 @@
+/**
+ * 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 {
+ ICommandService,
+ isNodeEnv,
+ LifecycleService,
+ LifecycleStages,
+ LocaleService,
+ LocaleType,
+ Univer,
+} from '@univerjs/core';
+import { FUniver } from '@univerjs/core/facade';
+import { SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { UniverSheetsFormulaPlugin } from '../../plugin';
+import '@univerjs/engine-formula/facade';
+import '@univerjs/sheets/facade';
+import '../../facade';
+
+function createWorkbookData() {
+ return {
+ id: 'standalone-sheet-formula',
+ name: 'Standalone Sheet Formula',
+ appVersion: 'test',
+ locale: LocaleType.EN_US,
+ styles: {},
+ sheetOrder: ['sheet-1'],
+ sheets: {
+ 'sheet-1': {
+ id: 'sheet-1',
+ name: 'Sheet1',
+ rowCount: 20,
+ columnCount: 20,
+ cellData: {
+ 0: {
+ 0: { v: 2 },
+ 1: { f: '=A1*2' },
+ },
+ },
+ },
+ },
+ };
+}
+
+describe('standalone Sheet formula calculation trigger', () => {
+ let univer: Univer | undefined;
+
+ afterEach(() => {
+ univer?.dispose();
+ univer = undefined;
+ vi.restoreAllMocks();
+ });
+
+ it('calculates on cold start and recalculates after value and formula edits', async () => {
+ vi.mocked(isNodeEnv).mockReturnValue(false);
+
+ univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.get(LocaleService).load({ [LocaleType.EN_US]: {} });
+ injector.get(LocaleService).setLocale(LocaleType.EN_US);
+ univer.registerPlugin(UniverSheetsFormulaPlugin);
+
+ let calculationStarts = 0;
+ injector.get(ICommandService).onCommandExecuted((command) => {
+ if (command.id === SetFormulaCalculationStartMutation.id) {
+ calculationStarts++;
+ }
+ });
+
+ const api = FUniver.newAPI(univer);
+ const workbook = api.createWorkbook(createWorkbookData());
+ const sheet = workbook.getActiveSheet();
+ const input = sheet.getRange('A1');
+ const output = sheet.getRange('B1');
+
+ const startupResultApplied = api.getFormula().onCalculationResultApplied(10_000);
+ injector.get(LifecycleService).stage = LifecycleStages.Rendered;
+ await startupResultApplied;
+ expect(output.getValue()).toBe(4);
+ expect(calculationStarts).toBe(1);
+
+ const valueEditResultApplied = api.getFormula().onCalculationResultApplied(10_000);
+ input.setValue(3);
+ await valueEditResultApplied;
+ expect(output.getValue()).toBe(6);
+ expect(calculationStarts).toBe(2);
+
+ const formulaEditResultApplied = api.getFormula().onCalculationResultApplied(10_000);
+ output.setFormula('=A1*3');
+ await formulaEditResultApplied;
+ expect(output.getValue()).toBe(9);
+ expect(calculationStarts).toBe(3);
+ });
+});
+
+vi.mock('@univerjs/core', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@univerjs/core')>();
+
+ return {
+ ...actual,
+ isNodeEnv: vi.fn(actual.isNodeEnv),
+ };
+});