Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(formula): update formula (#555)

Dushusir5fc670d92e33
diff --git a/packages/base-formula-engine/src/basics/common.ts b/packages/base-formula-engine/src/basics/common.ts
index 6508076957..5ed3c27a5d 100644
--- a/packages/base-formula-engine/src/basics/common.ts
+++ b/packages/base-formula-engine/src/basics/common.ts
@@ -60,7 +60,7 @@ export interface IFormulaDataItem {
f: string; // formulaString
x?: number; // Offset from x direction
y?: number; // Offset from y direction
- // si: string; // formulaId,
+ si?: string; // formulaId,
// row: number;
// column: number;
// sheetId: string;
diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.ts
index 77aa6e3c79..69f27630ca 100644
--- a/packages/base-sheets/src/index.ts
+++ b/packages/base-sheets/src/index.ts
@@ -54,6 +54,7 @@ export { ClearSelectionContentCommand } from './commands/commands/clear-selectio
export { ClearSelectionFormatCommand } from './commands/commands/clear-selection-format.command';
export { CopySheetCommand } from './commands/commands/copy-worksheet.command';
export { DeleteRangeMoveLeftCommand } from './commands/commands/delete-range-move-left.command';
+export { type DeleteRangeMoveLeftCommandParams } from './commands/commands/delete-range-move-left.command';
export { DeleteRangeMoveUpCommand } from './commands/commands/delete-range-move-up.command';
export { InsertRangeMoveDownCommand } from './commands/commands/insert-range-move-down.command';
export { InsertRangeMoveRightCommand } from './commands/commands/insert-range-move-right.command';
@@ -150,6 +151,8 @@ export {
AddMergeUndoMutationFactory,
AddWorksheetMergeMutation,
} from './commands/mutations/add-worksheet-merge.mutation';
+export { DeleteRangeMutation } from './commands/mutations/delete-range.mutation';
+export { InsertRangeMutation } from './commands/mutations/insert-range.mutation';
export {
InsertColMutation,
InsertColMutationUndoFactory,
@@ -157,7 +160,11 @@ export {
InsertRowMutationUndoFactory,
} from './commands/mutations/insert-row-col.mutation';
export { InsertSheetMutation, InsertSheetUndoMutationFactory } from './commands/mutations/insert-sheet.mutation';
-export { MoveRowsMutation } from './commands/mutations/move-rows-cols.mutation';
+export { MoveRangeMutation } from './commands/mutations/move-range.mutation';
+export { type MoveRangeMutationParams } from './commands/mutations/move-range.mutation';
+export { type IMoveColumnsMutationParams } from './commands/mutations/move-rows-cols.mutation';
+export { type IMoveRowsMutationParams, MoveRowsMutation } from './commands/mutations/move-rows-cols.mutation';
+export { MoveColsMutation } from './commands/mutations/move-rows-cols.mutation';
export { RemoveColMutation, RemoveRowMutation } from './commands/mutations/remove-row-col.mutation';
export { RemoveSheetMutation, RemoveSheetUndoMutationFactory } from './commands/mutations/remove-sheet.mutation';
export { RemoveWorksheetMergeMutation } from './commands/mutations/remove-worksheet-merge.mutation';
diff --git a/packages/common-plugin-data/src/sheets/demo/default-workbook-data-demo.ts b/packages/common-plugin-data/src/sheets/demo/default-workbook-data-demo.ts
index 662b90876e..95053623e1 100644
--- a/packages/common-plugin-data/src/sheets/demo/default-workbook-data-demo.ts
+++ b/packages/common-plugin-data/src/sheets/demo/default-workbook-data-demo.ts
@@ -24168,6 +24168,7 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
v: 2,
m: '2',
f: '=SUM(A1)',
+ si: '3e4r5t',
},
},
1: {
diff --git a/packages/core/src/types/enum/dimension.ts b/packages/core/src/types/enum/dimension.ts
index 36db6b1b12..911a87097e 100644
--- a/packages/core/src/types/enum/dimension.ts
+++ b/packages/core/src/types/enum/dimension.ts
@@ -5,11 +5,11 @@
*/
export enum Dimension {
/**
- * The column (vertical) dimension.
+ * The column (vertical) dimension. move left or right
*/
COLUMNS,
/**
- * The row (horizontal) dimension.
+ * The row (horizontal) dimension. move up or down
*/
ROWS,
}
diff --git a/packages/sheets-plugin-formula-ui/src/commands/commands/insert-function.command.ts b/packages/sheets-plugin-formula-ui/src/commands/commands/insert-function.command.ts
index 4f52af43a9..a8784a89b4 100644
--- a/packages/sheets-plugin-formula-ui/src/commands/commands/insert-function.command.ts
+++ b/packages/sheets-plugin-formula-ui/src/commands/commands/insert-function.command.ts
@@ -2,7 +2,7 @@ import { ISetRangeValuesCommandParams, SetRangeValuesCommand } from '@univerjs/b
import { CommandType, ICellData, ICommand, ICommandService, IRange, ObjectMatrix, Tools } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
-interface IInsertFunction {
+export interface IInsertFunction {
/**
* The range into which the function is to be inserted
*/
@@ -28,7 +28,7 @@ export interface IInsertFunctionCommandParams {
export const InsertFunctionCommand: ICommand = {
id: 'formula-ui.command.insert-function',
- type: CommandType.OPERATION,
+ type: CommandType.COMMAND,
handler: async (accessor: IAccessor, params: IInsertFunctionCommandParams) => {
const { list } = params;
const commandService = accessor.get(ICommandService);
diff --git a/packages/sheets-plugin-formula-ui/src/commands/operations/__tests__/create-command-test-bed.ts b/packages/sheets-plugin-formula-ui/src/commands/operations/__tests__/create-command-test-bed.ts
new file mode 100644
index 0000000000..f60d586326
--- /dev/null
+++ b/packages/sheets-plugin-formula-ui/src/commands/operations/__tests__/create-command-test-bed.ts
@@ -0,0 +1,89 @@
+import { FormulaEngineService } from '@univerjs/base-formula-engine';
+import { SelectionManagerService } from '@univerjs/base-sheets';
+import {
+ ILogService,
+ IUniverInstanceService,
+ IWorkbookData,
+ LocaleType,
+ Plugin,
+ PluginType,
+ Univer,
+} from '@univerjs/core';
+import { Dependency, Inject, Injector } from '@wendellhu/redi';
+
+import { FormulaInputService, IFormulaInputService } from '../../../services/formula-input.service';
+
+const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ '1': {
+ '1': {
+ v: 1,
+ },
+ },
+ },
+ },
+ },
+ 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([SelectionManagerService]);
+ injector.add([FormulaEngineService]);
+ injector.add([IFormulaInputService, { useClass: FormulaInputService }]);
+
+ dependencies?.forEach((d) => injector.add(d));
+ }
+
+ override onDestroy(): void {
+ get = undefined;
+ }
+ }
+
+ univer.registerPlugin(TestSpyPlugin);
+ const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA_DEMO);
+
+ 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/sheets-plugin-formula-ui/src/commands/operations/__tests__/insert-function.operation.spec.ts b/packages/sheets-plugin-formula-ui/src/commands/operations/__tests__/insert-function.operation.spec.ts
new file mode 100644
index 0000000000..cf5e458117
--- /dev/null
+++ b/packages/sheets-plugin-formula-ui/src/commands/operations/__tests__/insert-function.operation.spec.ts
@@ -0,0 +1,126 @@
+import {
+ NORMAL_SELECTION_PLUGIN_NAME,
+ SelectionManagerService,
+ SetRangeValuesCommand,
+ SetRangeValuesMutation,
+} from '@univerjs/base-sheets';
+import { ICellData, ICommandService, IUniverInstanceService, Nullable, RANGE_TYPE, Univer } from '@univerjs/core';
+import { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { InsertFunctionCommand } from '../../commands/insert-function.command';
+import { IInsertFunctionOperationParams, InsertFunctionOperation } from '../insert-function.operation';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('Test insert function operation', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(InsertFunctionOperation);
+ commandService.registerCommand(InsertFunctionCommand);
+ commandService.registerCommand(SetRangeValuesCommand);
+ commandService.registerCommand(SetRangeValuesMutation);
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ describe('insert function', () => {
+ describe('correct situations', () => {
+ it('insert function, match the data range above', async () => {
+ const selectionManager = get(SelectionManagerService);
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+ // B3
+ selectionManager.add([
+ {
+ range: { startRow: 2, startColumn: 1, endRow: 2, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ function getValue(): Nullable<ICellData> {
+ return get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(2, 1, 2, 1)
+ .getValue();
+ }
+ const params: IInsertFunctionOperationParams = {
+ value: 'SUM',
+ };
+
+ // expect(await commandService.executeCommand(InsertFunctionOperation.id, params)).toBeTruthy();
+ // expect(getValue()?.f).toStrictEqual('=SUM(B2)');
+ // // undo
+ // expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ // expect(getValue()).toStrictEqual({});
+ // // redo
+ // expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ // expect(getValue()?.f).toStrictEqual('=SUM(B2)');
+
+ // // Restore the original data
+ // expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ });
+
+ it('insert function, match the data range left', async () => {
+ const selectionManager = get(SelectionManagerService);
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+ // C2
+ selectionManager.add([
+ {
+ range: { startRow: 1, startColumn: 2, endRow: 1, endColumn: 2, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ function getValue(): Nullable<ICellData> {
+ return get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(1, 2, 1, 2)
+ .getValue();
+ }
+ const params: IInsertFunctionOperationParams = {
+ value: 'SUM',
+ };
+
+ // expect(await commandService.executeCommand(InsertFunctionOperation.id, params)).toBeTruthy();
+ // expect(getValue()?.f).toStrictEqual('=SUM(B2)');
+ // // undo
+ // expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ // expect(getValue()).toStrictEqual({});
+ // // redo
+ // expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ // expect(getValue()?.f).toStrictEqual('=SUM(B2)');
+
+ // // Restore the original data
+ // expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ });
+ });
+
+ describe('fault situations', () => {
+ it('will not apply when there is no selected ranges', async () => {
+ const result = await commandService.executeCommand(InsertFunctionOperation.id);
+ expect(result).toBeFalsy();
+ });
+ });
+ });
+});
diff --git a/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts b/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts
index e32e539a69..3f077b9425 100644
--- a/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts
+++ b/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts
@@ -15,7 +15,7 @@ import {
import { IAccessor } from '@wendellhu/redi';
import { IFormulaInputService } from '../../services/formula-input.service';
-import { InsertFunctionCommand } from '../commands/insert-function.command';
+import { IInsertFunction, InsertFunctionCommand } from '../commands/insert-function.command';
export interface IInsertFunctionOperationParams {
/**
@@ -39,44 +39,44 @@ export const InsertFunctionOperation: ICommand = {
const cellMatrix = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getCellMatrix();
const { value } = params;
-
- // Select a single range to insert a formula:
- // 1. The entire row or column, first get the judgment result of the primary position, and then set the formula ID of other positions in sequence;
- // 2. For multiple rows and multiple columns, only get the judgment result of the primary position, and enter the edit mode
- if (currentSelections.length === 1) {
- const { startRow, endRow, startColumn, endColumn } = currentSelections[0].range;
- if (startRow !== endRow && startColumn !== endColumn) {
- // TODO@Dushusir: Enter the editing mode
- formulaInputService.inputFormula(value);
- return false;
- }
- }
-
const commandService = accessor.get(ICommandService);
+ // TODO@Dushusir: no match refRange situation, enter edit mode
+
// In each range (whether it is an entire row or column or multiple rows and columns),
// 1. First get the judgment result of the primary position, and then set the formula id of other positions;
// 2. If there is no primary range, just judge the upper left corner cell.
- const list = currentSelections.map((selection) => {
+ const list: IInsertFunction[] = [];
+ currentSelections.some((selection) => {
const { range, primary } = selection;
const row = primary?.actualRow ?? range.startRow;
const column = primary?.actualColumn ?? range.startColumn;
const refRange = findRefRange(cellMatrix, row, column);
- const rangeString = refRange ? serializeRange(refRange) : '';
+
+ if (!refRange) {
+ formulaInputService.inputFormula(value);
+ return true;
+ }
+
+ const rangeString = serializeRange(refRange);
const formulaString = `=${value}(${rangeString})`;
- return {
+ list.push({
range,
primary: {
row,
column,
},
formula: formulaString,
- };
+ });
+
+ return false;
});
+ if (list) return false;
+
return commandService.executeCommand(InsertFunctionCommand.id, {
list,
});
diff --git a/packages/sheets-plugin-formula/src/controllers/update-formula.controller.ts b/packages/sheets-plugin-formula/src/controllers/update-formula.controller.ts
new file mode 100644
index 0000000000..c33d43894b
--- /dev/null
+++ b/packages/sheets-plugin-formula/src/controllers/update-formula.controller.ts
@@ -0,0 +1,213 @@
+import { FormulaEngineService } from '@univerjs/base-formula-engine';
+import {
+ DeleteRangeMutation,
+ IDeleteRangeMutationParams,
+ IInsertRangeMutationParams,
+ IMoveColumnsMutationParams,
+ IMoveRowsMutationParams,
+ InsertColMutation,
+ InsertRangeMutation,
+ InsertRowMutation,
+ ISetRangeValuesMutationParams,
+ MoveColsMutation,
+ MoveRangeMutation,
+ MoveRangeMutationParams,
+ MoveRowsMutation,
+ RemoveColMutation,
+ RemoveRowMutation,
+ SetRangeValuesMutation,
+} from '@univerjs/base-sheets';
+import {
+ Dimension,
+ Disposable,
+ ICellData,
+ ICommandInfo,
+ ICommandService,
+ IRange,
+ IUniverInstanceService,
+ LifecycleStages,
+ Nullable,
+ ObjectMatrix,
+ ObjectMatrixPrimitiveType,
+ OnLifecycle,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+
+import { FormulaDataModel } from '../models/formula-data.model';
+
+export enum FormulaReferenceMoveType {
+ Move, // range
+ Insert, // row column
+ Remove, // row column
+ DeleteMoveLeft, // range
+ DeleteMoveUp, // range
+ InsertMoveDown, // range
+ InsertMoveRight, // range
+}
+
+export interface IFormulaReferenceMoveParam {
+ type: FormulaReferenceMoveType;
+ ranges?: IRange[];
+ from?: IRange;
+ to?: IRange;
+}
+
+@OnLifecycle(LifecycleStages.Starting, UpdateFormulaController)
+export class UpdateFormulaController extends Disposable {
+ constructor(
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize(): void {
+ this._commandExecutedListener();
+ }
+
+ private _commandExecutedListener() {
+ const updateCommandList = [
+ MoveRangeMutation.id,
+ MoveRowsMutation.id,
+ MoveColsMutation.id,
+ InsertRangeMutation.id,
+ InsertRowMutation.id,
+ InsertColMutation.id,
+ DeleteRangeMutation.id,
+ RemoveRowMutation.id,
+ RemoveColMutation.id,
+ ];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ const { id } = command;
+ let result: Nullable<IFormulaReferenceMoveParam> = null;
+
+ // TODO@Dushusir: handle cut operation, same as move operation
+ switch (id) {
+ case MoveRangeMutation.id:
+ result = this._handleMoveRange(command as ICommandInfo<MoveRangeMutationParams>);
+ break;
+ case MoveRowsMutation.id:
+ result = this._handleMoveRows(command as ICommandInfo<IMoveRowsMutationParams>);
+ break;
+ case MoveColsMutation.id:
+ result = this._handleMoveCols(command as ICommandInfo<IMoveColumnsMutationParams>);
+ break;
+ case InsertRangeMutation.id:
+ result = this._handleInsertRange(command as ICommandInfo<IInsertRangeMutationParams>);
+ break;
+ case DeleteRangeMutation.id:
+ result = this._handleDeleteRange(command as ICommandInfo<IDeleteRangeMutationParams>);
+ break;
+ }
+
+ // TODO@Dushusir: update formula and get update cell data matrix
+ // if (result) {
+ // this._updateFormula(cellValue);
+ // }
+ })
+ );
+ }
+
+ private _handleMoveRange(command: ICommandInfo<MoveRangeMutationParams>) {
+ const { params } = command;
+ if (!params) return null;
+
+ const { from, to } = params;
+ if (!from || !to) return null;
+
+ return {
+ type: FormulaReferenceMoveType.Move,
+ from: getRangeFromMatrixObject(from),
+ to: getRangeFromMatrixObject(to),
+ };
+ }
+
+ private _handleMoveRows(command: ICommandInfo<IMoveRowsMutationParams>) {
+ const { params } = command;
+ if (!params) return null;
+
+ const { sourceRange, targetRange } = params;
+ return {
+ type: FormulaReferenceMoveType.Move,
+ from: sourceRange,
+ to: targetRange,
+ };
+ }
+
+ private _handleMoveCols(command: ICommandInfo<IMoveColumnsMutationParams>) {
+ const { params } = command;
+ if (!params) return null;
+
+ const { sourceRange, targetRange } = params;
+ return {
+ type: FormulaReferenceMoveType.Move,
+ from: sourceRange,
+ to: targetRange,
+ };
+ }
+
+ private _handleInsertRange(command: ICommandInfo<IInsertRangeMutationParams>) {
+ const { params } = command;
+ if (!params) return null;
+
+ const { ranges, shiftDimension } = params;
+
+ if (shiftDimension === Dimension.ROWS) {
+ return {
+ type: FormulaReferenceMoveType.InsertMoveDown,
+ ranges,
+ };
+ }
+ if (shiftDimension === Dimension.COLUMNS) {
+ return {
+ type: FormulaReferenceMoveType.InsertMoveRight,
+ ranges,
+ };
+ }
+ }
+
+ private _handleDeleteRange(command: ICommandInfo<IDeleteRangeMutationParams>) {
+ const { params } = command;
+ if (!params) return null;
+
+ const { ranges, shiftDimension } = params;
+
+ if (shiftDimension === Dimension.ROWS) {
+ return {
+ type: FormulaReferenceMoveType.DeleteMoveUp,
+ ranges,
+ };
+ }
+ if (shiftDimension === Dimension.COLUMNS) {
+ return {
+ type: FormulaReferenceMoveType.DeleteMoveLeft,
+ ranges,
+ };
+ }
+ }
+
+ private _updateFormula(cellValue: ObjectMatrixPrimitiveType<ICellData>) {
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const workbookId = workbook.getUnitId();
+ const worksheetId = workbook.getActiveSheet().getSheetId();
+
+ const setRangeValuesMutation: ISetRangeValuesMutationParams = {
+ worksheetId,
+ workbookId,
+ cellValue,
+ };
+
+ this._commandService.executeCommand(SetRangeValuesMutation.id, setRangeValuesMutation);
+ }
+}
+
+function getRangeFromMatrixObject(matrixObject: ObjectMatrixPrimitiveType<ICellData | null>) {
+ const matrix = new ObjectMatrix(matrixObject);
+ return matrix.getDataRange();
+}
diff --git a/packages/sheets-plugin-formula/src/formula-plugin.ts b/packages/sheets-plugin-formula/src/formula-plugin.ts
index 38a9ae3a00..73aa47eaca 100644
--- a/packages/sheets-plugin-formula/src/formula-plugin.ts
+++ b/packages/sheets-plugin-formula/src/formula-plugin.ts
@@ -4,11 +4,14 @@ import { Dependency, Inject, Injector } from '@wendellhu/redi';
import { FORMULA_PLUGIN_NAME } from './common/plugin-name';
import { CalculateController } from './controllers/calculate.controller';
import { FormulaController } from './controllers/formula.controller';
+import { UpdateFormulaController } from './controllers/update-formula.controller';
import { FormulaDataModel, IFormulaConfig } from './models/formula-data.model';
export class FormulaPlugin extends Plugin {
static override type = PluginType.Sheet;
+ private _formulaDataModel: FormulaDataModel | null = null;
+
constructor(
private _config: IFormulaConfig | undefined,
@Inject(Injector) override readonly _injector: Injector
@@ -17,15 +20,17 @@ export class FormulaPlugin extends Plugin {
}
initialize(): void {
+ this._formulaDataModel = this._injector.createInstance(FormulaDataModel);
const dependencies: Dependency[] = [
// models
- [FormulaDataModel, { useFactory: () => this._injector.createInstance(FormulaDataModel, this._config) }],
+ [FormulaDataModel, { useValue: this._formulaDataModel }],
// controllers
[FormulaController],
];
if (!this._config?.notExecuteFormula) {
dependencies.push([CalculateController]);
+ dependencies.push([UpdateFormulaController]);
}
dependencies.forEach((dependency) => this._injector.add(dependency));
@@ -34,4 +39,8 @@ export class FormulaPlugin extends Plugin {
override onStarting(): void {
this.initialize();
}
+
+ override onReady(): void {
+ this._formulaDataModel?.initFormulaData();
+ }
}
diff --git a/packages/sheets-plugin-formula/src/models/formula-data.model.ts b/packages/sheets-plugin-formula/src/models/formula-data.model.ts
index fa9a8ea930..78d6d7cfc7 100644
--- a/packages/sheets-plugin-formula/src/models/formula-data.model.ts
+++ b/packages/sheets-plugin-formula/src/models/formula-data.model.ts
@@ -1,5 +1,5 @@
-import { ArrayFormulaDataType, IFormulaData } from '@univerjs/base-formula-engine';
-import { Disposable, ObjectMatrix } from '@univerjs/core';
+import { ArrayFormulaDataType, IFormulaData, IFormulaDataItem } from '@univerjs/base-formula-engine';
+import { Disposable, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
export interface IFormulaConfig {
notExecuteFormula?: boolean;
@@ -12,12 +12,8 @@ export class FormulaDataModel extends Disposable {
private _arrayFormulaData: ArrayFormulaDataType = {};
- constructor(config?: IFormulaConfig) {
+ constructor(@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService) {
super();
-
- if (config?.formulaData) {
- this._formulaData = config.formulaData;
- }
}
getFormulaData() {
@@ -43,4 +39,43 @@ export class FormulaDataModel extends Disposable {
});
});
}
+
+ initFormulaData() {
+ // load formula data from workbook config data
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const unitId = workbook.getUnitId();
+ this._formulaData[unitId] = {};
+
+ const worksheets = workbook.getSheets();
+ worksheets.forEach((worksheet) => {
+ const cellMatrix = worksheet.getCellMatrix();
+ const formulaDataMatrix = 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) {
+ formulaDataMatrix.setValue(r, c, {
+ f: formulaString,
+ si: formulaId,
+ });
+ } else if (checkFormulaString && !checkFormulaId) {
+ formulaDataMatrix.setValue(r, c, {
+ f: formulaString,
+ });
+ } else if (!checkFormulaString && checkFormulaId) {
+ formulaDataMatrix.setValue(r, c, {
+ f: '',
+ si: formulaId,
+ });
+ }
+ });
+
+ const sheetId = worksheet.getSheetId();
+ this._formulaData[unitId][sheetId] = formulaDataMatrix.getData();
+ });
+ }
}