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): reverse undo range list (#2389)
Dushusirb6ef910eb8cb
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex 1b9261374b..9fa83306b9 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -35,7 +35,7 @@ import { clearArrayFormulaCellDataByCell, updateFormulaDataByCellValue } from '.export interface IRangeChange {oldCell: IRange;- newCell: IRange;+ newCell: IRange | null;}export class FormulaDataModel extends Disposable {diff --git a/packages/engine-formula/src/models/utils/formula-data-util.ts b/packages/engine-formula/src/models/utils/formula-data-util.tsindex af4d6d45db..6489e973b5 100644--- a/packages/engine-formula/src/models/utils/formula-data-util.ts+++ b/packages/engine-formula/src/models/utils/formula-data-util.ts@@ -63,7 +63,14 @@ export function updateFormulaDataByCellValue(sheetFormulaDataMatrix: ObjectMatri// 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)) {- deleteFormulaIdMap.set(si, f);+ 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);+ }}sheetFormulaDataMatrix.realDeleteValue(r, c);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 2c6d2b61c9..6dc499669b 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@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellData, IWorkbookData, Nullable, Univer } from '@univerjs/core';+import type { ICellData, 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, NORMAL_SELECTION_PLUGIN_NAME, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, RemoveSheetMutation, SelectionManagerService, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetNameCommand, SetWorksheetNameMutation } from '@univerjs/sheets';@@ -67,6 +67,137 @@ const TEST_WORKBOOK_DATA_DEMO = (): IWorkbookData => ({t: CellValueType.NUMBER,},},+ 7: {+ 0: {+ v: 1,+ t: CellValueType.NUMBER,+ },+ 1: {+ v: 1,+ t: CellValueType.NUMBER,+ },+ 2: {+ v: 1,+ t: CellValueType.NUMBER,+ },+ 3: {+ f: '=SUM(A8)',+ },+ 4: {+ f: '=SUM(B8)',+ },+ 5: {+ f: '=SUM(C8)',+ },+ 7: {+ f: '=SUM(A8:C10)',+ },+ 8: {+ f: '=SUM(B8:D10)',+ si: 'CarNau',+ },+ 9: {+ f: 'CarNau',+ },+ },+ 8: {+ 0: {+ v: 1,+ t: CellValueType.NUMBER,+ },+ 1: {+ v: 1,+ t: CellValueType.NUMBER,+ },+ 2: {+ v: 1,+ t: CellValueType.NUMBER,+ },+ 3: {+ f: '=SUM(A9)',+ },+ 4: {+ f: '=SUM(B9)',+ },+ 5: {+ f: '=SUM(C9)',+ },+ 7: {+ f: '=SUM(A9:C11)',+ si: 'y0gLJX',+ },+ 8: {+ si: 'y0gLJX',+ },+ 9: {+ f: 'y0gLJX',+ },+ },+ 9: {+ 0: {+ v: 1,+ t: CellValueType.NUMBER,+ },+ 1: {+ v: 1,+ t: CellValueType.NUMBER,+ },+ 2: {+ v: 1,+ t: CellValueType.NUMBER,+ },+ 3: {+ f: '=SUM(A10)',+ },+ 4: {+ f: '=SUM(B10)',+ },+ 5: {+ f: '=SUM(C10)',+ },+ 7: {+ si: 'y0gLJX',+ },+ 8: {+ si: 'y0gLJX',+ },+ 9: {+ f: 'y0gLJX',+ },+ },+ 10: {+ 0: {+ f: '=SUM(A8)',+ },+ 1: {+ f: '=SUM(B8)',+ },+ 2: {+ f: '=SUM(C8)',+ },+ },+ 11: {+ 0: {+ f: '=SUM(A9)',+ },+ 1: {+ f: '=SUM(B9)',+ },+ 2: {+ f: '=SUM(C9)',+ },+ },+ 12: {+ 0: {+ f: '=SUM(A10)',+ },+ 1: {+ f: '=SUM(B10)',+ },+ 2: {+ f: '=SUM(C10)',+ },+ },14: {0: {f: '=A1:B2',@@ -101,6 +232,7 @@ describe('Test insert function operation', () => {endRow: number,endColumn: number) => Array<Array<Nullable<ICellData>>> | undefined;+ let getCellData: () => IObjectMatrixPrimitiveType<Nullable<ICellData>> | undefined;beforeEach(() => {const testBed = createCommandTestBed(TEST_WORKBOOK_DATA_DEMO(), [@@ -157,6 +289,11 @@ describe('Test insert function operation', () => {?.getSheetBySheetId('sheet1')?.getRange(startRow, startColumn, endRow, endColumn).getValues();++ getCellData = () => {+ return get(IUniverInstanceService).getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')?.getCellMatrix().clone();+ };});afterEach(() => {@@ -484,6 +621,32 @@ describe('Test insert function operation', () => {expect(valuesRedo2).toStrictEqual([[{ f: '=SUM(A1:B3)' }], [{ v: 1, t: CellValueType.NUMBER }]]);});+ it('Insert row, update reference and position, adjacent formula', async () => {+ const params: IInsertRowCommandParams = {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: {+ startRow: 8,+ endRow: 8,+ startColumn: 0,+ endColumn: 19,+ },+ direction: Direction.UP,+ };++ expect(await commandService.executeCommand(InsertRowCommand.id, params)).toBeTruthy();+ const values = getValues(10, 0, 13, 0);+ expect(values).toStrictEqual([[{ v: 1, t: CellValueType.NUMBER }], [{ f: '=SUM(A8)' }], [{ f: '=SUM(A10)' }], [{ f: '=SUM(A11)' }]]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ const valuesUndo = getValues(10, 0, 13, 0);+ expect(valuesUndo).toStrictEqual([[{ f: '=SUM(A8)' }], [{ f: '=SUM(A9)' }], [{ f: '=SUM(A10)' }], [{}]]);++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ const valuesRedo = getValues(10, 0, 13, 0);+ expect(valuesRedo).toStrictEqual([[{ v: 1, t: CellValueType.NUMBER }], [{ f: '=SUM(A8)' }], [{ f: '=SUM(A10)' }], [{ f: '=SUM(A11)' }]]);+ });+it('Insert column, update reference', async () => {const params: IInsertColCommandParams = {unitId: 'test',@@ -530,18 +693,24 @@ describe('Test insert function operation', () => {expect(values).toStrictEqual([[{ v: 1, t: CellValueType.NUMBER }, { f: '=A1:C2' }]]);const values2 = getValues(5, 3, 5, 4);expect(values2).toStrictEqual([[{ f: '=SUM(A1:C2)' }, { v: 1, t: CellValueType.NUMBER }]]);+ const values3 = getValues(7, 2, 7, 6);+ expect(values3).toStrictEqual([[{ v: 1, t: CellValueType.NUMBER }, { v: 1, t: CellValueType.NUMBER }, { f: '=SUM(A8)' }, { f: '=SUM(C8)' }, { f: '=SUM(D8)' }]]);expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();const valuesUndo = getValues(2, 1, 2, 2);expect(valuesUndo).toStrictEqual([[{ v: 1, t: CellValueType.NUMBER }, { f: '=A1:B2' }]]);const valuesUndo2 = getValues(5, 2, 5, 3);expect(valuesUndo2).toStrictEqual([[{ f: '=SUM(A1:B2)' }, { v: 1, t: CellValueType.NUMBER }]]);+ const valuesUndo3 = getValues(7, 2, 7, 6);+ expect(valuesUndo3).toStrictEqual([[{ v: 1, t: CellValueType.NUMBER }, { f: '=SUM(A8)' }, { f: '=SUM(B8)' }, { f: '=SUM(C8)' }, {}]]);expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();const valuesRedo = getValues(2, 2, 2, 3);expect(valuesRedo).toStrictEqual([[{ v: 1, t: CellValueType.NUMBER }, { f: '=A1:C2' }]]);const valuesRedo2 = getValues(5, 3, 5, 4);expect(valuesRedo2).toStrictEqual([[{ f: '=SUM(A1:C2)' }, { v: 1, t: CellValueType.NUMBER }]]);+ const valuesRedo3 = getValues(7, 2, 7, 6);+ expect(valuesRedo3).toStrictEqual([[{ v: 1, t: CellValueType.NUMBER }, { v: 1, t: CellValueType.NUMBER }, { f: '=SUM(A8)' }, { f: '=SUM(C8)' }, { f: '=SUM(D8)' }]]);});it('Remove row, update reference', async () => {@@ -596,6 +765,52 @@ describe('Test insert function operation', () => {expect(valuesRedo2).toStrictEqual([[{ f: '=SUM(A1:B1)' }], [{ v: 1, t: CellValueType.NUMBER }]]);});+ it('Remove row, update reference and position, adjacent formula', async () => {+ const params: IRemoveRowColCommandParams = {+ range: {+ startRow: 8,+ endRow: 8,+ startColumn: 0,+ endColumn: 19,+ },+ };++ expect(await commandService.executeCommand(RemoveRowCommand.id, params)).toBeTruthy();+ const values = getValues(9, 0, 12, 0);+ expect(values).toStrictEqual([[{ f: '=SUM(A8)' }], [{ f: '=SUM(#REF!)' }], [{ f: '=SUM(A9)' }], [{}]]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ const valuesUndo = getValues(9, 0, 12, 0);+ expect(valuesUndo).toStrictEqual([[{ v: 1, t: CellValueType.NUMBER }], [{ f: '=SUM(A8)' }], [{ f: '=SUM(A9)' }], [{ f: '=SUM(A10)' }]]);++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ const valuesRedo = getValues(9, 0, 12, 0);+ expect(valuesRedo).toStrictEqual([[{ f: '=SUM(A8)' }], [{ f: '=SUM(#REF!)' }], [{ f: '=SUM(A9)' }], [{}]]);+ });++ it('Remove row, removed row contains formula', async () => {+ const params: IRemoveRowColCommandParams = {+ range: {+ startRow: 10,+ endRow: 10,+ startColumn: 0,+ endColumn: 19,+ },+ };++ expect(await commandService.executeCommand(RemoveRowCommand.id, params)).toBeTruthy();+ const values = getValues(10, 0, 10, 0);+ expect(values).toStrictEqual([[{ f: '=SUM(A9)' }]]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ const valuesUndo = getValues(10, 0, 10, 0);+ expect(valuesUndo).toStrictEqual([[{ f: '=SUM(A8)' }]]);++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ const valuesRedo = getValues(10, 0, 10, 0);+ expect(valuesRedo).toStrictEqual([[{ f: '=SUM(A9)' }]]);+ });+it('Remove column, update reference', async () => {const params: IRemoveRowColCommandParams = {range: {@@ -634,18 +849,47 @@ describe('Test insert function operation', () => {expect(values).toStrictEqual([[{ f: '=A1:A2' }, {}]]);const values2 = getValues(5, 1, 5, 2);expect(values2).toStrictEqual([[{ f: '=SUM(A1:A2)' }, { v: 1, t: CellValueType.NUMBER }]]);+ const values3 = getValues(7, 2, 7, 5);+ expect(values3).toStrictEqual([[{ f: '=SUM(A8)' }, { f: '=SUM(#REF!)' }, { f: '=SUM(B8)' }, {}]]);expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();const valuesUndo = getValues(2, 1, 2, 2);expect(valuesUndo).toStrictEqual([[{ v: 1, t: CellValueType.NUMBER }, { f: '=A1:B2' }]]);const valuesUndo2 = getValues(5, 2, 5, 3);expect(valuesUndo2).toStrictEqual([[{ f: '=SUM(A1:B2)' }, { v: 1, t: CellValueType.NUMBER }]]);+ const valuesUndo3 = getValues(7, 2, 7, 5);+ expect(valuesUndo3).toStrictEqual([[{ v: 1, t: CellValueType.NUMBER }, { f: '=SUM(A8)' }, { f: '=SUM(B8)' }, { f: '=SUM(C8)' }]]);expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();const valuesRedo = getValues(2, 1, 2, 2);expect(valuesRedo).toStrictEqual([[{ f: '=A1:A2' }, {}]]);const valuesRedo2 = getValues(5, 1, 5, 2);expect(valuesRedo2).toStrictEqual([[{ f: '=SUM(A1:A2)' }, { v: 1, t: CellValueType.NUMBER }]]);+ const valuesRedo3 = getValues(7, 2, 7, 5);+ expect(valuesRedo3).toStrictEqual([[{ f: '=SUM(A8)' }, { f: '=SUM(#REF!)' }, { f: '=SUM(B8)' }, {}]]);+ });++ it('Remove column, removed column contains formula', async () => {+ const params: IRemoveRowColCommandParams = {+ range: {+ startColumn: 3,+ endColumn: 3,+ startRow: 0,+ endRow: 2,+ },+ };++ expect(await commandService.executeCommand(RemoveColCommand.id, params)).toBeTruthy();+ const values = getValues(7, 3, 7, 3);+ expect(values).toStrictEqual([[{ f: '=SUM(B8)' }]]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ const valuesUndo = getValues(7, 3, 7, 3);+ expect(valuesUndo).toStrictEqual([[{ f: '=SUM(A8)' }]]);++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ const valuesRedo = getValues(7, 3, 7, 3);+ expect(valuesRedo).toStrictEqual([[{ f: '=SUM(B8)' }]]);});it('Delete move left, value on the left', async () => {diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.tsindex 9dea505dfe..5f77e080b3 100644--- a/packages/sheets-formula/src/controllers/prompt.controller.ts+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts@@ -1719,9 +1719,7 @@ export class PromptController extends Disposable {eventType: DeviceInputEventType.Keyboard,keycode,});- this._commandService.executeCommand(MoveSelectionCommand.id, {- direction: Direction.DOWN,- });+ // Don't move the selection here, because changeVisible will update the selection.}private _pressTab(params: ISelectEditorFormulaOperationParam) {@@ -1740,9 +1738,7 @@ export class PromptController extends Disposable {eventType: DeviceInputEventType.Keyboard,keycode,});- this._commandService.executeCommand(MoveSelectionCommand.id, {- direction: Direction.RIGHT,- });+ // Don't move the selection here, because changeVisible will update the selection.}private _pressEsc(params: ISelectEditorFormulaOperationParam) {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 eb5a0fc890..bca2de296e 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, formulaDataItemToCellDataFormula, isFormulaDataItem } from '../ref-range-formula';describe('Ref range formula test', () => {describe('Util function', () => {@@ -94,6 +94,77 @@ describe('Ref range formula test', () => {expect(result).toStrictEqual({ f: null, si: null });});+ it('Function formulaDataItemToCellDataFormula', () => {+ let formulaDataItem: IFormulaDataItem = {+ f: '=SUM(1)',+ };++ let result = formulaDataItemToCellDataFormula(formulaDataItem);++ expect(result).toStrictEqual({+ f: '=SUM(1)',+ });++ formulaDataItem = {+ f: '',+ si: 'id1',+ };++ result = formulaDataItemToCellDataFormula(formulaDataItem);++ expect(result).toStrictEqual({+ si: 'id1',+ });++ formulaDataItem = {+ f: '=SUM(1)',+ si: 'id1',+ };++ result = formulaDataItemToCellDataFormula(formulaDataItem);++ expect(result).toStrictEqual({+ f: '=SUM(1)',+ });++ formulaDataItem = {+ f: '=SUM(1)',+ si: 'id1',+ x: 0,+ y: 0,+ };++ result = formulaDataItemToCellDataFormula(formulaDataItem);++ expect(result).toStrictEqual({+ f: '=SUM(1)',+ });++ formulaDataItem = {+ f: '=SUM(1)',+ si: 'id1',+ x: 0,+ y: 1,+ };++ result = formulaDataItemToCellDataFormula(formulaDataItem);++ expect(result).toStrictEqual({+ f: '=SUM(1)',+ });++ formulaDataItem = {+ f: '',+ si: '',+ x: 0,+ y: 1,+ };++ result = formulaDataItemToCellDataFormula(formulaDataItem);++ expect(result).toStrictEqual({ f: null, si: null });+ });+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 e39904cf6e..c0c50a232b 100644--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts@@ -15,7 +15,7 @@*/import type { ICellData, IMutationInfo, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';-import { cellToRange, Direction, isFormulaId, isFormulaString, ObjectMatrix, Tools } from '@univerjs/core';+import { cellToRange, Direction, isFormulaId, isFormulaString, ObjectMatrix } from '@univerjs/core';import type { IFormulaData, IFormulaDataItem, IRangeChange } from '@univerjs/engine-formula';import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';import { EffectRefRangId, handleDeleteRangeMoveLeft, handleDeleteRangeMoveUp, handleInsertCol, handleInsertRangeMoveDown, handleInsertRangeMoveRight, handleInsertRow, handleIRemoveCol, handleIRemoveRow, handleMoveCols, handleMoveRange, handleMoveRows, runRefRangeMutations, SetRangeValuesMutation } from '@univerjs/sheets';@@ -207,105 +207,106 @@ export function refRangeFormula(oldFormulaData: IFormulaData,const oldFormulaMatrix = new ObjectMatrix(currentOldFormulaData || {});const newFormulaMatrix = new ObjectMatrix(currentNewFormulaData || {});+ const rangeList = processFormulaChanges(oldFormulaMatrix, type, from, to, range);++ redoFormulaData = getRedoFormulaData(rangeList, oldFormulaMatrix, newFormulaMatrix);+ undoFormulaData = getUndoFormulaData(rangeList, oldFormulaMatrix);++ return {+ redoFormulaData,+ undoFormulaData,+ };+}++function processFormulaChanges(oldFormulaMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>, type: FormulaReferenceMoveType, from: Nullable<IRange>, to: Nullable<IRange>, range: Nullable<IRange>) {// When undoing and redoing, the traversal order may be different. Record the range list of all single formula offsets, and then retrieve the traversal as needed.const rangeList: IRangeChange[] = [];- let isReverse = false;- oldFormulaMatrix.forValue((row, column, cell) => {- if (cell == null) {- return true;- }+ oldFormulaMatrix.forValue((row, column, cell) => {// Offset is only needed when there is a formula- if (!isFormulaDataItem(cell)) {- return;- }+ if (cell == null || !isFormulaDataItem(cell)) return true;const oldCell = cellToRange(row, column);let newCell = null;-- switch (type) {- case FormulaReferenceMoveType.MoveRange:- if (from == null || to == null) {- return;- }- newCell = handleRefMoveRange(from, to, oldCell);- break;- case FormulaReferenceMoveType.MoveRows:- if (from == null || to == null) {- return;- }- newCell = handleRefMoveRows(from, to, oldCell);- break;- case FormulaReferenceMoveType.MoveCols:- if (from == null || to == null) {- return;- }- newCell = handleRefMoveCols(from, to, oldCell);- break;- default:- break;+ let isReverse = false;++ // Handle moves+ if ([FormulaReferenceMoveType.MoveRange, FormulaReferenceMoveType.MoveRows, FormulaReferenceMoveType.MoveCols].includes(type)) {+ newCell = handleMove(type, from, to, oldCell);+ } else if (range !== undefined && range !== null) { // Handle inserts and deletes+ const result = handleInsertDelete(type, range, oldCell);+ // When removing a cell containing a formula, newCell is null, but the formula value of oldCell is required when undoing it, newCell can be null+ newCell = result.newCell;+ isReverse = result.isReverse;}- if (Tools.isDefine(range)) {- switch (type) {- case FormulaReferenceMoveType.InsertRow:- newCell = handleRefInsertRow(range, oldCell);- isReverse = true;- break;- case FormulaReferenceMoveType.InsertColumn:- newCell = handleRefInsertCol(range, oldCell);- isReverse = true;- break;- case FormulaReferenceMoveType.RemoveRow:- newCell = handleRefRemoveRow(range, oldCell);- break;- case FormulaReferenceMoveType.RemoveColumn:- newCell = handleRefMoveCol(range, oldCell);- break;- case FormulaReferenceMoveType.DeleteMoveLeft:- newCell = handleRefDeleteMoveLeft(range, oldCell);- break;- case FormulaReferenceMoveType.DeleteMoveUp:- newCell = handleRefDeleteMoveUp(range, oldCell);- break;- case FormulaReferenceMoveType.InsertMoveDown:- newCell = handleRefInsertMoveDown(range, oldCell);- isReverse = true;- break;- case FormulaReferenceMoveType.InsertMoveRight:- newCell = handleRefInsertMoveRight(range, oldCell);- isReverse = true;- break;- default:- break;- }- }-- if (newCell == null) {- return;- }+ // Don't intercept newCell null here// Note: The formula may only update the reference and not offset the position. The situation where the position is not shifted cannot be intercepted here.- if (isReverse) {- rangeList.unshift({- oldCell,- newCell,- });- } else {- rangeList.push({- oldCell,- newCell,- });- }+ isReverse ? rangeList.unshift({ oldCell, newCell }) : rangeList.push({ oldCell, newCell });});- redoFormulaData = getRedoFormulaData(rangeList, oldFormulaMatrix, newFormulaMatrix);- undoFormulaData = getUndoFormulaData(rangeList, oldFormulaMatrix);+ return rangeList;+}- return {- redoFormulaData,- undoFormulaData,- };+function handleMove(type: FormulaReferenceMoveType, from: Nullable<IRange>, to: Nullable<IRange>, oldCell: IRange) {+ if (from == null || to == null) {+ return null;+ }++ switch (type) {+ case FormulaReferenceMoveType.MoveRange:++ return handleRefMoveRange(from, to, oldCell);+ case FormulaReferenceMoveType.MoveRows:++ return handleRefMoveRows(from, to, oldCell);+ case FormulaReferenceMoveType.MoveCols:++ return handleRefMoveCols(from, to, oldCell);+ default:+ return null;+ }+}++function handleInsertDelete(type: FormulaReferenceMoveType, range: IRange, oldCell: IRange) {+ let newCell: IRange | null = null;+ let isReverse = false;++ switch (type) {+ case FormulaReferenceMoveType.InsertRow:+ newCell = handleRefInsertRow(range, oldCell);+ isReverse = true;+ break;+ case FormulaReferenceMoveType.InsertColumn:+ newCell = handleRefInsertCol(range, oldCell);+ isReverse = true;+ break;+ case FormulaReferenceMoveType.RemoveRow:+ newCell = handleRefRemoveRow(range, oldCell);+ break;+ case FormulaReferenceMoveType.RemoveColumn:+ newCell = handleRefRemoveCol(range, oldCell);+ break;+ case FormulaReferenceMoveType.DeleteMoveLeft:+ newCell = handleRefDeleteMoveLeft(range, oldCell);+ break;+ case FormulaReferenceMoveType.DeleteMoveUp:+ newCell = handleRefDeleteMoveUp(range, oldCell);+ break;+ case FormulaReferenceMoveType.InsertMoveDown:+ newCell = handleRefInsertMoveDown(range, oldCell);+ isReverse = true;+ break;+ case FormulaReferenceMoveType.InsertMoveRight:+ newCell = handleRefInsertMoveRight(range, oldCell);+ isReverse = true;+ break;+ default:+ break;+ }++ return { newCell, isReverse };}function handleRefMoveRange(from: IRange, to: IRange, oldCell: IRange) {@@ -380,7 +381,7 @@ function handleRefRemoveRow(range: IRange, oldCell: IRange) {return runRefRangeMutations(operators, oldCell);}-function handleRefMoveCol(range: IRange, oldCell: IRange) {+function handleRefRemoveCol(range: IRange, oldCell: IRange) {const operators = handleIRemoveCol({id: EffectRefRangId.RemoveColCommandId,@@ -453,13 +454,17 @@ function getRedoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectMconst { oldCell, newCell } = item;const { startRow: oldStartRow, startColumn: oldStartColumn } = oldCell;- const { startRow: newStartRow, startColumn: newStartColumn } = newCell;const newFormula = newFormulaMatrix.getValue(oldStartRow, oldStartColumn) || oldFormulaMatrix.getValue(oldStartRow, oldStartColumn);- const newValue = formulaDataItemToCellData(newFormula);+ // Use the formula result value to update the data to ensure accuracy, otherwise the new formula cannot be inferred from #REF+ const newValue = formulaDataItemToCellDataFormula(newFormula);redoFormulaData.setValue(oldStartRow, oldStartColumn, { f: null, si: null });- redoFormulaData.setValue(newStartRow, newStartColumn, newValue);++ if (newCell) {+ const { startRow: newStartRow, startColumn: newStartColumn } = newCell;+ redoFormulaData.setValue(newStartRow, newStartColumn, newValue);+ }});return redoFormulaData.clone();@@ -474,16 +479,20 @@ function getRedoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectMfunction getUndoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>) {const undoFormulaData = new ObjectMatrix<Nullable<ICellData>>({});- rangeList.forEach((item) => {+ // Maintaining the correct assignment order prevents overwriting data+ rangeList.reverse().forEach((item) => {const { oldCell, newCell } = item;const { startRow: oldStartRow, startColumn: oldStartColumn } = oldCell;- const { startRow: newStartRow, startColumn: newStartColumn } = newCell;const oldFormula = oldFormulaMatrix.getValue(oldStartRow, oldStartColumn);const oldValue = formulaDataItemToCellData(oldFormula);- undoFormulaData.setValue(newStartRow, newStartColumn, { f: null, si: null });+ if (newCell) {+ const { startRow: newStartRow, startColumn: newStartColumn } = newCell;+ undoFormulaData.setValue(newStartRow, newStartColumn, { f: null, si: null });+ }+undoFormulaData.setValue(oldStartRow, oldStartColumn, oldValue);});@@ -532,6 +541,50 @@ export function formulaDataItemToCellData(formulaDataItem: Nullable<IFormulaDatareturn cellData;}+/**+ * Transfer the formulaDataItem to the cellData, contains formula+ * ┌────────────────────────────────┬─────────────────┐+ * │ IFormulaDataItem │ ICellData │+ * ├──────────────────┬─────┬───┬───┼───────────┬─────┤+ * │ f │ si │ x │ y │ f │ si │+ * ├──────────────────┼─────┼───┼───┼───────────┼─────┤+ * │ =SUM(1) │ │ │ │ =SUM(1) │ │+ * │ │ id1 │ │ │ │ id1 │+ * │ =SUM(1) │ id1 │ │ │ =SUM(1) │ │+ * │ =SUM(1) │ id1 │ 0 │ 0 │ =SUM(1) │ │+ * │ =SUM(1) │ id1 │ 0 │ 1 │ =SUM(1) │ │+ * └──────────────────┴─────┴───┴───┴───────────┴─────┘+ *+ * The fifth case: The value f of the formula is already the result value. If the formula content of si contains #REF, it cannot be obtained from the formula offset of si, and the result value must be stored directly+ */+export function formulaDataItemToCellDataFormula(formulaDataItem: Nullable<IFormulaDataItem>): Nullable<ICellData> {+ if (formulaDataItem == null) {+ return;+ }+ const { f, si } = formulaDataItem;+ const checkFormulaString = isFormulaString(f);+ const checkFormulaId = isFormulaId(si);++ if (!checkFormulaString && !checkFormulaId) {+ return {+ f: null,+ si: null,+ };+ }++ const cellData: ICellData = {};++ if (checkFormulaString) {+ cellData.f = f;+ }++ if (checkFormulaId && !checkFormulaString) {+ cellData.si = si;+ }++ return cellData;+}+export function isFormulaDataItem(cell: IFormulaDataItem) {const formulaString = cell?.f || '';const formulaId = cell?.si || '';