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): fix the issue with formula movement (#5740)

wpxp123456cb76748640f5
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/update-formula.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/update-formula.controller.spec.ts
index 47dab71585..d60cdab25f 100644
--- a/packages/sheets-formula-ui/src/controllers/__tests__/update-formula.controller.spec.ts
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/update-formula.controller.spec.ts
@@ -725,7 +725,7 @@ describe('Test update formula ', () => {
]);
});
- it('Move range with si only', async () => {
+ it('Move range with si only, but the si is not source formula cell', async () => {
const workbook = get(IUniverInstanceService).getUnit<Workbook>('test');
const sheetId = 'sheet6';
const sheet6 = workbook?.getSheetBySheetId(sheetId);
@@ -756,9 +756,9 @@ describe('Test update formula ', () => {
expect(values1).toStrictEqual([[{ f: '=A3', t: 2, v: 3 }]]);
const values2 = getValues(1, 1, 3, 1, sheetId);
expect(values2).toStrictEqual([
- [{ f: '=A2', t: 2, v: 2 }],
+ [{ f: '=A2', si: 'W8Hdfc', t: 2, v: 2 }],
[null],
- [{ f: '=A4', t: 2, v: 4 }],
+ [{ si: 'W8Hdfc', t: 2, v: 4 }],
]);
expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
@@ -776,9 +776,9 @@ describe('Test update formula ', () => {
expect(valuesRedo1).toStrictEqual([[{ f: '=A3', t: 2, v: 3 }]]);
const valuesRedo2 = getValues(1, 1, 3, 1, sheetId);
expect(valuesRedo2).toStrictEqual([
- [{ f: '=A2', t: 2, v: 2 }],
+ [{ f: '=A2', si: 'W8Hdfc', t: 2, v: 2 }],
[null],
- [{ f: '=A4', t: 2, v: 4 }],
+ [{ si: 'W8Hdfc', t: 2, v: 4 }],
]);
});
diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.ts
index fa2ecfbff7..9861bf595a 100644
--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts
@@ -362,8 +362,8 @@ export class UpdateFormulaController extends Disposable {
for (const sheetId of sheetDataKeys) {
const matrixData = new ObjectMatrix(sheetData[sheetId] || {});
-
const newFormulaDataItem = new ObjectMatrix<IFormulaDataItem>();
+ const shouldModifySi: string[] = [];
// eslint-disable-next-line max-lines-per-function, complexity
matrixData.forValue((row, column, formulaDataItem) => {
@@ -379,6 +379,8 @@ export class UpdateFormulaController extends Disposable {
let shouldModify = false;
const refChangeIds: number[] = [];
+ const { type, from } = formulaReferenceMoveParam;
+
for (let i = 0, len = sequenceNodes.length; i < len; i++) {
const node = sequenceNodes[i];
@@ -387,7 +389,6 @@ export class UpdateFormulaController extends Disposable {
}
const { token, nodeType } = node;
- const { type } = formulaReferenceMoveParam;
// The impact of defined name changes on formula calculation
// 1. ref range only changes formulaOrRefString to trigger recalculation
@@ -514,15 +515,30 @@ export class UpdateFormulaController extends Disposable {
shouldModify = true;
refChangeIds.push(i);
// newRefString = ErrorType.REF;
- } else if (type === FormulaReferenceMoveType.MoveRange && si) {
- // If the operation is a move range and the formula has si, unpack the si to f.
- // This is to ensure that the si formula can be recalculated correctly after the move.
- shouldModify = true;
+
+ // If the formula cell has an si, it means the formula cell is source of other same si cells, so the si cells needs to be updated.
+ if (si && (x ?? 0) === 0 && (y ?? 0) === 0) shouldModifySi.push(si);
}
}
if (!shouldModify) {
- return true;
+ /**
+ * If the operation is a move type, and the formula cell has si and is the same as the current shouldModifySi, unpack the si to f.
+ * Or the source formula cell is in the moved range.
+ * This is to ensure that the si formula can be recalculated correctly after the move.
+ */
+ if (
+ si &&
+ [FormulaReferenceMoveType.MoveRows, FormulaReferenceMoveType.MoveCols, FormulaReferenceMoveType.MoveRange].includes(type)
+ ) {
+ if (from && from.startRow <= row && row <= from.endRow && from.startColumn <= column && column <= from.endColumn) {
+ if ((x ?? 0) === 0 && (y ?? 0) === 0) shouldModifySi.push(si);
+ } else if (!shouldModifySi.includes(si)) {
+ return true;
+ }
+ } else {
+ return true;
+ }
}
const newSequenceNodes = updateRefOffset(sequenceNodes, refChangeIds, x, y);
diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
index 4858ae7686..e75f536141 100644
--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
@@ -17,7 +17,7 @@
import type { ICellData, IMutationInfo, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';
import type { IFormulaData, IFormulaDataItem, IRangeChange, ISequenceNode } from '@univerjs/engine-formula';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import { cellToRange, Direction, isFormulaId, isFormulaString, ObjectMatrix, Rectangle } from '@univerjs/core';
+import { cellToRange, Direction, isFormulaId, isFormulaString, ObjectMatrix, Rectangle, Tools } from '@univerjs/core';
import { deserializeRangeWithSheetWithCache, sequenceNodeType, serializeRangeToRefString } from '@univerjs/engine-formula';
import { EffectRefRangId, handleDeleteRangeMoveLeft, handleDeleteRangeMoveUp, handleInsertCol, handleInsertRangeMoveDown, handleInsertRangeMoveRight, handleInsertRow, handleIRemoveCol, handleIRemoveRow, handleMoveCols, handleMoveRange, handleMoveRows, runRefRangeMutations, SetRangeValuesMutation } from '@univerjs/sheets';
import { checkFormulaDataNull } from './offset-formula-data';
@@ -239,7 +239,7 @@ export function refRangeFormula(oldFormulaData: IFormulaData, newFormulaData: IF
if (unitId !== targetUnitId || currentSheetId !== sheetId) {
rangeList = processFormulaRange(newFormulaMatrix);
} else {
- rangeList = processFormulaChanges(oldFormulaMatrix, formulaReferenceMoveParam);
+ rangeList = processFormulaChanges(oldFormulaMatrix, newFormulaMatrix, formulaReferenceMoveParam);
}
const sheetRedoFormulaData = getRedoFormulaData(rangeList, oldFormulaMatrix, newFormulaMatrix);
@@ -269,7 +269,7 @@ export function refRangeFormula(oldFormulaData: IFormulaData, newFormulaData: IF
};
}
-function processFormulaChanges(oldFormulaMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>, formulaReferenceMoveParam: IFormulaReferenceMoveParam) {
+function processFormulaChanges(oldFormulaMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>, newFormulaMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>, formulaReferenceMoveParam: IFormulaReferenceMoveParam) {
// 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 { type, from, to, range } = formulaReferenceMoveParam;
const rangeList: IRangeChange[] = [];
@@ -292,6 +292,11 @@ function processFormulaChanges(oldFormulaMatrix: ObjectMatrix<Nullable<IFormulaD
isReverse = result.isReverse;
}
+ // If oldCell and newCell are the same and this cell no formula updated, it means that the formula is not offset, skip it directly
+ if (Tools.diffValue(oldCell, newCell) && !newFormulaMatrix.getValue(row, column)) {
+ return true;
+ }
+
// 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.
diff --git a/tests/formula-integration/src/__snapshots__/test-formula-move---move-formula-si-rows-result.json b/tests/formula-integration/src/__snapshots__/test-formula-move---move-formula-si-rows-result.json
new file mode 100644
index 0000000000..2344a02921
--- /dev/null
+++ b/tests/formula-integration/src/__snapshots__/test-formula-move---move-formula-si-rows-result.json
@@ -0,0 +1,105 @@
+{
+ "id": "Opu_sb",
+ "sheetOrder": [
+ "AmvABRJl7VeVXpMk7Hq6_"
+ ],
+ "name": "",
+ "appVersion": "0.10.5",
+ "locale": "zhCN",
+ "styles": {},
+ "sheets": {
+ "AmvABRJl7VeVXpMk7Hq6_": {
+ "id": "AmvABRJl7VeVXpMk7Hq6_",
+ "name": "Sheet1",
+ "tabColor": "",
+ "hidden": 0,
+ "rowCount": 1000,
+ "columnCount": 20,
+ "zoomRatio": 1,
+ "freeze": {
+ "xSplit": 0,
+ "ySplit": 0,
+ "startRow": -1,
+ "startColumn": -1
+ },
+ "scrollTop": 0,
+ "scrollLeft": 0,
+ "defaultColumnWidth": 88,
+ "defaultRowHeight": 24,
+ "mergeData": [],
+ "cellData": {
+ "2": {
+ "2": {
+ "v": 2,
+ "t": 2
+ },
+ "3": {
+ "f": "=C3",
+ "v": 2,
+ "t": 2
+ }
+ },
+ "3": {
+ "2": {
+ "v": 1,
+ "t": 2
+ },
+ "3": {
+ "f": "=C4",
+ "v": 1,
+ "t": 2
+ }
+ },
+ "4": {
+ "2": {
+ "v": 3,
+ "t": 2
+ },
+ "3": {
+ "f": "=C5",
+ "v": 3,
+ "t": 2
+ }
+ }
+ },
+ "rowData": {},
+ "columnData": {},
+ "showGridlines": 1,
+ "rowHeader": {
+ "width": 46,
+ "hidden": 0
+ },
+ "columnHeader": {
+ "height": 20,
+ "hidden": 0
+ },
+ "rightToLeft": 0
+ }
+ },
+ "resources": [
+ {
+ "name": "SHEET_RANGE_PROTECTION_PLUGIN",
+ "data": ""
+ },
+ {
+ "name": "SHEET_AuthzIoMockService_PLUGIN",
+ "data": "{}"
+ },
+ {
+ "name": "SHEET_WORKSHEET_PROTECTION_PLUGIN",
+ "data": "{}"
+ },
+ {
+ "name": "SHEET_WORKSHEET_PROTECTION_POINT_PLUGIN",
+ "data": "{}"
+ },
+ {
+ "name": "SHEET_DEFINED_NAME_PLUGIN",
+ "data": "{}"
+ },
+ {
+ "name": "SHEET_RANGE_THEME_MODEL_PLUGIN",
+ "data": "{}"
+ }
+ ]
+}
diff --git a/tests/formula-integration/src/__snapshots__/test-formula-move---move-formula-si-rows.json b/tests/formula-integration/src/__snapshots__/test-formula-move---move-formula-si-rows.json
new file mode 100644
index 0000000000..a933c2665a
--- /dev/null
+++ b/tests/formula-integration/src/__snapshots__/test-formula-move---move-formula-si-rows.json
@@ -0,0 +1,106 @@
+{
+ "id": "Opu_sb",
+ "sheetOrder": [
+ "AmvABRJl7VeVXpMk7Hq6_"
+ ],
+ "name": "",
+ "appVersion": "0.10.5",
+ "locale": "zhCN",
+ "styles": {},
+ "sheets": {
+ "AmvABRJl7VeVXpMk7Hq6_": {
+ "id": "AmvABRJl7VeVXpMk7Hq6_",
+ "name": "Sheet1",
+ "tabColor": "",
+ "hidden": 0,
+ "rowCount": 1000,
+ "columnCount": 20,
+ "zoomRatio": 1,
+ "freeze": {
+ "xSplit": 0,
+ "ySplit": 0,
+ "startRow": -1,
+ "startColumn": -1
+ },
+ "scrollTop": 0,
+ "scrollLeft": 0,
+ "defaultColumnWidth": 88,
+ "defaultRowHeight": 24,
+ "mergeData": [],
+ "cellData": {
+ "2": {
+ "2": {
+ "v": 1,
+ "t": 2
+ },
+ "3": {
+ "f": "=C3",
+ "v": 1,
+ "t": 2
+ }
+ },
+ "3": {
+ "2": {
+ "v": 2,
+ "t": 2
+ },
+ "3": {
+ "si": "v8h2ot",
+ "f": "=C4",
+ "v": 2,
+ "t": 2
+ }
+ },
+ "4": {
+ "2": {
+ "v": 3,
+ "t": 2
+ },
+ "3": {
+ "si": "v8h2ot",
+ "v": 3,
+ "t": 2
+ }
+ }
+ },
+ "rowData": {},
+ "columnData": {},
+ "showGridlines": 1,
+ "rowHeader": {
+ "width": 46,
+ "hidden": 0
+ },
+ "columnHeader": {
+ "height": 20,
+ "hidden": 0
+ },
+ "rightToLeft": 0
+ }
+ },
+ "resources": [
+ {
+ "name": "SHEET_RANGE_PROTECTION_PLUGIN",
+ "data": ""
+ },
+ {
+ "name": "SHEET_AuthzIoMockService_PLUGIN",
+ "data": "{}"
+ },
+ {
+ "name": "SHEET_WORKSHEET_PROTECTION_PLUGIN",
+ "data": "{}"
+ },
+ {
+ "name": "SHEET_WORKSHEET_PROTECTION_POINT_PLUGIN",
+ "data": "{}"
+ },
+ {
+ "name": "SHEET_DEFINED_NAME_PLUGIN",
+ "data": "{}"
+ },
+ {
+ "name": "SHEET_RANGE_THEME_MODEL_PLUGIN",
+ "data": "{}"
+ }
+ ]
+}
diff --git a/tests/formula-integration/src/__testing__/test-formula-move.ts b/tests/formula-integration/src/__testing__/test-formula-move.ts
index 03179a94a5..6cfd42f6da 100644
--- a/tests/formula-integration/src/__testing__/test-formula-move.ts
+++ b/tests/formula-integration/src/__testing__/test-formula-move.ts
@@ -22,7 +22,7 @@ import { FUniver } from '@univerjs/core/facade';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import zhCN from '@univerjs/mockdata/locales/zh-CN';
import { MoveRangeCommand, UniverSheetsPlugin } from '@univerjs/sheets';
-import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
+import { CalculationMode, UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
import { expect } from 'vitest';
import { getTestFilePath, getTestName } from './util';
@@ -36,7 +36,9 @@ function createTestBed() {
univer.registerPlugin(UniverFormulaEnginePlugin);
univer.registerPlugin(UniverSheetsPlugin);
- univer.registerPlugin(UniverSheetsFormulaPlugin);
+ univer.registerPlugin(UniverSheetsFormulaPlugin, {
+ initialFormulaComputing: CalculationMode.FORCED,
+ });
const injector = univer.__getInjector();
@@ -97,6 +99,56 @@ export async function expectMoveFormulaRowsResultMatchesSnapshot() {
}
}
+export async function expectMoveFormulaSiRowsResultMatchesSnapshot() {
+ const testBed = createTestBed();
+ const snapshotRootDir = path.join(import.meta.dirname, '../__snapshots__');
+
+ const testSnapshotPath = path.resolve(snapshotRootDir, `${getTestFilePath()}.json`);
+ if (!fs.existsSync(testSnapshotPath)) {
+ throw new Error(`Cannot find snapshot file for test "${getTestName()}".`);
+ }
+
+ const testSnapshotRaw = fs.readFileSync(testSnapshotPath, 'utf-8');
+ const testSnapshot = JSON.parse(testSnapshotRaw) as IWorkbookData;
+
+ const workbook = testBed.api.createWorkbook(testSnapshot);
+ const univerInstanceService = testBed.get(IUniverInstanceService);
+ univerInstanceService.focusUnit(workbook.getId());
+ const worksheet = workbook.getActiveSheet();
+
+ // move row 3 to before row 5
+ const rowSpec = worksheet.getRange('3:3');
+ worksheet.moveRows(rowSpec, 4);
+
+ const resultSnapshot = workbook.save();
+ const snapshotFilePath = path.resolve(snapshotRootDir, `${getTestFilePath()}-result.json`);
+ if (fs.existsSync(snapshotFilePath)) {
+ const resultSnapshotFileString = fs.readFileSync(snapshotFilePath, 'utf-8');
+ expect(resultSnapshot).toMatchObject(JSON.parse(resultSnapshotFileString));
+ } else {
+ fs.writeFileSync(snapshotFilePath, JSON.stringify(resultSnapshot, null, 4));
+
+ // eslint-disable-next-line no-console
+ console.log(`Snapshot file created at: ${snapshotFilePath}`);
+ }
+
+ // perform undo operation
+ await testBed.api.undo();
+
+ // compare the result with the snapshot
+ const resultSnapshot_undo = workbook.save();
+ const snapshotFilePath_undo = path.resolve(snapshotRootDir, `${getTestFilePath()}.json`);
+ if (fs.existsSync(snapshotFilePath_undo)) {
+ const resultSnapshotFileString = fs.readFileSync(snapshotFilePath_undo, 'utf-8');
+ expect(resultSnapshot_undo).toMatchObject(JSON.parse(resultSnapshotFileString));
+ } else {
+ fs.writeFileSync(snapshotFilePath_undo, JSON.stringify(resultSnapshot_undo, null, 4));
+
+ // eslint-disable-next-line no-console
+ console.log(`Snapshot file created at: ${snapshotFilePath_undo}`);
+ }
+}
+
export async function expectMoveFormulaCellResultMatchesSnapshot() {
const testBed = createTestBed();
const snapshotRootDir = path.join(import.meta.dirname, '../__snapshots__');
diff --git a/tests/formula-integration/src/__tests__/test-formula-move.spec.ts b/tests/formula-integration/src/__tests__/test-formula-move.spec.ts
index 741ac9eb6d..db595096c3 100644
--- a/tests/formula-integration/src/__tests__/test-formula-move.spec.ts
+++ b/tests/formula-integration/src/__tests__/test-formula-move.spec.ts
@@ -15,13 +15,17 @@
*/
import { describe, it } from 'vitest';
-import { expectMoveFormulaCellResultMatchesSnapshot, expectMoveFormulaRowsResultMatchesSnapshot } from '../__testing__/test-formula-move';
+import { expectMoveFormulaCellResultMatchesSnapshot, expectMoveFormulaRowsResultMatchesSnapshot, expectMoveFormulaSiRowsResultMatchesSnapshot } from '../__testing__/test-formula-move';
describe('Test formula move', () => {
it('move formula rows', () => {
expectMoveFormulaRowsResultMatchesSnapshot();
});
+ it('move formula si rows', () => {
+ expectMoveFormulaSiRowsResultMatchesSnapshot();
+ });
+
it('move formula cell', () => {
expectMoveFormulaCellResultMatchesSnapshot();
});