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): fix some issues with the cross-worksheet cut formula (#6722)
wpxp12345666631d4bbf0e
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.tsindex dbe6abac76..31ed9bf7c0 100644--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts@@ -223,6 +223,9 @@ function createFormulaClipboardWorkbookData(): IWorkbookData {4: { v: 11 },5: { f: '=SUM(B3:E3)' },},+ 3: {+ 0: { f: '=SUM(Sheet3!A1:A3,B1)' },+ },},},sheet2: {@@ -235,6 +238,17 @@ function createFormulaClipboardWorkbookData(): IWorkbookData {},},},+ sheet3: {+ id: 'sheet3',+ name: 'Sheet3',+ cellData: {+ 0: {+ 0: { v: 1 },+ 1: { v: 2 },+ 2: { v: 3 },+ },+ },+ },},};}@@ -474,6 +488,99 @@ describe('Test cut command with formulas', () => {[{ f: '=F3' }],]);});++ it('cut-pasting a formula cell across worksheets, the reference range is not affected by the moved range', async () => {+ await cutPaste(+ { rows: [0], cols: [2] },+ { startRow: 10, startColumn: 0, endRow: 10, endColumn: 0 },+ 'sheet1',+ 'sheet2'+ );++ expect(getValues(0, 2, 0, 2)).toStrictEqual([+ [null],+ ]);+ expect(getValues(10, 0, 10, 0, 'sheet2')).toStrictEqual([+ [{ f: '=Sheet1!A1' }],+ ]);+ expect(getValues(10, 0, 10, 0, 'sheet1')).toStrictEqual([+ [null],+ ]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();++ expect(getValues(0, 2, 0, 2)).toStrictEqual([+ [{ f: '=A1' }],+ ]);+ expect(getValues(10, 0, 10, 0, 'sheet2')).toStrictEqual([+ [null],+ ]);+ expect(getValues(10, 0, 10, 0, 'sheet1')).toStrictEqual([+ [null],+ ]);+ });++ it('cut-pasting a formula cell across worksheets, the reference range is affected by the moved range', async () => {+ await cutPaste(+ { rows: [2], cols: [0, 1, 2, 3, 4, 5] },+ { startRow: 11, startColumn: 0, endRow: 11, endColumn: 0 },+ 'sheet1',+ 'sheet2'+ );++ expect(getValues(2, 0, 2, 5)).toStrictEqual([+ [null, null, null, null, null, null],+ ]);+ expect(getValues(11, 0, 11, 5, 'sheet2')).toStrictEqual([+ [{ v: 'label' }, { v: 7 }, { f: '=B12' }, { f: '=C12+1' }, { v: 11 }, { f: '=SUM(B12:E12)' }],+ ]);+ expect(getValues(11, 0, 11, 5, 'sheet1')).toStrictEqual([+ [null, null, null, null, null, null],+ ]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();++ expect(getValues(2, 0, 2, 5)).toStrictEqual([+ [{ v: 'label' }, { v: 7 }, { f: '=B3' }, { f: '=C3+1' }, { v: 11 }, { f: '=SUM(B3:E3)' }],+ ]);+ expect(getValues(11, 0, 11, 5, 'sheet2')).toStrictEqual([+ [null, null, null, null, null, null],+ ]);+ expect(getValues(11, 0, 11, 5, 'sheet1')).toStrictEqual([+ [null, null, null, null, null, null],+ ]);+ });++ it('cut-pasting a formula cell across worksheets, the reference range has Sheet3 range and Sheet1 range', async () => {+ await cutPaste(+ { rows: [3], cols: [0] },+ { startRow: 12, startColumn: 0, endRow: 12, endColumn: 0 },+ 'sheet1',+ 'sheet2'+ );++ expect(getValues(3, 0, 3, 0)).toStrictEqual([+ [null],+ ]);+ expect(getValues(12, 0, 12, 0, 'sheet2')).toStrictEqual([+ [{ f: '=SUM(Sheet3!A1:A3,Sheet1!B1)' }],+ ]);+ expect(getValues(12, 0, 12, 0, 'sheet1')).toStrictEqual([+ [null],+ ]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();++ expect(getValues(3, 0, 3, 0)).toStrictEqual([+ [{ f: '=SUM(Sheet3!A1:A3,B1)' }],+ ]);+ expect(getValues(12, 0, 12, 0, 'sheet2')).toStrictEqual([+ [null],+ ]);+ expect(getValues(12, 0, 12, 0, 'sheet1')).toStrictEqual([+ [null],+ ]);+ });});describe('Test paste with formula', () => {diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.tsindex 4a32512377..e04fef134b 100644--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts@@ -39,6 +39,7 @@ import {Injector,IUniverInstanceService,ObjectMatrix,+ Rectangle,Tools,UniverInstanceType,} from '@univerjs/core';@@ -343,15 +344,22 @@ export class UpdateFormulaController extends Disposable {unitSheetNameMap: IUnitSheetNameMap,formulaReferenceMoveParam: IFormulaReferenceMoveParam) {- if (!Tools.isDefine(formulaData)) return { newFormulaData: {}, oldFormulaData: {} };+ if (!Tools.isDefine(formulaData)) return { newFormulaData: {} };const formulaDataKeys = Object.keys(formulaData);- if (formulaDataKeys.length === 0) return { newFormulaData: {}, oldFormulaData: {} };+ if (formulaDataKeys.length === 0) return { newFormulaData: {} };- const oldFormulaData: IFormulaData = {};const newFormulaData: IFormulaData = {};+ const { unitId: fromUnitId, sheetId: fromSheetId, sheetName: fromSheetName, targetUnitId, targetSheetId, type, from, to } = formulaReferenceMoveParam;++ const inCrossSheetCutRangeNewFormulas: Array<{+ fromRow: number;+ fromColumn: number;+ formulaString: string;+ }> = [];+for (const unitId of formulaDataKeys) {const sheetData = formulaData[unitId];@@ -361,10 +369,6 @@ export class UpdateFormulaController extends Disposable {const sheetDataKeys = Object.keys(sheetData);- if (!Tools.isDefine(oldFormulaData[unitId])) {- oldFormulaData[unitId] = {};- }-if (!Tools.isDefine(newFormulaData[unitId])) {newFormulaData[unitId] = {};}@@ -388,7 +392,18 @@ export class UpdateFormulaController extends Disposable {let shouldModify = false;const refChangeIds: number[] = [];- const { type, from } = formulaReferenceMoveParam;++ // Whether the formula cell is in the moved range and the move is a cross-worksheet cut operation+ const inCrossSheetCutRange = type === FormulaReferenceMoveType.MoveRange &&+ (targetUnitId !== fromUnitId || targetSheetId !== fromSheetId) &&+ unitId === fromUnitId &&+ sheetId === fromSheetId &&+ from &&+ from.startRow <= row &&+ row <= from.endRow &&+ from.startColumn <= column &&+ column <= from.endColumn;+ const inCrossSheetCutRangeSequenceNodes = [...sequenceNodes];for (let i = 0, len = sequenceNodes.length; i < len; i++) {const node = sequenceNodes[i];@@ -512,7 +527,10 @@ export class UpdateFormulaController extends Disposable {sequenceUnitRangeWidthOffset,formulaReferenceMoveParam,unitId,- sheetId+ sheetId,+ {+ inCrossSheetCutRange,+ });}@@ -528,6 +546,34 @@ export class UpdateFormulaController extends Disposable {// 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 the reference sequence range is not affected by the move, and the move is a cross-worksheet cut operation, it may be necessary to rewrite the sheet name in the ref string after move, to make sure the ref still works after move.+ * For example, if a formula cell is `=SUM(A1:A5)` in Sheet1, and formula cell cut to Sheet2, the formula should be rewritten to `=SUM(Sheet1!A1:A5)`, otherwise it will become `=SUM(A1:A5)` and reference the wrong range in Sheet2.+ */+ if (inCrossSheetCutRange) {+ if (newRefString != null) {+ inCrossSheetCutRangeSequenceNodes[i] = {+ ...node,+ token: newRefString,+ };+ } else if ((!sequenceUnitId || sequenceUnitId === fromUnitId) && (!sequenceSheetId || sequenceSheetId === fromSheetId)) {+ /**+ * Only the reference range is in the from worksheet need to rewrite the sheet name, otherwise the ref string will be rewritten unnecessarily when moving between other worksheets.+ * For example, if a formula cell is `=SUM(Sheet3!A1:A5)` in Sheet1, and formula cell cut to Sheet2, the formula should not be rewritten, otherwise it will become `=SUM(Sheet1!A1:A5)` and reference the wrong range in Sheet1, while the original ref is referencing Sheet3 and should not be affected by the move between Sheet1 and Sheet2.+ */+ const sequenceRange = Rectangle.moveOffset(range, x || 0, y || 0);+ inCrossSheetCutRangeSequenceNodes[i] = {+ ...node,+ token: serializeRangeToRefString({+ range: sequenceRange,+ sheetName: fromSheetName || sheetName,+ unitId: targetUnitId !== fromUnitId ? fromUnitId : '',+ }),+ };+ shouldModify = true;+ }+ }}if (!shouldModify) {@@ -550,6 +596,16 @@ export class UpdateFormulaController extends Disposable {}}+ if (inCrossSheetCutRange) {+ const newSequenceNodes = updateRefOffset(inCrossSheetCutRangeSequenceNodes, refChangeIds, x, y);+ inCrossSheetCutRangeNewFormulas.push({+ fromRow: row,+ fromColumn: column,+ formulaString: `=${generateStringWithSequence(newSequenceNodes)}`,+ });+ return true;+ }+const newSequenceNodes = updateRefOffset(sequenceNodes, refChangeIds, x, y);newFormulaDataItem.setValue(row, column, {@@ -563,6 +619,30 @@ export class UpdateFormulaController extends Disposable {}}+ if (inCrossSheetCutRangeNewFormulas.length > 0 && targetUnitId && targetSheetId) {+ if (!newFormulaData[targetUnitId]) {+ newFormulaData[targetUnitId] = {};+ }++ if (!newFormulaData[targetUnitId][targetSheetId]) {+ newFormulaData[targetUnitId][targetSheetId] = {};+ }++ for (const newFormula of inCrossSheetCutRangeNewFormulas) {+ const { fromRow, fromColumn, formulaString } = newFormula;+ const targetRow = fromRow + ((to?.startRow ?? 0) - (from?.startRow ?? 0));+ const targetColumn = fromColumn + ((to?.startColumn ?? 0) - (from?.startColumn ?? 0));++ if (!newFormulaData[targetUnitId][targetSheetId][targetRow]) {+ newFormulaData[targetUnitId][targetSheetId][targetRow] = {};+ }++ newFormulaData[targetUnitId][targetSheetId][targetRow][targetColumn] = {+ f: formulaString,+ };+ }+ }+return { newFormulaData };}}diff --git a/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-param.spec.ts b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-param.spec.tsindex d9aed3452d..1085018720 100644--- a/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-param.spec.ts+++ b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-param.spec.ts@@ -89,6 +89,7 @@ describe('getReferenceMoveParams', () => {type: FormulaReferenceMoveType.MoveRange,unitId: 'test',sheetId: 'sheet1',+ sheetName: 'Sheet1',targetUnitId: 'test',targetSheetId: 'sheet1',targetSheetName: 'Sheet1',diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts b/packages/sheets-formula/src/controllers/utils/ref-range-formula.tsindex c651b07ea4..7e83222f34 100644--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts@@ -213,13 +213,16 @@ export function refRangeFormula(oldFormulaData: IFormulaData, newFormulaData: IFconst redoFormulaData: Record<string, Record<string, IObjectMatrixPrimitiveType<Nullable<ICellData>>>> = {};const undoFormulaData: Record<string, Record<string, IObjectMatrixPrimitiveType<Nullable<ICellData>>>> = {};- const { unitId: targetUnitId, sheetId } = formulaReferenceMoveParam;+ const { unitId: fromUnitId, sheetId: fromSheetId } = formulaReferenceMoveParam;+ const targetUnitId = formulaReferenceMoveParam.targetUnitId ?? fromUnitId;+ const targetSheetId = formulaReferenceMoveParam.targetSheetId ?? fromSheetId;+ const isCrossSheet = fromUnitId !== targetUnitId || fromSheetId !== targetSheetId;// Iterate over all unitId in oldFormulaDataconst allUnitIds = new Set([...Object.keys(oldFormulaData), ...Object.keys(newFormulaData)]);allUnitIds.forEach((unitId) => {- if (checkFormulaDataNull(oldFormulaData, unitId, sheetId)) {+ if (checkFormulaDataNull(oldFormulaData, unitId, fromSheetId)) {return;}@@ -239,7 +242,7 @@ export function refRangeFormula(oldFormulaData: IFormulaData, newFormulaData: IF// If the sheet where the range is changed is different from the current sheet, the position will not be changed.// Simply get the data from newFormulaMatrix to update the range.- if (unitId !== targetUnitId || currentSheetId !== sheetId) {+ if (isCrossSheet || unitId !== fromUnitId || currentSheetId !== fromSheetId) {rangeList = processFormulaRange(newFormulaMatrix);} else {rangeList = processFormulaChanges(oldFormulaMatrix, newFormulaMatrix, formulaReferenceMoveParam);diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-move.ts b/packages/sheets-formula/src/controllers/utils/ref-range-move.tsindex 0120b52c12..59fec5f5e1 100644--- a/packages/sheets-formula/src/controllers/utils/ref-range-move.ts+++ b/packages/sheets-formula/src/controllers/utils/ref-range-move.ts@@ -57,6 +57,7 @@ export function getNewRangeByMoveParam(currentFormulaSheetId: string,options: {preserveSheetQualifier?: boolean;+ inCrossSheetCutRange?: boolean;} = {}) {const {@@ -80,7 +81,7 @@ export function getNewRangeByMoveParam(refOffsetX,refOffsetY,} = unitRangeWidthOffset;- const { preserveSheetQualifier = false } = options;+ const { preserveSheetQualifier = false, inCrossSheetCutRange = false } = options;if (!checkIsSameUnitAndSheet(@@ -370,7 +371,8 @@ export function getNewRangeByMoveParam(const shouldRewriteSheet = type === FormulaReferenceMoveType.MoveRange&& !!targetSheetId- && targetSheetId !== userSheetId;+ && targetSheetId !== userSheetId+ && !inCrossSheetCutRange;const rewrittenSheetId = shouldRewriteSheet ? targetSheetId : sequenceRangeSheetId;const rewrittenSheetName = shouldRewriteSheet ? (targetSheetName || sequenceRangeSheetName) : sequenceRangeSheetName;const rewrittenUnitId = shouldRewriteSheet ? (targetUnitId || sequenceRangeUnitId) : sequenceRangeUnitId;diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-param.ts b/packages/sheets-formula/src/controllers/utils/ref-range-param.tsindex 11956d6ade..a43856b0d7 100644--- a/packages/sheets-formula/src/controllers/utils/ref-range-param.ts+++ b/packages/sheets-formula/src/controllers/utils/ref-range-param.ts@@ -133,6 +133,7 @@ function handleRefMoveRange(command: ICommandInfo<IMoveRangeCommandParams>, workconst { unitId: currentUnitId, sheetId: currentSheetId } = getCurrentSheetInfo(workbook);const unitId = fromUnitId || toUnitId || currentUnitId;const sheetId = fromSubUnitId || currentSheetId;+ const sheetName = workbook.getSheetBySheetId(sheetId)?.getName();const targetSheetId = toSubUnitId || fromSubUnitId || currentSheetId;const targetUnitId = toUnitId || fromUnitId || currentUnitId;const targetSheetName = workbook.getSheetBySheetId(targetSheetId)?.getName();@@ -143,6 +144,7 @@ function handleRefMoveRange(command: ICommandInfo<IMoveRangeCommandParams>, workto: toRange,unitId,sheetId,+ sheetName,targetUnitId,targetSheetId,targetSheetName,