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): update formula data when remove sheet or insert sheet (#650)

Dushusirbc60c048fabf
diff --git a/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts
new file mode 100644
index 0000000000..9b74030ad5
--- /dev/null
+++ b/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts
@@ -0,0 +1,111 @@
+import type { IWorkbookData } from '@univerjs/core';
+import { ILogService, IUniverInstanceService, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+
+import { CalculateController } from '../../controller/calculate.controller';
+import { FormulaController } from '../../controller/formula.controller';
+import { FormulaDataModel } from '../../models/formula-data.model';
+import { ActiveDirtyManagerService, IActiveDirtyManagerService } from '../../services/active-dirty-manager.service';
+import { FormulaService, IFormulaService } from '../../services/formula.service';
+import { FormulaEngineService } from '../../services/formula-engine.service';
+
+const TEST_WORKBOOK_DATA: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ 0: {
+ 0: {
+ v: 1,
+ },
+ },
+ 1: {
+ 0: {
+ v: 4,
+ },
+ },
+ 2: {
+ 0: {
+ v: 44,
+ },
+ },
+ 3: {
+ 0: {
+ v: 444,
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+};
+export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+
+ let get: Injector['get'] | undefined;
+
+ /**
+ * This plugin hooks into Sheet's DI system to expose API to test scripts
+ */
+ class TestSpyPlugin extends Plugin {
+ static override type = PluginType.Sheet;
+
+ private _formulaDataModel: FormulaDataModel | null = null;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super('test-plugin');
+
+ this._injector = _injector;
+ get = this._injector.get.bind(this._injector);
+ }
+
+ override onStarting(injector: Injector): void {
+ injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);
+ injector.add([FormulaEngineService]);
+ this._formulaDataModel = this._injector.createInstance(FormulaDataModel);
+
+ injector.add([FormulaDataModel, { useValue: this._formulaDataModel }]);
+ injector.add([FormulaController]);
+ injector.add([IFormulaService, { useClass: FormulaService }]);
+ injector.add([CalculateController]);
+
+ dependencies?.forEach((d) => injector.add(d));
+ }
+
+ override onDestroy(): void {
+ get = undefined;
+ }
+
+ override onReady(): void {
+ this._formulaDataModel?.initFormulaData();
+ }
+ }
+
+ univer.registerPlugin(TestSpyPlugin);
+ const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA);
+
+ if (get === undefined) {
+ throw new Error('[TestPlugin]: not hooked on!');
+ }
+
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.focusUniverInstance('test');
+
+ const logService = get(ILogService);
+ logService.toggleLogEnabled(false); // change this to `true` to debug tests via logs
+
+ return {
+ univer,
+ get,
+ sheet,
+ };
+}
diff --git a/packages/engine-formula/src/functions/math/sumif/__tests__/sumif.spec.ts b/packages/engine-formula/src/functions/math/sumif/__tests__/sumif.spec.ts
index 704f98c096..140b7445a6 100644
--- a/packages/engine-formula/src/functions/math/sumif/__tests__/sumif.spec.ts
+++ b/packages/engine-formula/src/functions/math/sumif/__tests__/sumif.spec.ts
@@ -1,5 +1,52 @@
-import { describe, it } from 'vitest';
+import type { ICellData, Nullable, Univer } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService } from '@univerjs/core';
+import type { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, it } from 'vitest';
+
+import type { FormulaEngineService } from '../../../../services/formula-engine.service';
+import { createCommandTestBed } from '../../../__tests__/create-command-test-bed';
describe('test sumif', () => {
- it('correct situations', () => {});
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let formulaEngineService: FormulaEngineService;
+ let getValue: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Nullable<ICellData> | undefined;
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+
+ getValue = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Nullable<ICellData> | undefined =>
+ get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(startRow, startColumn, endRow, endColumn)
+ .getValue();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('range and criteria', async () => {
+ const params = {
+ value: {
+ f: '=SUMIF(A1:A4, ">40")',
+ },
+ };
+ });
});
diff --git a/packages/engine-formula/src/functions/math/sumif/sumif.ts b/packages/engine-formula/src/functions/math/sumif/sumif.ts
index cb7c5d4706..d25bb0adef 100644
--- a/packages/engine-formula/src/functions/math/sumif/sumif.ts
+++ b/packages/engine-formula/src/functions/math/sumif/sumif.ts
@@ -2,7 +2,7 @@ import { ErrorType } from '../../../basics/error-type';
import type { compareToken } from '../../../basics/token';
import { ErrorValueObject } from '../../../engine/other-object/error-value-object';
import type { BaseReferenceObject, FunctionVariantType } from '../../../engine/reference-object/base-reference-object';
-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
+import { type ArrayValueObject, ValueObjectFactory } from '../../../engine/value-object/array-value-object';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import type { BooleanValueObject } from '../../../engine/value-object/primitive-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
@@ -28,13 +28,26 @@ export class Sumif extends BaseFunction {
let accumulatorAll: BaseValueObject = new NumberValueObject(0);
if (range.isReferenceObject() || (range.isValueObject() && (range as BaseValueObject).isArray())) {
- (range as BaseReferenceObject | ArrayValueObject).iterator((valueObject, row, column) => {
- if (!valueObject.isErrorObject() && criteria.isValueObject()) {
- // TODO@Dushusir: criteria is referenceObject
- const accumulator = this._validator(valueObject as BaseValueObject, criteria as BaseValueObject);
- accumulatorAll = accumulatorAll.plus(accumulator) as BaseValueObject;
- }
- });
+ // TODO@Dushusir: criteria is referenceObject
+ const criteriaValueString = (criteria as BaseValueObject).getValue();
+ if (criteriaValueString) {
+ const token = (criteriaValueString as string).substring(0, 1) as compareToken;
+ const criteriaString = (criteriaValueString as string).substring(1);
+ const resultArrayObject = (range as BaseReferenceObject)
+ .toArrayValueObject()
+ .compare(ValueObjectFactory.create(criteriaString) as BaseValueObject, token);
+ const resultArrayValue = (resultArrayObject as ArrayValueObject).getArrayValue();
+
+ (range as BaseReferenceObject | ArrayValueObject).iterator((valueObject, row, column) => {
+ if (!valueObject.isErrorObject()) {
+ const arrayValue = resultArrayValue[row][column] as BaseValueObject;
+ const accumulator = arrayValue.getValue()
+ ? (valueObject as BaseValueObject)
+ : new NumberValueObject(0);
+ accumulatorAll = accumulatorAll.plus(accumulator) as BaseValueObject;
+ }
+ });
+ }
} else if (criteria.isValueObject()) {
// TODO@Dushusir: criteria is referenceObject
accumulatorAll = this._validator(range as BaseValueObject, criteria as BaseValueObject);
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index febd8e6241..4cc610f62b 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -40,7 +40,7 @@ export { ErrorValueObject } from './engine/other-object/error-value-object';
export { BaseReferenceObject, type FunctionVariantType } from './engine/reference-object/base-reference-object';
export { RangeReferenceObject } from './engine/reference-object/range-reference-object';
export { generateStringWithSequence, type ISequenceNode, sequenceNodeType } from './engine/utils/sequence';
-export { ArrayValueObject } from './engine/value-object/array-value-object';
+export { ArrayValueObject, ValueObjectFactory } from './engine/value-object/array-value-object';
export { BaseValueObject } from './engine/value-object/base-value-object';
export { NumberValueObject } from './engine/value-object/primitive-object';
export { BooleanValueObject } from './engine/value-object/primitive-object';
@@ -48,6 +48,7 @@ export { StringValueObject } from './engine/value-object/primitive-object';
export { BaseFunction } from './functions/base-function';
export { FUNCTION_NAMES_MATH } from './functions/math/function-names';
export { FormulaDataModel } from './models/formula-data.model';
+export { initSheetFormulaData } from './models/formula-data.model';
export { BaseFormulaEnginePlugin } from './plugin';
export { IActiveDirtyManagerService } from './services/active-dirty-manager.service';
export { FormulaEngineService } from './services/formula-engine.service';
diff --git a/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts
new file mode 100644
index 0000000000..e30df2464a
--- /dev/null
+++ b/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts
@@ -0,0 +1,83 @@
+import type { IWorkbookData } from '@univerjs/core';
+import { ILogService, IUniverInstanceService, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+
+import { FormulaEngineService } from '../../services/formula-engine.service';
+import { FormulaDataModel } from '../formula-data.model';
+
+const TEST_WORKBOOK_DATA: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ '0': {
+ '0': {
+ v: 'A1',
+ },
+ '1': {
+ v: 'B1',
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+};
+export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+
+ let get: Injector['get'] | undefined;
+
+ /**
+ * This plugin hooks into Sheet's DI system to expose API to test scripts
+ */
+ class TestSpyPlugin extends Plugin {
+ static override type = PluginType.Sheet;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super('test-plugin');
+
+ this._injector = _injector;
+ get = this._injector.get.bind(this._injector);
+ }
+
+ override onStarting(injector: Injector): void {
+ injector.add([FormulaEngineService]);
+ injector.add([FormulaDataModel]);
+
+ dependencies?.forEach((d) => injector.add(d));
+ }
+
+ override onDestroy(): void {
+ get = undefined;
+ }
+ }
+
+ univer.registerPlugin(TestSpyPlugin);
+ const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA);
+
+ if (get === undefined) {
+ throw new Error('[TestPlugin]: not hooked on!');
+ }
+
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.focusUniverInstance('test');
+
+ const logService = get(ILogService);
+ logService.toggleLogEnabled(false); // change this to `true` to debug tests via logs
+
+ return {
+ univer,
+ get,
+ sheet,
+ };
+}
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
new file mode 100644
index 0000000000..7282695f9a
--- /dev/null
+++ b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
@@ -0,0 +1,295 @@
+import type { ICellData, IWorkbookData, Nullable, Univer } from '@univerjs/core';
+import { IUniverInstanceService, LocaleType, ObjectMatrix } from '@univerjs/core';
+import type { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { FormulaDataModel, initSheetFormulaData } from '../formula-data.model';
+import { createCommandTestBed } from './create-command-test-bed';
+
+const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ '0': {
+ '3': {
+ f: '=SUM(A1)',
+ si: '3e4r5t',
+ },
+ },
+ '1': {
+ '3': {
+ f: '=SUM(A2)',
+ si: 'OSPtzm',
+ },
+ },
+ '2': {
+ '3': {
+ si: 'OSPtzm',
+ },
+ },
+ '3': {
+ '3': {
+ si: 'OSPtzm',
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+};
+
+describe('Test formula data model', () => {
+ describe('updateFormulaData', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let formulaDataModel: FormulaDataModel;
+ let getValues: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Array<Array<Nullable<ICellData>>> | undefined;
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed(TEST_WORKBOOK_DATA_DEMO);
+ univer = testBed.univer;
+ get = testBed.get;
+
+ formulaDataModel = get(FormulaDataModel);
+
+ getValues = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Array<Array<Nullable<ICellData>>> | undefined =>
+ get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(startRow, startColumn, endRow, endColumn)
+ .getValues();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('delete formula with id', () => {
+ formulaDataModel.initFormulaData();
+
+ const unitId = 'test';
+ const sheetId = 'sheet1';
+ const cellValue = {
+ '1': {
+ '3': {
+ v: null,
+ p: null,
+ f: null,
+ si: null,
+ },
+ },
+ };
+
+ const result = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(A1)',
+ si: '3e4r5t',
+ },
+ },
+ '2': {
+ '3': {
+ f: '=SUM(A3)',
+ si: 'OSPtzm',
+ },
+ },
+ '3': {
+ '3': {
+ f: '=SUM(A3)',
+ si: 'OSPtzm',
+ x: 0,
+ y: 1,
+ },
+ },
+ },
+ },
+ };
+
+ formulaDataModel.updateFormulaData(unitId, sheetId, cellValue);
+
+ const formulaData = formulaDataModel.getFormulaData();
+ expect(formulaData).toStrictEqual(result);
+ });
+
+ it('delete formulas with ids and formulas with only ids', () => {
+ formulaDataModel.initFormulaData();
+
+ const unitId = 'test';
+ const sheetId = 'sheet1';
+ const cellValue = {
+ '0': {
+ '3': {
+ v: null,
+ p: null,
+ f: null,
+ si: null,
+ },
+ },
+ '1': {
+ '3': {
+ v: null,
+ p: null,
+ f: null,
+ si: null,
+ },
+ },
+ '2': {
+ '3': {
+ v: null,
+ p: null,
+ f: null,
+ si: null,
+ },
+ },
+ };
+
+ const result = {
+ [unitId]: {
+ [sheetId]: {
+ '3': {
+ '3': {
+ f: '=SUM(A4)',
+ si: 'OSPtzm',
+ },
+ },
+ },
+ },
+ };
+
+ formulaDataModel.updateFormulaData(unitId, sheetId, cellValue);
+
+ const formulaData = formulaDataModel.getFormulaData();
+ expect(formulaData).toStrictEqual(result);
+ });
+
+ it('delete the formula with only id', () => {
+ formulaDataModel.initFormulaData();
+
+ const unitId = 'test';
+ const sheetId = 'sheet1';
+ const cellValue = {
+ '3': {
+ '3': {
+ v: null,
+ p: null,
+ f: null,
+ si: null,
+ },
+ },
+ };
+
+ const result = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(A1)',
+ si: '3e4r5t',
+ },
+ },
+ '1': {
+ '3': {
+ f: '=SUM(A2)',
+ si: 'OSPtzm',
+ },
+ },
+ '2': {
+ '3': {
+ f: '=SUM(A2)',
+ si: 'OSPtzm',
+ x: 0,
+ y: 1,
+ },
+ },
+ },
+ },
+ };
+
+ formulaDataModel.updateFormulaData(unitId, sheetId, cellValue);
+
+ const formulaData = formulaDataModel.getFormulaData();
+ expect(formulaData).toStrictEqual(result);
+ });
+ });
+
+ describe('function initSheetFormulaData', () => {
+ it('init formula data', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+
+ const formulaData = {
+ [unitId]: {},
+ };
+
+ const cellValue = {
+ '0': {
+ '0': {
+ v: 1,
+ },
+ '1': {
+ v: 2,
+ },
+ '2': {
+ v: 3,
+ },
+ '3': {
+ v: 2,
+ f: '=SUM(A1)',
+ si: '3e4r5t',
+ },
+ },
+ '1': {
+ '0': {
+ v: 4,
+ },
+ },
+ '2': {
+ '0': {
+ v: 44,
+ },
+ },
+ '3': {
+ '0': {
+ v: 444,
+ },
+ },
+ };
+
+ const cellMatrix = new ObjectMatrix(cellValue);
+
+ const result = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(A1)',
+ si: '3e4r5t',
+ },
+ },
+ },
+ },
+ };
+
+ initSheetFormulaData(formulaData, unitId, sheetId, cellMatrix);
+ expect(formulaData).toStrictEqual(result);
+ });
+ });
+});
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index 40a5911235..de507165da 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -7,6 +7,7 @@ import {
IUniverInstanceService,
ObjectMatrix,
} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
import type {
IArrayFormulaRangeType,
@@ -18,6 +19,7 @@ import type {
IUnitData,
IUnitSheetNameMap,
} from '../basics/common';
+import { FormulaEngineService } from '../services/formula-engine.service';
export interface IFormulaConfig {
notExecuteFormula?: boolean;
@@ -34,7 +36,8 @@ export class FormulaDataModel extends Disposable {
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService
) {
super();
}
@@ -203,33 +206,9 @@ export class FormulaDataModel extends Disposable {
const worksheets = workbook.getSheets();
worksheets.forEach((worksheet) => {
const cellMatrix = worksheet.getCellMatrix();
- const sheetFormulaDataMatrix = new ObjectMatrix<IFormulaDataItem>();
- cellMatrix.forValue((r, c, cell) => {
- const formulaString = cell?.f || '';
- const formulaId = cell?.si || '';
-
- const checkFormulaString = isFormulaString(formulaString);
- const checkFormulaId = isFormulaId(formulaId);
-
- if (checkFormulaString && checkFormulaId) {
- sheetFormulaDataMatrix.setValue(r, c, {
- f: formulaString,
- si: formulaId,
- });
- } else if (checkFormulaString && !checkFormulaId) {
- sheetFormulaDataMatrix.setValue(r, c, {
- f: formulaString,
- });
- } else if (!checkFormulaString && checkFormulaId) {
- sheetFormulaDataMatrix.setValue(r, c, {
- f: '',
- si: formulaId,
- });
- }
- });
-
const sheetId = worksheet.getSheetId();
- this._formulaData[unitId][sheetId] = sheetFormulaDataMatrix.getData();
+
+ initSheetFormulaData(this._formulaData, unitId, sheetId, cellMatrix);
});
}
@@ -329,30 +308,32 @@ export class FormulaDataModel extends Disposable {
// Convert the formula ID to formula string
sheetFormulaDataMatrix.forValue((r, c, cell) => {
+ const formulaString = cell?.f || '';
const formulaId = cell?.si || '';
if (isFormulaId(formulaId)) {
const formulaInfo = formulaIdMap.get(formulaId);
const deleteFormula = deleteFormulaIdMap.get(formulaId);
- if (formulaInfo) {
+
+ if (formulaInfo && !isFormulaString(formulaString)) {
const f = formulaInfo.f;
const x = c - formulaInfo.c;
const y = r - formulaInfo.r;
-
sheetFormulaDataMatrix.setValue(r, c, { f, si: formulaId, x, y });
} else if (typeof deleteFormula === 'string') {
+ const x = cell.x || 0;
+ const y = cell.y || 0;
+ const offsetFormula = this._formulaEngineService.moveFormulaRefOffset(deleteFormula, x, y);
deleteFormulaIdMap.set(formulaId, {
r,
c,
- f: deleteFormula,
+ f: offsetFormula,
});
- sheetFormulaDataMatrix.setValue(r, c, { f: deleteFormula, si: formulaId });
+ sheetFormulaDataMatrix.setValue(r, c, { f: offsetFormula, si: formulaId });
} else if (typeof deleteFormula === 'object') {
const x = c - deleteFormula.c;
const y = r - deleteFormula.r;
- // TODO@Dushusir: Calculate the new formula based on the offset
- // let f = '';
sheetFormulaDataMatrix.setValue(r, c, {
f: deleteFormula.f,
si: formulaId,
@@ -364,3 +345,55 @@ export class FormulaDataModel extends Disposable {
});
}
}
+
+export function initSheetFormulaData(
+ formulaData: IFormulaData,
+ unitId: string,
+ sheetId: string,
+ cellMatrix: ObjectMatrix<ICellData>
+) {
+ const formulaIdMap = new Map<string, { f: string; r: number; c: number }>(); // Connect the formula and ID
+ const sheetFormulaDataMatrix = new ObjectMatrix<IFormulaDataItem>();
+ cellMatrix.forValue((r, c, cell) => {
+ const formulaString = cell?.f || '';
+ const formulaId = cell?.si || '';
+
+ const checkFormulaString = isFormulaString(formulaString);
+ const checkFormulaId = isFormulaId(formulaId);
+
+ if (checkFormulaString && checkFormulaId) {
+ sheetFormulaDataMatrix.setValue(r, c, {
+ f: formulaString,
+ si: formulaId,
+ });
+ formulaIdMap.set(formulaId, { f: formulaString, r, c });
+ } else if (checkFormulaString && !checkFormulaId) {
+ sheetFormulaDataMatrix.setValue(r, c, {
+ f: formulaString,
+ });
+ } else if (!checkFormulaString && checkFormulaId) {
+ sheetFormulaDataMatrix.setValue(r, c, {
+ f: '',
+ si: formulaId,
+ });
+ }
+ });
+
+ sheetFormulaDataMatrix.forValue((r, c, cell) => {
+ const formulaString = cell?.f || '';
+ const formulaId = cell?.si || '';
+
+ if (isFormulaId(formulaId) && !isFormulaString(formulaString)) {
+ const formulaInfo = formulaIdMap.get(formulaId);
+ if (formulaInfo) {
+ const f = formulaInfo.f;
+ const x = c - formulaInfo.c;
+ const y = r - formulaInfo.r;
+
+ sheetFormulaDataMatrix.setValue(r, c, { f, si: formulaId, x, y });
+ }
+ }
+ });
+
+ formulaData[unitId][sheetId] = sheetFormulaDataMatrix.getData();
+}
diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.ts
index f59d8b4ed0..ff6111b127 100644
--- a/packages/engine-formula/src/plugin.ts
+++ b/packages/engine-formula/src/plugin.ts
@@ -31,7 +31,7 @@ export class BaseFormulaEnginePlugin extends Plugin {
}
private _initialize() {
- this._formulaDataModel = this._injector.createInstance(FormulaDataModel);
+ // this._formulaDataModel = this._injector.createInstance(FormulaDataModel);
const dependencies: Dependency[] = [
// Services
@@ -41,7 +41,7 @@ export class BaseFormulaEnginePlugin extends Plugin {
// [IFormulaService, { useClass: FormulaService }],
// Models
- [FormulaDataModel, { useValue: this._formulaDataModel }],
+ [FormulaDataModel],
//Controllers
[FormulaController],
@@ -57,7 +57,7 @@ export class BaseFormulaEnginePlugin extends Plugin {
}
override onReady(): void {
- this._formulaDataModel?.initFormulaData();
+ this._injector.get(FormulaDataModel).initFormulaData();
if (!this._config?.notExecuteFormula) {
this._injector.get(IFormulaService).registerFunctions();
diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
index 7d639ff1f1..18eb120d09 100644
--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
@@ -10,13 +10,11 @@ import {
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import { SetRangeValuesMutation, SetStyleCommand } from '@univerjs/sheets';
-const globalObject = typeof self !== 'undefined' ? self : window;
-
@OnLifecycle(LifecycleStages.Ready, TriggerCalculationController)
export class TriggerCalculationController extends Disposable {
private _waitingCommandQueue: ICommandInfo[] = [];
- private _setTimeoutKey: number = -1;
+ private _setTimeoutKey: NodeJS.Timeout | number = -1;
private _startExecutionTime: number = 0;
@@ -68,9 +66,9 @@ export class TriggerCalculationController extends Disposable {
this._waitingCommandQueue.push(command);
- globalObject.clearTimeout(this._setTimeoutKey);
+ clearTimeout(this._setTimeoutKey);
- this._setTimeoutKey = globalObject.setTimeout(() => {
+ this._setTimeoutKey = setTimeout(() => {
this._commandService.executeCommand(
SetFormulaCalculationStartMutation.id,
{
diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.ts
index 17b435c827..1aade9fa4d 100644
--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts
@@ -1,4 +1,4 @@
-import type { ICellData, ICommandInfo, IRange, IUnitRange, Nullable } from '@univerjs/core';
+import type { ICellData, ICommandInfo, IExecutionOptions, IRange, IUnitRange, Nullable } from '@univerjs/core';
import {
deserializeRangeWithSheet,
Direction,
@@ -19,6 +19,7 @@ import {
FormulaDataModel,
FormulaEngineService,
generateStringWithSequence,
+ initSheetFormulaData,
sequenceNodeType,
SetArrayFormulaDataMutation,
SetFormulaDataMutation,
@@ -28,12 +29,14 @@ import type {
IDeleteRangeMoveUpCommandParams,
IInsertColCommandParams,
IInsertRowCommandParams,
+ IInsertSheetMutationParams,
IMoveColsCommandParams,
IMoveRangeCommandParams,
IMoveRowsCommandParams,
InsertRangeMoveDownCommandParams,
InsertRangeMoveRightCommandParams,
IRemoveRowColCommandParams,
+ IRemoveSheetMutationParams,
ISetRangeValuesMutationParams,
ISetWorksheetNameCommandParams,
} from '@univerjs/sheets';
@@ -54,11 +57,13 @@ import {
InsertRangeMoveDownCommand,
InsertRangeMoveRightCommand,
InsertRowCommand,
+ InsertSheetMutation,
MoveColsCommand,
MoveRangeCommand,
MoveRowsCommand,
RemoveColCommand,
RemoveRowCommand,
+ RemoveSheetMutation,
runRefRangeMutations,
SelectionManagerService,
SetRangeValuesMutation,
@@ -136,32 +141,81 @@ export class UpdateFormulaController extends Disposable {
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo, options) => {
- // Synchronous data from worker
- if (command.id === SetRangeValuesMutation.id) {
- const params = command.params as ISetRangeValuesMutationParams;
+ const { id, params } = command;
+ if (!params) return;
+
+ switch (id) {
+ case SetRangeValuesMutation.id:
+ this._handleSetRangeValuesMutation(params as ISetRangeValuesMutationParams, options);
+ break;
+ case RemoveSheetMutation.id:
+ this._handleRemoveSheetMutation(params as IRemoveSheetMutationParams);
+ break;
+ case InsertSheetMutation.id:
+ this._handleInsertSheetMutation(params as IInsertSheetMutationParams);
+ break;
+
+ default:
+ break;
+ }
+ })
+ );
+ }
- const { worksheetId: sheetId, workbookId: unitId, cellValue } = params;
+ private _handleSetRangeValuesMutation(params: ISetRangeValuesMutationParams, options?: IExecutionOptions) {
+ const { worksheetId: sheetId, workbookId: unitId, cellValue } = params;
- if ((options && options.local === true) || cellValue == null) {
- return;
- }
+ if ((options && options.local === true) || cellValue == null) {
+ return;
+ }
- this._formulaDataModel.updateFormulaData(unitId, sheetId, cellValue);
+ this._formulaDataModel.updateFormulaData(unitId, sheetId, cellValue);
- this._commandService.executeCommand(
- SetFormulaDataMutation.id,
- {
- formulaData: this._formulaDataModel.getFormulaData(),
- },
- {
- local: true,
- }
- );
- }
- })
+ this._commandService.executeCommand(
+ SetFormulaDataMutation.id,
+ {
+ formulaData: this._formulaDataModel.getFormulaData(),
+ },
+ {
+ local: true,
+ }
);
}
+ private _handleRemoveSheetMutation(params: IRemoveSheetMutationParams) {
+ const { worksheetId: sheetId, workbookId: unitId } = params;
+
+ const formulaData = this._formulaDataModel.getFormulaData();
+ delete formulaData[unitId][sheetId];
+
+ const arrayFormulaRange = this._formulaDataModel.getArrayFormulaRange();
+ delete arrayFormulaRange[unitId][sheetId];
+
+ const arrayFormulaCellData = this._formulaDataModel.getArrayFormulaCellData();
+ delete arrayFormulaCellData[unitId][sheetId];
+
+ this._commandService.executeCommand(SetFormulaDataMutation.id, {
+ formulaData,
+ });
+ this._commandService.executeCommand(SetArrayFormulaDataMutation.id, {
+ arrayFormulaRange,
+ arrayFormulaCellData,
+ });
+ }
+
+ private _handleInsertSheetMutation(params: IInsertSheetMutationParams) {
+ const { sheet, workbookId: unitId } = params;
+
+ const formulaData = this._formulaDataModel.getFormulaData();
+ const { id: sheetId, cellData } = sheet;
+ const cellMatrix = new ObjectMatrix(cellData);
+ initSheetFormulaData(formulaData, unitId, sheetId, cellMatrix);
+
+ this._commandService.executeCommand(SetFormulaDataMutation.id, {
+ formulaData,
+ });
+ }
+
private _getUpdateFormula(command: ICommandInfo) {
const { id } = command;
let result: Nullable<IFormulaReferenceMoveParam> = null;
@@ -247,6 +301,11 @@ export class UpdateFormulaController extends Disposable {
oldFormulaData = offsetFormula(oldFormulaData, command, unitId, sheetId, selections);
const offsetFormulaData = offsetFormula(formulaData, command, unitId, sheetId, selections);
+ // Synchronous to the worker thread
+ this._commandService.executeCommand(SetFormulaDataMutation.id, {
+ formulaData: this._formulaDataModel.getFormulaData(),
+ });
+
return this._getUpdateFormulaMutations(oldFormulaData, offsetFormulaData);
}
@@ -563,6 +622,8 @@ export class UpdateFormulaController extends Disposable {
const newFormulaDataItem = new ObjectMatrix<IFormulaDataItem>();
matrixData.forValue((row, column, formulaDataItem) => {
+ if (!formulaDataItem) return true;
+
const { f: formulaString, x, y, si } = formulaDataItem;
const sequenceNodes = this._formulaEngineService.buildSequenceNodes(formulaString);
diff --git a/packages/sheets-ui/src/commands/commands/add-worksheet-merge.command.ts b/packages/sheets-ui/src/commands/commands/add-worksheet-merge.command.ts
index 9e144ed76e..e4e642d15f 100644
--- a/packages/sheets-ui/src/commands/commands/add-worksheet-merge.command.ts
+++ b/packages/sheets-ui/src/commands/commands/add-worksheet-merge.command.ts
@@ -1,8 +1,7 @@
-import type { ICommand, IMutationInfo, IRange, Worksheet } from '@univerjs/core';
+import type { ICellData, ICommand, IMutationInfo, IRange, Worksheet } from '@univerjs/core';
import {
CommandType,
Dimension,
- ICellData,
ICommandService,
IUndoRedoService,
IUniverInstanceService,