Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(formula): update formula id (#3339)
Dushusir1434966620e4
diff --git a/packages/engine-formula/src/controller/set-dependency.controller.ts b/packages/engine-formula/src/controller/set-dependency.controller.tsindex 7ea41fd019..3001e42cff 100644--- a/packages/engine-formula/src/controller/set-dependency.controller.ts+++ b/packages/engine-formula/src/controller/set-dependency.controller.ts@@ -99,12 +99,26 @@ export class SetDependencyController extends Disposable {} else if (command.id === SetFormulaDataMutation.id) {const formulaData = (command.params as ISetFormulaDataMutationParams).formulaData;Object.keys(formulaData).forEach((unitId) => {- if (formulaData[unitId] == null) {- return true;+ const unitFormulaData = formulaData[unitId];+ // undefined means do nothing+ if (unitFormulaData === undefined) {+ return;}- Object.keys(formulaData[unitId]!).forEach((subUnitId) => {- const formulaDataItem = formulaData[unitId]![subUnitId];- if (formulaDataItem == null) {++ // null means clear all formula data with the unitId+ if (unitFormulaData === null) {+ this._dependencyManagerService.clearFormulaDependency(unitId);+ return;+ }++ Object.keys(unitFormulaData).forEach((subUnitId) => {+ const formulaDataItem = unitFormulaData[subUnitId];++ if (formulaDataItem === undefined) {+ return;+ }++ if (formulaDataItem === null) {this._dependencyManagerService.clearFormulaDependency(unitId, subUnitId);return true;}diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex 12d8ef83fd..94f25ddaf6 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -53,6 +53,13 @@ export class FormulaDataModel extends Disposable {this.initFormulaData();}+ override dispose() {+ super.dispose();+ this._formulaData = {};+ this._arrayFormulaRange = {};+ this._arrayFormulaCellData = {};+ }+clearPreviousArrayFormulaCellData(clearArrayFormulaCellData: IRuntimeUnitDataType) {Object.keys(clearArrayFormulaCellData).forEach((unitId) => {const clearSheetData = clearArrayFormulaCellData[unitId];diff --git a/packages/engine-formula/src/models/utils/formula-data-util.ts b/packages/engine-formula/src/models/utils/formula-data-util.tsindex 6489e973b5..3f58e14ea1 100644--- a/packages/engine-formula/src/models/utils/formula-data-util.ts+++ b/packages/engine-formula/src/models/utils/formula-data-util.ts@@ -24,6 +24,7 @@ export interface IFormulaIdMap {c: number;}+// eslint-disable-next-line complexityexport function updateFormulaDataByCellValue(sheetFormulaDataMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>, newSheetFormulaDataMatrix: ObjectMatrix<IFormulaDataItem | null>, formulaIdMap: Map<string, IFormulaIdMap>, deleteFormulaIdMap: Map<string, string | IFormulaIdMap>, r: number, c: number, cell: Nullable<ICellData>) {const formulaString = cell?.f || '';const formulaId = cell?.si || '';@@ -31,7 +32,31 @@ export function updateFormulaDataByCellValue(sheetFormulaDataMatrix: ObjectMatriconst checkFormulaString = isFormulaString(formulaString);const checkFormulaId = isFormulaId(formulaId);+ const currentFormulaInfo = sheetFormulaDataMatrix.getValue(r, c);+ const f = currentFormulaInfo?.f || '';+ const si = currentFormulaInfo?.si || '';++ // Any data update may destroy the original correspondence between f and si, and the relationship between f and si needs to be re-bound.+ function clearFormulaData() {+ // The id that needs to be offset+ // When the cell containing the formulas f and si is deleted, f and si lose their association, and f needs to be moved to the next cell containing the same si.+ if (isFormulaString(f) && isFormulaId(si)) {+ const updatedFormula = formulaIdMap.get(si)?.f;++ // The formula may have been updated. For example, when you delete a column referenced by a formula, it will become #REF and cannot take the original value.+ if (updatedFormula) {+ deleteFormulaIdMap.set(si, updatedFormula);+ } else {+ deleteFormulaIdMap.set(si, f);+ }+ }+ }+if (checkFormulaString && checkFormulaId) {+ if (si !== formulaId) {+ clearFormulaData();+ }+sheetFormulaDataMatrix.setValue(r, c, {f: formulaString,si: formulaId,@@ -44,6 +69,10 @@ export function updateFormulaDataByCellValue(sheetFormulaDataMatrix: ObjectMatrisi: formulaId,});} else if (checkFormulaString && !checkFormulaId) {+ if (f !== formulaString) {+ clearFormulaData();+ }+sheetFormulaDataMatrix.setValue(r, c, {f: formulaString,});@@ -51,27 +80,15 @@ export function updateFormulaDataByCellValue(sheetFormulaDataMatrix: ObjectMatrif: formulaString,});} else if (!checkFormulaString && checkFormulaId) {+ if (si !== formulaId) {+ clearFormulaData();+ }sheetFormulaDataMatrix.setValue(r, c, {f: '',si: formulaId,});} else if (!checkFormulaString && !checkFormulaId && sheetFormulaDataMatrix.getValue(r, c)) {- const currentFormulaInfo = sheetFormulaDataMatrix.getValue(r, c);- const f = currentFormulaInfo?.f || '';- const si = currentFormulaInfo?.si || '';-- // The id that needs to be offset- // When the cell containing the formulas f and si is deleted, f and si lose their association, and f needs to be moved to the next cell containing the same si.- if (isFormulaString(f) && isFormulaId(si)) {- const updatedFormula = formulaIdMap.get(si)?.f;-- // The formula may have been updated. For example, when you delete a column referenced by a formula, it will become #REF and cannot take the original value.- if (updatedFormula) {- deleteFormulaIdMap.set(si, updatedFormula);- } else {- deleteFormulaIdMap.set(si, f);- }- }+ clearFormulaData();sheetFormulaDataMatrix.realDeleteValue(r, c);newSheetFormulaDataMatrix.setValue(r, c, null);diff --git a/packages/engine-formula/src/services/dependency-manager.service.ts b/packages/engine-formula/src/services/dependency-manager.service.tsindex e51e7e9a84..41cb57e67f 100644--- a/packages/engine-formula/src/services/dependency-manager.service.ts+++ b/packages/engine-formula/src/services/dependency-manager.service.ts@@ -62,7 +62,7 @@ export interface IDependencyManagerService {hasFormulaDependency(unitId: string, sheetId: string, row: number, column: number): boolean;- clearFormulaDependency(unitId: string, sheetId: string): void;+ clearFormulaDependency(unitId: string, sheetId?: string): void;}/**@@ -303,9 +303,11 @@ export class DependencyManagerService extends Disposable implements IDependencyM}}- clearFormulaDependency(unitId: string, sheetId: string) {- if (this._formulaData[unitId] && this._formulaData[unitId]![sheetId]) {+ clearFormulaDependency(unitId: string, sheetId?: string) {+ if (sheetId && this._formulaData[unitId] && this._formulaData[unitId]![sheetId]) {this._formulaData[unitId]![sheetId].reset();+ } else if (this._formulaData[unitId]) {+ this._formulaData[unitId] = null;}}diff --git a/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.tsindex ab54855887..ac605bcdfa 100644--- a/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts+++ b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts@@ -18,7 +18,7 @@ import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';import { ILogService, Inject, Injector, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';import { CalculateFormulaService, DefinedNamesService, FormulaCurrentConfigService, FormulaDataModel, FormulaRuntimeService, IDefinedNamesService, IFormulaCurrentConfigService, IFormulaRuntimeService, LexerTreeBuilder } from '@univerjs/engine-formula';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';-import { IRefSelectionsService, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';+import { IRefSelectionsService, RangeProtectionRuleModel, SheetInterceptorService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';import { EditorBridgeService, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { EditorService, IEditorService } from '@univerjs/ui';@@ -77,6 +77,11 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?override onStarting(): void {const injector = this._injector;+ injector.add([WorksheetPermissionService]);+ injector.add([WorksheetProtectionPointModel]);+ injector.add([RangeProtectionRuleModel]);+ injector.add([WorkbookPermissionService]);+ injector.add([WorksheetProtectionRuleModel]);injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);injector.add([CalculateFormulaService]);diff --git a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.tsindex 51c507ca91..d8405f6d18 100644--- a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts@@ -26,7 +26,6 @@ import {import {AddWorksheetMergeMutation,RangeProtectionRenderModel,- RangeProtectionRuleModel,RangeProtectionService,RemoveWorksheetMergeMutation,SetRangeValuesMutation,@@ -78,7 +77,6 @@ describe('Test auto fill with formula', () => {[IShortcutService, { useClass: ShortcutService }],[IPlatformService, { useClass: PlatformService }],[FormulaAutoFillController],- [RangeProtectionRuleModel],[RangeProtectionService],[RangeProtectionRenderModel],[SheetsRenderService, { useClass: mockSheetsRenderService }],diff --git a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.tsindex c7f881b5a2..5cc73c2d3c 100644--- a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts@@ -16,8 +16,8 @@import type { ICellData, Injector, IObjectMatrixPrimitiveType, IWorkbookData, Nullable, Univer } from '@univerjs/core';import { CellValueType, Direction, ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';-import type { IDeleteRangeMoveLeftCommandParams, IDeleteRangeMoveUpCommandParams, IInsertColCommandParams, IInsertRowCommandParams, IMoveColsCommandParams, IMoveRangeCommandParams, IMoveRowsCommandParams, InsertRangeMoveDownCommandParams, InsertRangeMoveRightCommandParams, IRemoveRowColCommandParams, IRemoveSheetCommandParams, ISetWorksheetNameCommandParams } from '@univerjs/sheets';-import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, InsertColCommand, InsertColMutation, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, InsertRowMutation, MoveColsCommand, MoveColsMutation, MoveRangeCommand, MoveRangeMutation, MoveRowsCommand, MoveRowsMutation, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, RemoveSheetMutation, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetNameCommand, SetWorksheetNameMutation, SheetsSelectionsService } from '@univerjs/sheets';+import type { IDeleteRangeMoveLeftCommandParams, IDeleteRangeMoveUpCommandParams, IInsertColCommandParams, IInsertRowCommandParams, IMoveColsCommandParams, IMoveRangeCommandParams, IMoveRowsCommandParams, InsertRangeMoveDownCommandParams, InsertRangeMoveRightCommandParams, IRemoveRowColCommandParams, IRemoveSheetCommandParams, ISetRangeValuesCommandParams, ISetWorksheetNameCommandParams } from '@univerjs/sheets';+import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, InsertColCommand, InsertColMutation, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, InsertRowMutation, MoveColsCommand, MoveColsMutation, MoveRangeCommand, MoveRangeMutation, MoveRowsCommand, MoveRowsMutation, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, RemoveSheetMutation, SetRangeValuesCommand, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetNameCommand, SetWorksheetNameMutation, SheetsSelectionsService } from '@univerjs/sheets';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { SetArrayFormulaDataMutation, SetFormulaDataMutation } from '@univerjs/engine-formula';@@ -96,7 +96,7 @@ const TEST_WORKBOOK_DATA_DEMO = (): IWorkbookData => ({si: 'CarNau',},9: {- f: 'CarNau',+ si: 'CarNau',},},8: {@@ -129,7 +129,7 @@ const TEST_WORKBOOK_DATA_DEMO = (): IWorkbookData => ({si: 'y0gLJX',},9: {- f: 'y0gLJX',+ si: 'y0gLJX',},},9: {@@ -161,7 +161,7 @@ const TEST_WORKBOOK_DATA_DEMO = (): IWorkbookData => ({si: 'y0gLJX',},9: {- f: 'y0gLJX',+ si: 'y0gLJX',},},10: {@@ -322,6 +322,7 @@ describe('Test insert function operation', () => {commandService.registerCommand(RemoveSheetMutation);commandService.registerCommand(SetSelectionsOperation);+ commandService.registerCommand(SetRangeValuesCommand);commandService.registerCommand(SetRangeValuesMutation);commandService.registerCommand(SetFormulaDataMutation);commandService.registerCommand(SetArrayFormulaDataMutation);@@ -1321,5 +1322,115 @@ describe('Test insert function operation', () => {const values = getValues(14, 2, 14, 2);expect(values).toStrictEqual([[{ f: '=#REF!' }]]);});++ it('set range values, set new formula string and formula id', async () => {+ const params: ISetRangeValuesCommandParams = {+ range: {+ startRow: 7,+ startColumn: 8,+ endRow: 7,+ endColumn: 8,+ },+ value: {+ f: '=A1',+ si: 'qwerty',+ },+ };++ expect(await commandService.executeCommand(SetRangeValuesCommand.id, params)).toBeTruthy();+ const values = getValues(7, 8, 7, 9);+ expect(values).toStrictEqual([[{ f: '=A1', si: 'qwerty' }, { f: '=SUM(C8:E10)', si: 'CarNau' }]]);+ });+ it('set range values, set same formula string and formula id', async () => {+ const params: ISetRangeValuesCommandParams = {+ range: {+ startRow: 7,+ startColumn: 8,+ endRow: 7,+ endColumn: 8,+ },+ value: {+ f: '=SUM(B8:D10)',+ si: 'CarNau',+ },+ };++ expect(await commandService.executeCommand(SetRangeValuesCommand.id, params)).toBeTruthy();+ const values = getValues(7, 8, 7, 9);+ expect(values).toStrictEqual([[{ f: '=SUM(B8:D10)', si: 'CarNau' }, { si: 'CarNau' }]]);+ });+ it('set range values, set same formula id', async () => {+ const params: ISetRangeValuesCommandParams = {+ range: {+ startRow: 7,+ startColumn: 9,+ endRow: 7,+ endColumn: 9,+ },+ value: {+ si: 'CarNau',+ },+ };++ expect(await commandService.executeCommand(SetRangeValuesCommand.id, params)).toBeTruthy();+ const values = getValues(7, 8, 7, 9);+ expect(values).toStrictEqual([[{ f: '=SUM(B8:D10)', si: 'CarNau' }, { si: 'CarNau' }]]);+ });+ it('set range values, set new formula string', async () => {+ const params: ISetRangeValuesCommandParams = {+ range: {+ startRow: 7,+ startColumn: 8,+ endRow: 7,+ endColumn: 8,+ },+ value: {+ f: '=A1',+ si: null,+ },+ };++ expect(await commandService.executeCommand(SetRangeValuesCommand.id, params)).toBeTruthy();+ const values = getValues(7, 8, 7, 9);+ expect(values).toStrictEqual([[{ f: '=A1' }, { f: '=SUM(C8:E10)', si: 'CarNau' }]]);+ });++ it('set range values, set new formula id', async () => {+ const params: ISetRangeValuesCommandParams = {+ range: {+ startRow: 7,+ startColumn: 8,+ endRow: 7,+ endColumn: 8,+ },+ value: {+ f: null,+ si: 'y0gLJX',+ },+ };++ expect(await commandService.executeCommand(SetRangeValuesCommand.id, params)).toBeTruthy();+ const values = getValues(7, 8, 7, 9);+ expect(values).toStrictEqual([[{ si: 'y0gLJX' }, { f: '=SUM(C8:E10)', si: 'CarNau' }]]);+ });++ it('set range values, remove formula string and id', async () => {+ const params: ISetRangeValuesCommandParams = {+ range: {+ startRow: 7,+ startColumn: 8,+ endRow: 7,+ endColumn: 8,+ },+ value: {+ f: null,+ si: null,+ },+ };++ expect(await commandService.executeCommand(SetRangeValuesCommand.id, params)).toBeTruthy();+ const values = getValues(7, 8, 7, 9);+ expect(values).toStrictEqual([[{ }, { f: '=SUM(C8:E10)', si: 'CarNau' }]]);+ });});});diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.tsindex 5fd4b2265d..acf1943cb9 100644--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts@@ -50,6 +50,7 @@ import { deserializeRangeWithSheet,sequenceNodeType,serializeRangeToRefString,SetArrayFormulaDataMutation,+ SetFormulaCalculationStartMutation,SetFormulaDataMutation,} from '@univerjs/engine-formula';@@ -109,7 +110,7 @@ import {import { filter, map, merge } from 'rxjs';import { IEditorService } from '@univerjs/ui';import { removeFormulaData } from './utils/offset-formula-data';-import { getFormulaReferenceMoveUndoRedo } from './utils/ref-range-formula';+import { formulaDataToCellData, getFormulaReferenceMoveUndoRedo } from './utils/ref-range-formula';interface IUnitRangeWithOffset extends IUnitRange {refOffsetX: number;@@ -255,6 +256,20 @@ export class UpdateFormulaController extends Disposable {},};+ // update core snapshot+ this._commandService.executeCommand(+ SetRangeValuesMutation.id,+ {+ unitId,+ subUnitId: sheetId,+ cellValue: formulaDataToCellData(newSheetFormulaData),+ },+ {+ onlyLocal: true,+ }+ );++ // update formula modelthis._formulaDataModel.updateArrayFormulaCellData(unitId, sheetId, cellValue);this._formulaDataModel.updateArrayFormulaRange(unitId, sheetId, cellValue);@@ -369,6 +384,18 @@ export class UpdateFormulaController extends Disposable {onlyLocal: true,});++ // start calculation+ this._commandService.executeCommand(+ SetFormulaCalculationStartMutation.id,+ {+ commands: [],+ forceCalculation: true,+ },+ {+ onlyLocal: true,+ }+ );}private _getUpdateFormula(command: ICommandInfo) {diff --git a/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-formula.spec.ts b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-formula.spec.tsindex 19783e120d..37c07d08c2 100644--- a/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-formula.spec.ts+++ b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-formula.spec.ts@@ -17,7 +17,7 @@import { describe, expect, it } from 'vitest';import type { IFormulaDataItem } from '@univerjs/engine-formula';-import { formulaDataItemToCellData, isFormulaDataItem } from '../ref-range-formula';+import { formulaDataItemToCellData, formulaDataToCellData, isFormulaDataItem } from '../ref-range-formula';describe('Ref range formula test', () => {describe('Util function', () => {@@ -97,6 +97,44 @@ describe('Ref range formula test', () => {expect(result).toStrictEqual({ f: null, si: null });});+ it('Function formulaDataToCellData', () => {+ const formulaData = {+ 0: {+ 0: {+ f: '=SUM(1)',+ },+ 1: {+ f: '',+ si: 'id1',+ },+ 2: {+ f: '=SUM(1)',+ si: 'id2',+ x: 0,+ y: 1,+ },+ },+ };++ const cellData = {+ 0: {+ 0: {+ f: '=SUM(1)',+ si: null,+ },+ 1: {+ f: null,+ si: 'id1',+ },+ 2: {+ f: null,+ si: 'id2',+ },+ },+ };+ expect(formulaDataToCellData(formulaData)).toStrictEqual(cellData);+ });+it('isFormulaDataItem', () => {expect(isFormulaDataItem({ f: '=SUM(1)' })).toBeTruthy();expect(isFormulaDataItem({ f: '' })).toBeFalsy();diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts b/packages/sheets-formula/src/controllers/utils/ref-range-formula.tsindex f73785bc87..6a71153a9e 100644--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts@@ -549,6 +549,24 @@ export function formulaDataItemToCellData(formulaDataItem: Nullable<IFormulaDatareturn cellData;}+/**+ * Convert formulaData to cellData+ * @param formulaData+ * @returns+ */+export function formulaDataToCellData(formulaData: IObjectMatrixPrimitiveType<IFormulaDataItem | null>+): IObjectMatrixPrimitiveType<Nullable<ICellData>> {+ const cellData = new ObjectMatrix<Nullable<ICellData>>({});+ const formulaDataMatrix = new ObjectMatrix(formulaData);++ formulaDataMatrix.forValue((r, c, formulaDataItem) => {+ const cellDataItem = formulaDataItemToCellData(formulaDataItem);+ cellData.setValue(r, c, cellDataItem);+ });++ return cellData.clone();+}+export function isFormulaDataItem(cell: IFormulaDataItem) {const formulaString = cell?.f || '';const formulaId = cell?.si || '';@@ -562,3 +580,4 @@ export function isFormulaDataItem(cell: IFormulaDataItem) {return false;}+