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(sheets): update formula refs on clipboard cut/paste (#6686)

technical-founder0d373095f051
diff --git a/packages/sheets-filter/src/controllers/sheets-filter.controller.ts b/packages/sheets-filter/src/controllers/sheets-filter.controller.ts
index 5bd847b5f8..6baed7428c 100644
--- a/packages/sheets-filter/src/controllers/sheets-filter.controller.ts
+++ b/packages/sheets-filter/src/controllers/sheets-filter.controller.ts
@@ -591,6 +591,13 @@ export class SheetsFilterController extends Disposable {
private _handleMoveRangeCommand(config: IMoveRangeCommandParams, unitId: string, subUnitId: string) {
const { fromRange, toRange } = config;
+ const sourceSubUnitId = config.fromSubUnitId ?? subUnitId;
+ const targetSubUnitId = config.toSubUnitId ?? sourceSubUnitId;
+
+ if (sourceSubUnitId !== targetSubUnitId && subUnitId !== sourceSubUnitId) {
+ return this._handleNull();
+ }
+
const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
if (!filterModel) {
return this._handleNull();
@@ -622,6 +629,60 @@ export class SheetsFilterController extends Disposable {
const setNewFilterRange = { id: SetSheetsFilterRangeMutation.id, params: { unitId, subUnitId, range: newFilterRange } as ISetSheetsFilterRangeMutationParams };
const setOldFilterRange = { id: SetSheetsFilterRangeMutation.id, params: { unitId, subUnitId, range: filterRange } as ISetSheetsFilterRangeMutationParams };
+ if (sourceSubUnitId !== targetSubUnitId) {
+ const targetFilterModel = this._sheetsFilterService.getFilterModel(unitId, targetSubUnitId);
+ if (targetFilterModel?.getRange()) {
+ return this._handleNull();
+ }
+
+ redos.push(removeFilter, {
+ id: SetSheetsFilterRangeMutation.id,
+ params: { unitId, subUnitId: targetSubUnitId, range: newFilterRange } as ISetSheetsFilterRangeMutationParams,
+ });
+
+ undos.push(
+ {
+ id: RemoveSheetsFilterMutation.id,
+ params: {
+ unitId,
+ subUnitId: targetSubUnitId,
+ },
+ },
+ setOldFilterRange
+ );
+
+ const filterColumn = filterModel.getAllFilterColumns();
+ const moveColDelta = toRange.startColumn - fromRange.startColumn;
+ filterColumn.forEach((column) => {
+ const [col, criteria] = column;
+ if (criteria) {
+ redos.push({
+ id: SetSheetsFilterCriteriaMutation.id,
+ params: {
+ unitId,
+ subUnitId: targetSubUnitId,
+ col: col + moveColDelta,
+ criteria: { ...criteria.serialize(), colId: col + moveColDelta },
+ },
+ });
+ undos.push({
+ id: SetSheetsFilterCriteriaMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ col,
+ criteria: { ...criteria.serialize(), colId: col },
+ },
+ });
+ }
+ });
+
+ return {
+ redos,
+ undos,
+ };
+ }
+
redos.push(removeFilter, setNewFilterRange);
undos.push(removeFilter, setOldFilterRange);
diff --git a/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts
index c0238535d1..7eaa8d4de2 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts
@@ -187,6 +187,13 @@ export class FormulaClipboardController extends Disposable {
};
}
+ if (payload.copyType === COPY_TYPE.CUT && !isSpecialPaste) {
+ return {
+ undos: [],
+ redos: [],
+ };
+ }
+
const workbook = this._getWorkbook();
const unitId = pasteTo.unitId || workbook?.getUnitId();
const subUnitId = pasteTo.subUnitId || workbook?.getActiveSheet()?.getSheetId();
@@ -234,7 +241,7 @@ export function getSetCellFormulaMutations(
},
lexerTreeBuilder: LexerTreeBuilder,
formulaDataModel: FormulaDataModel,
- isSpecialPaste = false,
+ _isSpecialPaste = false,
pasteFrom: ISheetDiscreteRangeLocation | null
) {
const redoMutationsInfo: IMutationInfo[] = [];
diff --git a/packages/sheets-formula/src/controllers/update-defined-name.controller.ts b/packages/sheets-formula/src/controllers/update-defined-name.controller.ts
index acd9b176d2..00efd2afb0 100644
--- a/packages/sheets-formula/src/controllers/update-defined-name.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-defined-name.controller.ts
@@ -161,7 +161,8 @@ export class UpdateDefinedNameController extends Disposable {
sequenceUnitRangeWidthOffset,
moveParams,
unitId,
- sheetId
+ sheetId,
+ { preserveSheetQualifier: true }
);
}
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.ts
index 51a667f85c..d9aed3452d 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,9 @@ describe('getReferenceMoveParams', () => {
type: FormulaReferenceMoveType.MoveRange,
unitId: 'test',
sheetId: 'sheet1',
+ targetUnitId: 'test',
+ targetSheetId: 'sheet1',
+ targetSheetName: 'Sheet1',
from: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },
to: { startRow: 4, endRow: 5, startColumn: 3, endColumn: 4 },
});
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 c824c0f01a..c651b07ea4 100644
--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
@@ -44,6 +44,9 @@ export interface IFormulaReferenceMoveParam {
type: FormulaReferenceMoveType;
unitId: string;
sheetId: string;
+ targetUnitId?: string;
+ targetSheetId?: string;
+ targetSheetName?: string;
range?: IRange;
from?: IRange;
to?: IRange;
diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-move.ts b/packages/sheets-formula/src/controllers/utils/ref-range-move.ts
index b1528b460d..0120b52c12 100644
--- a/packages/sheets-formula/src/controllers/utils/ref-range-move.ts
+++ b/packages/sheets-formula/src/controllers/utils/ref-range-move.ts
@@ -54,9 +54,23 @@ export function getNewRangeByMoveParam(
unitRangeWidthOffset: IUnitRangeWithOffset,
formulaReferenceMoveParam: IFormulaReferenceMoveParam,
currentFormulaUnitId: string,
- currentFormulaSheetId: string
+ currentFormulaSheetId: string,
+ options: {
+ preserveSheetQualifier?: boolean;
+ } = {}
) {
- const { type, unitId: userUnitId, sheetId: userSheetId, range, from, to, rangeFilteredRows } = formulaReferenceMoveParam;
+ const {
+ type,
+ unitId: userUnitId,
+ sheetId: userSheetId,
+ targetUnitId,
+ targetSheetId,
+ targetSheetName,
+ range,
+ from,
+ to,
+ rangeFilteredRows,
+ } = formulaReferenceMoveParam;
const {
range: unitRange,
@@ -66,6 +80,7 @@ export function getNewRangeByMoveParam(
refOffsetX,
refOffsetY,
} = unitRangeWidthOffset;
+ const { preserveSheetQualifier = false } = options;
if (
!checkIsSameUnitAndSheet(
@@ -353,10 +368,23 @@ export function getNewRangeByMoveParam(
return;
}
+ const shouldRewriteSheet = type === FormulaReferenceMoveType.MoveRange
+ && !!targetSheetId
+ && targetSheetId !== userSheetId;
+ const rewrittenSheetId = shouldRewriteSheet ? targetSheetId : sequenceRangeSheetId;
+ const rewrittenSheetName = shouldRewriteSheet ? (targetSheetName || sequenceRangeSheetName) : sequenceRangeSheetName;
+ const rewrittenUnitId = shouldRewriteSheet ? (targetUnitId || sequenceRangeUnitId) : sequenceRangeUnitId;
+ // We need the destination sheet to decide whether a rewritten ref should stay local (`A1`)
+ // or become explicitly qualified (`Sheet2!A1`) after a move.
+ const isCurrentFormulaWorkbook = rewrittenUnitId == null
+ || rewrittenUnitId.length === 0
+ || rewrittenUnitId === currentFormulaUnitId;
+ const isCurrentFormulaSheet = rewrittenSheetId === currentFormulaSheetId;
+
return serializeRangeToRefString({
range: newRange,
- sheetName: sequenceRangeSheetName,
- unitId: sequenceRangeUnitId,
+ sheetName: preserveSheetQualifier || !(isCurrentFormulaWorkbook && isCurrentFormulaSheet) ? rewrittenSheetName : '',
+ unitId: isCurrentFormulaWorkbook ? '' : rewrittenUnitId,
});
}
diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-param.ts b/packages/sheets-formula/src/controllers/utils/ref-range-param.ts
index 6561ad29d0..11956d6ade 100644
--- a/packages/sheets-formula/src/controllers/utils/ref-range-param.ts
+++ b/packages/sheets-formula/src/controllers/utils/ref-range-param.ts
@@ -120,10 +120,22 @@ function handleRefMoveRange(command: ICommandInfo<IMoveRangeCommandParams>, work
const { params } = command;
if (!params) return null;
- const { fromRange, toRange } = params;
+ const {
+ fromRange,
+ toRange,
+ fromUnitId,
+ fromSubUnitId,
+ toUnitId,
+ toSubUnitId,
+ } = params;
if (!fromRange || !toRange) return null;
- const { unitId, sheetId } = getCurrentSheetInfo(workbook);
+ const { unitId: currentUnitId, sheetId: currentSheetId } = getCurrentSheetInfo(workbook);
+ const unitId = fromUnitId || toUnitId || currentUnitId;
+ const sheetId = fromSubUnitId || currentSheetId;
+ const targetSheetId = toSubUnitId || fromSubUnitId || currentSheetId;
+ const targetUnitId = toUnitId || fromUnitId || currentUnitId;
+ const targetSheetName = workbook.getSheetBySheetId(targetSheetId)?.getName();
return {
type: FormulaReferenceMoveType.MoveRange,
@@ -131,6 +143,9 @@ function handleRefMoveRange(command: ICommandInfo<IMoveRangeCommandParams>, work
to: toRange,
unitId,
sheetId,
+ targetUnitId,
+ targetSheetId,
+ targetSheetName,
};
}
diff --git a/packages/sheets-ui/package.json b/packages/sheets-ui/package.json
index c929056e58..0d34d87178 100644
--- a/packages/sheets-ui/package.json
+++ b/packages/sheets-ui/package.json
@@ -95,6 +95,7 @@
},
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
+ "@univerjs/sheets-formula": "workspace:*",
"@univerjs/themes": "workspace:*",
"postcss": "^8.5.8",
"react": "18.3.1",
diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.ts
index 20952f5a3b..510d38e28b 100644
--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts
@@ -20,14 +20,11 @@ import type { IAccessor, IBorderData, ICellData, ICustomRange, IDocumentBody, IM
import type {
IAddWorksheetMergeMutationParams,
IDiscreteRange,
- IMoveRangeMutationParams,
IRemoveWorksheetMergeMutationParams,
ISetRangeValuesMutationParams,
- ISetSelectionsOperationParams,
} from '@univerjs/sheets';
import type { ICellDataWithSpanInfo, ICopyPastePayload, ISheetDiscreteRangeLocation } from '../../services/clipboard/type';
import {
- cellToRange,
CellValueType,
cloneCellData,
cloneCellDataMatrix,
@@ -39,7 +36,6 @@ import {
isTextFormat,
IUniverInstanceService,
ObjectMatrix,
- Range,
Rectangle,
Tools,
willLoseNumericPrecision,
@@ -49,18 +45,12 @@ import {
AddMergeUndoMutationFactory,
AddWorksheetMergeMutation,
discreteRangeToRange,
- getAddMergeMutationRangeByType,
- getPrimaryForRange,
+ getMoveRangeCommandMutations,
getSheetCommandTarget,
- MoveRangeCommand,
- MoveRangeMutation,
RemoveMergeUndoMutationFactory,
RemoveWorksheetMergeMutation,
- SelectionMoveType,
SetRangeValuesMutation,
SetRangeValuesUndoMutationFactory,
- SetSelectionsOperation,
- SheetInterceptorService,
} from '@univerjs/sheets';
import { COPY_TYPE } from '../../services/clipboard/type';
import { isRichText } from '../editor/editing.render-controller';
@@ -151,186 +141,38 @@ export function getMoveRangeMutations(
},
accessor: IAccessor
) {
- let redos: IMutationInfo[] = [];
- let undos: IMutationInfo[] = [];
const { range: fromDiscreteRange, subUnitId: fromSubUnitId, unitId } = from;
const { range: toDiscreteRange, subUnitId: toSubUnitId } = to;
const toRange = toDiscreteRange ? discreteRangeToRange(toDiscreteRange) : null;
const fromRange = fromDiscreteRange ? discreteRangeToRange(fromDiscreteRange) : null;
- if (fromRange && toRange) {
- const univerInstanceService = accessor.get(IUniverInstanceService);
- const sheetInterceptorService = accessor.get(SheetInterceptorService);
- const workbook = univerInstanceService.getUniverSheetInstance(unitId);
- const fromWorksheet = workbook?.getSheetBySheetId(fromSubUnitId);
- const toWorksheet = workbook?.getSheetBySheetId(toSubUnitId);
- if (fromWorksheet && toWorksheet) {
- const fromCellValue = new ObjectMatrix<Nullable<ICellData>>();
- const newFromCellValue = new ObjectMatrix<Nullable<ICellData>>();
- const fromCellMatrix = fromWorksheet.getCellMatrix();
- const toCellMatrix = toWorksheet.getCellMatrix();
-
- Range.foreach(fromRange, (row, col) => {
- fromCellValue.setValue(row, col, cloneCellData(fromCellMatrix.getValue(row, col)));
- newFromCellValue.setValue(row, col, null);
- });
- const toCellValue = new ObjectMatrix<Nullable<ICellData>>();
-
- Range.foreach(toRange, (row, col) => {
- toCellValue.setValue(row, col, cloneCellData(toCellMatrix.getValue(row, col)));
- });
-
- const newToCellValue = new ObjectMatrix<Nullable<ICellData>>();
-
- Range.foreach(fromRange, (row, col) => {
- const cellRange = cellToRange(row, col);
- const relativeRange = Rectangle.getRelativeRange(cellRange, fromRange);
- const range = Rectangle.getPositionRange(relativeRange, toRange);
- newToCellValue.setValue(range.startRow, range.startColumn, fromCellMatrix.getValue(row, col));
- });
-
- const doMoveRangeMutation: IMoveRangeMutationParams = {
- fromRange,
- toRange,
- from: {
- value: newFromCellValue.getMatrix(),
- subUnitId: fromSubUnitId,
- },
- to: {
- value: newToCellValue.getMatrix(),
- subUnitId: toSubUnitId,
- },
- unitId,
- };
- const undoMoveRangeMutation: IMoveRangeMutationParams = {
- fromRange: toRange,
- toRange: fromRange,
- from: {
- value: fromCellValue.getMatrix(),
- subUnitId: fromSubUnitId,
- },
- to: {
- value: toCellValue.getMatrix(),
- subUnitId: toSubUnitId,
- },
- unitId,
- };
- const interceptorCommands = sheetInterceptorService.onCommandExecute({
- id: MoveRangeCommand.id,
- params: { toRange, fromRange },
- });
-
- // handle merge mutations
- const fromMergeData = fromWorksheet.getMergeData();
- const toMergeData = toWorksheet.getMergeData();
- const fromMergeRanges = fromMergeData.filter((item) => Rectangle.intersects(item, fromRange));
- const toMergeRanges = toMergeData.filter((item) => Rectangle.intersects(item, toRange));
- const mergeRedos: Array<{
- id: string;
- params: IAddWorksheetMergeMutationParams | IRemoveWorksheetMergeMutationParams;
- }> = [];
- const mergeUndos: Array<{
- id: string;
- params: IAddWorksheetMergeMutationParams | IRemoveWorksheetMergeMutationParams;
- }> = [];
-
- if (fromMergeRanges.length > 0 || toMergeRanges.length > 0) {
- const willMoveToMergeRanges = fromMergeRanges
- .map((mergeRange) => Rectangle.getRelativeRange(mergeRange, fromRange))
- .map((relativeRange) => Rectangle.getPositionRange(relativeRange, toRange));
- const addMergeCellRanges = getAddMergeMutationRangeByType(willMoveToMergeRanges);
-
- if (fromMergeRanges.length > 0) {
- mergeRedos.push({
- id: RemoveWorksheetMergeMutation.id,
- params: {
- unitId,
- subUnitId: fromSubUnitId,
- ranges: fromMergeRanges,
- },
- });
- mergeUndos.push({
- id: AddWorksheetMergeMutation.id,
- params: {
- unitId,
- subUnitId: fromSubUnitId,
- ranges: fromMergeRanges,
- },
- });
- }
-
- if (toMergeRanges.length > 0) {
- mergeRedos.push({
- id: RemoveWorksheetMergeMutation.id,
- params: {
- unitId,
- subUnitId: fromSubUnitId,
- ranges: toMergeRanges,
- },
- });
- mergeUndos.push({
- id: AddWorksheetMergeMutation.id,
- params: {
- unitId,
- subUnitId: toSubUnitId,
- ranges: toMergeRanges,
- },
- });
- }
+ if (!fromRange || !toRange) {
+ return {
+ undos: [],
+ redos: [],
+ };
+ }
- mergeRedos.push({
- id: AddWorksheetMergeMutation.id,
- params: {
- unitId,
- subUnitId: toSubUnitId,
- ranges: addMergeCellRanges,
- },
- });
- mergeUndos.unshift({
- id: RemoveWorksheetMergeMutation.id,
- params: {
- unitId,
- subUnitId: toSubUnitId,
- ranges: addMergeCellRanges,
- },
- });
- }
+ const moveRangeMutations = getMoveRangeCommandMutations(accessor, {
+ fromRange,
+ toRange,
+ fromUnitId: unitId,
+ fromSubUnitId,
+ toUnitId: to.unitId,
+ toSubUnitId,
+ }, {
+ includeAutoHeight: false,
+ });
- redos = [
- { id: MoveRangeMutation.id, params: doMoveRangeMutation },
- ...interceptorCommands.redos,
- ...mergeRedos,
- {
- id: SetSelectionsOperation.id,
- params: {
- unitId,
- subUnitId: toSubUnitId,
- selections: [{ range: toRange, primary: getPrimaryForRange(toRange, toWorksheet) }],
- type: SelectionMoveType.MOVE_END,
- } as ISetSelectionsOperationParams,
- },
- ];
- undos = [
- { id: MoveRangeMutation.id, params: undoMoveRangeMutation },
- ...interceptorCommands.undos,
- ...mergeUndos,
- {
- id: SetSelectionsOperation.id,
- params: {
- unitId,
- subUnitId: fromSubUnitId,
- type: SelectionMoveType.MOVE_END,
- selections: [{ range: fromRange, primary: getPrimaryForRange(fromRange, fromWorksheet) }],
- },
- },
- ];
+ return moveRangeMutations
+ ? {
+ undos: moveRangeMutations.undos,
+ redos: moveRangeMutations.redos,
}
- }
-
- return {
- undos,
- redos,
- };
+ : {
+ undos: [],
+ redos: [],
+ };
}
/**
@@ -423,16 +265,17 @@ export function getSetCellValueMutations(
/**
*
* @param pasteTo
+ * @param pasteFrom
* @param matrix
* @param accessor
- * @param withRichFormat
+ * @param _withRichFormat
*/
export function getSetCellStyleMutations(
pasteTo: ISheetDiscreteRangeLocation,
pasteFrom: Nullable<ISheetDiscreteRangeLocation>,
matrix: ObjectMatrix<ICellDataWithSpanInfo>,
accessor: IAccessor,
- withRichFormat = false
+ _withRichFormat = false
) {
const redoMutationsInfo: IMutationInfo[] = [];
const undoMutationsInfo: IMutationInfo[] = [];
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
index df99af71a7..d3fa8a36ed 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
@@ -14,9 +14,11 @@
* limitations under the License.
*/
-import type { ICellData, Injector, IRange, IStyleData, Nullable, Univer } from '@univerjs/core';
+import type { ICellData, Injector, IRange, IStyleData, IWorkbookData, Nullable, ObjectMatrix, Univer } from '@univerjs/core';
+import type { ICellDataWithSpanInfo } from '../type';
import type { IClipboardItem } from './mock-clipboard';
-import { ICommandService, IUniverInstanceService, RANGE_TYPE, Rectangle, RedoCommand, UndoCommand } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE, Rectangle, RedoCommand, UndoCommand } from '@univerjs/core';
+import { SetArrayFormulaDataMutation, SetFormulaDataMutation } from '@univerjs/engine-formula';
import {
AddWorksheetMergeMutation,
discreteRangeToRange,
@@ -29,12 +31,26 @@ import {
SetWorksheetRowHeightMutation,
SheetsSelectionsService,
} from '@univerjs/sheets';
+import { UpdateFormulaController } from '@univerjs/sheets-formula';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { ISheetClipboardService, PREDEFINED_HOOK_NAME_PASTE } from '../clipboard.service';
import { COPY_TYPE } from '../type';
import { clipboardTestBed } from './clipboard-test-bed';
import { MockClipboard } from './mock-clipboard';
+interface ITestSheetClipboardService extends ISheetClipboardService {
+ _generateCopyContent: (
+ unitId: string,
+ subUnitId: string,
+ range: IRange,
+ hooks: unknown[]
+ ) => {
+ matrixFragment: Nullable<ObjectMatrix<ICellDataWithSpanInfo>>;
+ copyId: string;
+ };
+ _pasteInternal: (copyId: string, pasteType: string) => Promise<boolean>;
+}
+
describe('Test clipboard', () => {
let univer: Univer;
let get: Injector['get'];
@@ -153,7 +169,6 @@ describe('Test clipboard', () => {
const values = getValues(startRow, startColumn, endRow, endColumn);
const styles = getStyles(startRow, startColumn, endRow, endColumn);
const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
- const rowManager = get(IUniverInstanceService).getUniverSheetInstance('test')?.getSheetBySheetId('sheet1')?.getRowManager();
const columnManager = get(IUniverInstanceService).getUniverSheetInstance('test')?.getSheetBySheetId('sheet1')?.getColumnManager();
const columnWidth = columnManager?.getColumnWidth(0);
expect(columnWidth).toBe(88);
@@ -1116,8 +1131,9 @@ describe('Test clipboard', () => {
const subUnitId = 'sheet1';
const fromRange = { rows: [24], cols: [0] };
const toRange = { startRow: 24, startColumn: 1, endRow: 24, endColumn: 1 };
+ const testSheetClipboardService = sheetClipboardService as ITestSheetClipboardService;
const copyContentCache = sheetClipboardService.copyContentCache();
- const { matrixFragment, copyId } = (sheetClipboardService as any)._generateCopyContent(unitId, subUnitId, discreteRangeToRange(fromRange), []);
+ const { matrixFragment, copyId } = testSheetClipboardService._generateCopyContent(unitId, subUnitId, discreteRangeToRange(fromRange), []);
// cache the copy content for internal paste
copyContentCache.set(copyId, {
@@ -1138,7 +1154,7 @@ describe('Test clipboard', () => {
},
]);
- (sheetClipboardService as any)._pasteInternal(copyId, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE);
+ testSheetClipboardService._pasteInternal(copyId, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE);
expect(getValues(24, 0, 24, 0)![0][0]).toBe(null);
expect(getValues(24, 1, 24, 1)![0][0]!.v).toBe('A25');
@@ -1155,3 +1171,295 @@ describe('Test clipboard', () => {
});
});
});
+
+function createFormulaClipboardWorkbookData(): IWorkbookData {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: ['sheet1', 'sheet2'],
+ styles: {},
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'Sheet1',
+ cellData: {
+ 0: {
+ 0: { v: 1 },
+ 1: { v: 2 },
+ 2: { f: '=A1' },
+ 3: { f: '=SUM(A1:B2)' },
+ 4: { f: '=$A1' },
+ 5: { f: '=A$1' },
+ 6: { f: '=$A$1' },
+ 7: { f: '=B1' },
+ 8: { f: '=H1' },
+ 9: { f: '=F3' },
+ 10: { f: '=A1', si: 'shared-ref' },
+ },
+ 1: {
+ 0: { v: 3 },
+ 1: { v: 4 },
+ 10: { si: 'shared-ref' },
+ },
+ 2: {
+ 0: { v: 'label' },
+ 1: { v: 7 },
+ 2: { f: '=B3' },
+ 3: { f: '=C3+1' },
+ 4: { v: 11 },
+ 5: { f: '=SUM(B3:E3)' },
+ },
+ },
+ },
+ sheet2: {
+ id: 'sheet2',
+ name: 'Sheet2',
+ cellData: {
+ 0: {
+ 0: { f: '=Sheet1!A1' },
+ 1: { f: '=Sheet1!H1' },
+ },
+ },
+ },
+ },
+ };
+}
+
+describe('Test cut command with formulas', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let sheetClipboardService: ISheetClipboardService;
+ let getValues: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number,
+ sheetId?: string
+ ) => Array<Array<Nullable<ICellData>>> | undefined;
+
+ beforeEach(() => {
+ const testBed = clipboardTestBed(createFormulaClipboardWorkbookData(), [
+ [UpdateFormulaController],
+ ]);
+
+ univer = testBed.univer;
+ get = testBed.get;
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(SetSelectionsOperation);
+ commandService.registerCommand(MoveRangeMutation);
+ commandService.registerCommand(SetWorksheetRowAutoHeightMutation);
+ commandService.registerCommand(SetFormulaDataMutation);
+ commandService.registerCommand(SetArrayFormulaDataMutation);
+ sheetClipboardService = get(ISheetClipboardService);
+
+ get(UpdateFormulaController);
+
+ getValues = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number,
+ sheetId: string = 'sheet1'
+ ): Array<Array<Nullable<ICellData>>> | undefined =>
+ get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId(sheetId)
+ ?.getRange(startRow, startColumn, endRow, endColumn)
+ .getValues();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ async function cutPaste(
+ fromRange: { rows: number[]; cols: number[] },
+ toRange: { startRow: number; startColumn: number; endRow: number; endColumn: number },
+ fromSubUnitId: string = 'sheet1',
+ toSubUnitId: string = fromSubUnitId
+ ) {
+ const testSheetClipboardService = sheetClipboardService as ITestSheetClipboardService;
+ const copyContentCache = sheetClipboardService.copyContentCache();
+ const workbook = get(IUniverInstanceService).getUniverSheetInstance('test');
+ const targetWorksheet = workbook?.getSheetBySheetId(toSubUnitId);
+
+ if (targetWorksheet) {
+ workbook?.setActiveSheet(targetWorksheet);
+ }
+
+ const { matrixFragment, copyId } = testSheetClipboardService._generateCopyContent(
+ 'test',
+ fromSubUnitId,
+ discreteRangeToRange(fromRange),
+ []
+ );
+
+ copyContentCache.set(copyId, {
+ unitId: 'test',
+ subUnitId: fromSubUnitId,
+ range: fromRange,
+ matrix: matrixFragment,
+ copyType: COPY_TYPE.CUT,
+ });
+
+ get(SheetsSelectionsService).addSelections([
+ {
+ range: { ...toRange, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await testSheetClipboardService._pasteInternal(copyId, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE);
+ }
+
+ it('cut-moving a referenced value range updates direct, range, mixed-absolute, cross-sheet, and shared formulas', async () => {
+ await cutPaste(
+ { rows: [0, 1], cols: [0, 1] },
+ { startRow: 3, startColumn: 3, endRow: 4, endColumn: 4 }
+ );
+
+ expect(getValues(0, 0, 1, 1)).toStrictEqual([
+ [null, null],
+ [null, null],
+ ]);
+ expect(getValues(3, 3, 4, 4)).toStrictEqual([
+ [{ v: 1 }, { v: 2 }],
+ [{ v: 3 }, { v: 4 }],
+ ]);
+
+ expect(getValues(0, 2, 0, 6)).toStrictEqual([
+ [
+ { f: '=D4' },
+ { f: '=SUM(D4:E5)' },
+ { f: '=$D4' },
+ { f: '=D$4' },
+ { f: '=$D$4' },
+ ],
+ ]);
+ expect(getValues(0, 10, 1, 10)).toStrictEqual([
+ [{ f: '=D4' }],
+ [{ f: '=D5' }],
+ ]);
+ expect(getValues(0, 0, 0, 1, 'sheet2')).toStrictEqual([
+ [{ f: '=Sheet1!D4' }, { f: '=Sheet1!H1' }],
+ ]);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(0, 2, 0, 6)).toStrictEqual([
+ [
+ { f: '=A1' },
+ { f: '=SUM(A1:B2)' },
+ { f: '=$A1' },
+ { f: '=A$1' },
+ { f: '=$A$1' },
+ ],
+ ]);
+ expect(getValues(0, 10, 1, 10)).toStrictEqual([
+ [{ f: '=A1', si: 'shared-ref' }],
+ [{ si: 'shared-ref' }],
+ ]);
+ expect(getValues(0, 0, 0, 1, 'sheet2')).toStrictEqual([
+ [{ f: '=Sheet1!A1' }, { f: '=Sheet1!H1' }],
+ ]);
+ });
+
+ it('cut-pasting a referenced value range across sheets adds and removes sheet qualifiers correctly', async () => {
+ await cutPaste(
+ { rows: [0, 1], cols: [0, 1] },
+ { startRow: 2, startColumn: 2, endRow: 3, endColumn: 3 },
+ 'sheet1',
+ 'sheet2'
+ );
+
+ expect(getValues(0, 0, 1, 1)).toStrictEqual([
+ [null, null],
+ [null, null],
+ ]);
+ expect(getValues(2, 2, 3, 3, 'sheet2')).toStrictEqual([
+ [{ v: 1 }, { v: 2 }],
+ [{ v: 3 }, { v: 4 }],
+ ]);
+
+ expect(getValues(0, 2, 0, 6)).toStrictEqual([
+ [
+ { f: '=Sheet2!C3' },
+ { f: '=SUM(Sheet2!C3:D4)' },
+ { f: '=Sheet2!$C3' },
+ { f: '=Sheet2!C$3' },
+ { f: '=Sheet2!$C$3' },
+ ],
+ ]);
+ expect(getValues(0, 0, 0, 1, 'sheet2')).toStrictEqual([
+ [{ f: '=C3' }, { f: '=Sheet1!H1' }],
+ ]);
+ });
+
+ it('cut-moving a formula cell keeps its formula text stable while dependents update to the new address', async () => {
+ await cutPaste(
+ { rows: [0], cols: [7] },
+ { startRow: 3, startColumn: 9, endRow: 3, endColumn: 9 }
+ );
+
+ expect(getValues(0, 7, 0, 8)).toStrictEqual([
+ [null, { f: '=J4' }],
+ ]);
+ expect(getValues(3, 9, 3, 9)).toStrictEqual([
+ [{ f: '=B1' }],
+ ]);
+ expect(getValues(0, 0, 0, 1, 'sheet2')).toStrictEqual([
+ [{ f: '=Sheet1!A1' }, { f: '=Sheet1!J4' }],
+ ]);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(0, 7, 0, 8)).toStrictEqual([
+ [{ f: '=B1' }, { f: '=H1' }],
+ ]);
+ expect(getValues(0, 0, 0, 1, 'sheet2')).toStrictEqual([
+ [{ f: '=Sheet1!A1' }, { f: '=Sheet1!H1' }],
+ ]);
+ });
+
+ it('cut-moving a larger mixed value, text, and formula range preserves moved formulas and updates dependents', async () => {
+ await cutPaste(
+ { rows: [2], cols: [0, 1, 2, 3, 4, 5] },
+ { startRow: 5, startColumn: 0, endRow: 5, endColumn: 5 }
+ );
+
+ expect(getValues(2, 0, 2, 5)).toStrictEqual([
+ [null, null, null, null, null, null],
+ ]);
+ expect(getValues(5, 0, 5, 5)).toStrictEqual([
+ [
+ { v: 'label' },
+ { v: 7 },
+ { f: '=B6' },
+ { f: '=C6+1' },
+ { v: 11 },
+ { f: '=SUM(B6:E6)' },
+ ],
+ ]);
+ expect(getValues(0, 9, 0, 9)).toStrictEqual([
+ [{ f: '=F6' }],
+ ]);
+
+ 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(0, 9, 0, 9)).toStrictEqual([
+ [{ f: '=F3' }],
+ ]);
+ });
+});
diff --git a/packages/sheets/src/commands/commands/move-range.command.ts b/packages/sheets/src/commands/commands/move-range.command.ts
index a86df54574..9ae1191d6c 100644
--- a/packages/sheets/src/commands/commands/move-range.command.ts
+++ b/packages/sheets/src/commands/commands/move-range.command.ts
@@ -42,95 +42,56 @@ import { getSheetCommandTarget } from './utils/target-util';
export interface IMoveRangeCommandParams {
toRange: IRange;
fromRange: IRange;
+ fromUnitId?: string;
+ fromSubUnitId?: string;
+ toUnitId?: string;
+ toSubUnitId?: string;
}
export const MoveRangeCommandId = 'sheet.command.move-range';
+interface IResolvedMoveRangeContext {
+ unitId: string;
+ fromSubUnitId: string;
+ toSubUnitId: string;
+ fromWorksheet: Worksheet;
+ toWorksheet: Worksheet;
+}
+
+interface IGetMoveRangeCommandMutationsOptions {
+ includeSelection?: boolean;
+ includeAfterCommand?: boolean;
+ includeAutoHeight?: boolean;
+}
+
export const MoveRangeCommand: ICommand = {
type: CommandType.COMMAND,
id: MoveRangeCommandId,
-
- // eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params: IMoveRangeCommandParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
- const univerInstanceService = accessor.get(IUniverInstanceService);
const errorService = accessor.get(ErrorService);
const localeService = accessor.get(LocaleService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
- const target = getSheetCommandTarget(univerInstanceService);
- if (!target) return false;
-
const perform = await sheetInterceptorService.beforeCommandExecute({ id: MoveRangeCommand.id, params });
if (!perform) {
return false;
}
- const { worksheet, subUnitId, unitId } = target;
- const moveRangeMutations = getMoveRangeUndoRedoMutations(
- accessor,
- { unitId, subUnitId, range: params.fromRange },
- { unitId, subUnitId, range: params.toRange }
- );
- if (moveRangeMutations === null) {
+ const moveRangeCommandMutations = getMoveRangeCommandMutations(accessor, params);
+ if (!moveRangeCommandMutations) {
errorService.emit(localeService.t('sheets.info.acrossMergedCell'));
return false;
}
- const interceptorCommands = sheetInterceptorService.onCommandExecute({
- id: MoveRangeCommand.id,
- params,
- });
-
- const redos = [
- ...(interceptorCommands.preRedos ?? []),
- ...moveRangeMutations.redos,
- ...interceptorCommands.redos,
- {
- id: SetSelectionsOperation.id,
- params: {
- unitId,
- subUnitId,
- selections: [{ range: params.toRange, primary: getPrimaryAfterMove(params.fromRange, params.toRange, worksheet) }],
- type: SelectionMoveType.MOVE_END,
- } as ISetSelectionsOperationParams,
- },
- ];
- const undos = [
- ...(interceptorCommands.preUndos ?? []),
- ...moveRangeMutations.undos,
- ...interceptorCommands.undos,
- {
- id: SetSelectionsOperation.id,
- params: {
- unitId,
- subUnitId,
- selections: [{ range: params.fromRange, primary: getPrimaryForRange(params.fromRange, worksheet) }],
- type: SelectionMoveType.MOVE_END,
- } as ISetSelectionsOperationParams,
- },
- ];
-
- const result = sequenceExecute(redos, commandService).result;
+ const result = sequenceExecute(moveRangeCommandMutations.redos, commandService).result;
if (result) {
- const { undos: autoHeightUndos, redos: autoHeightRedos } = sheetInterceptorService.generateMutationsOfAutoHeight({
- unitId,
- subUnitId,
- ranges: [params.fromRange, params.toRange],
- });
-
- const afterInterceptors = sheetInterceptorService.afterCommandExecute({
- id: MoveRangeCommand.id,
- params,
- });
-
- sequenceExecute([...afterInterceptors.redos, ...autoHeightRedos], commandService);
undoRedoService.pushUndoRedo({
- unitID: unitId,
- undoMutations: [...undos, ...afterInterceptors.undos, ...autoHeightUndos],
- redoMutations: [...redos, ...afterInterceptors.redos, ...autoHeightRedos],
+ unitID: moveRangeCommandMutations.unitId,
+ undoMutations: moveRangeCommandMutations.undos,
+ redoMutations: moveRangeCommandMutations.redos,
});
return true;
}
@@ -138,6 +99,129 @@ export const MoveRangeCommand: ICommand = {
},
};
+function _resolveMoveRangeContext(accessor: IAccessor, params: IMoveRangeCommandParams): IResolvedMoveRangeContext | null {
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const target = getSheetCommandTarget(univerInstanceService);
+
+ const unitId = params.toUnitId ?? params.fromUnitId ?? target?.unitId;
+ const fromSubUnitId = params.fromSubUnitId ?? target?.subUnitId;
+ const toSubUnitId = params.toSubUnitId ?? params.fromSubUnitId ?? target?.subUnitId;
+
+ if (!unitId || !fromSubUnitId || !toSubUnitId) {
+ return null;
+ }
+
+ if (params.fromUnitId && params.toUnitId && params.fromUnitId !== params.toUnitId) {
+ return null;
+ }
+
+ const workbook = univerInstanceService.getUniverSheetInstance(unitId);
+ const fromWorksheet = workbook?.getSheetBySheetId(fromSubUnitId);
+ const toWorksheet = workbook?.getSheetBySheetId(toSubUnitId);
+
+ if (!fromWorksheet || !toWorksheet) {
+ return null;
+ }
+
+ return {
+ unitId,
+ fromSubUnitId,
+ toSubUnitId,
+ fromWorksheet,
+ toWorksheet,
+ };
+}
+
+export function getMoveRangeCommandMutations(
+ accessor: IAccessor,
+ params: IMoveRangeCommandParams,
+ options: IGetMoveRangeCommandMutationsOptions = {}
+) {
+ const {
+ includeSelection = true,
+ includeAfterCommand = true,
+ includeAutoHeight = true,
+ } = options;
+
+ const context = _resolveMoveRangeContext(accessor, params);
+ if (!context) {
+ return null;
+ }
+
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
+ const { unitId, fromSubUnitId, toSubUnitId, fromWorksheet, toWorksheet } = context;
+
+ const moveRangeMutations = getMoveRangeUndoRedoMutations(
+ accessor,
+ { unitId, subUnitId: fromSubUnitId, range: params.fromRange },
+ { unitId, subUnitId: toSubUnitId, range: params.toRange }
+ );
+ if (moveRangeMutations === null) {
+ return null;
+ }
+
+ const commandInfo = {
+ id: MoveRangeCommand.id,
+ params,
+ };
+
+ const interceptorCommands = sheetInterceptorService.onCommandExecute(commandInfo);
+ const redos = [
+ ...(interceptorCommands.preRedos ?? []),
+ ...moveRangeMutations.redos,
+ ...interceptorCommands.redos,
+ ];
+ const undos = [
+ ...(interceptorCommands.preUndos ?? []),
+ ...moveRangeMutations.undos,
+ ...interceptorCommands.undos,
+ ];
+
+ if (includeSelection) {
+ redos.push({
+ id: SetSelectionsOperation.id,
+ params: {
+ unitId,
+ subUnitId: toSubUnitId,
+ selections: [{ range: params.toRange, primary: getPrimaryAfterMove(params.fromRange, params.toRange, fromWorksheet, toWorksheet) }],
+ type: SelectionMoveType.MOVE_END,
+ } as ISetSelectionsOperationParams,
+ });
+ undos.push({
+ id: SetSelectionsOperation.id,
+ params: {
+ unitId,
+ subUnitId: fromSubUnitId,
+ selections: [{ range: params.fromRange, primary: getPrimaryForRange(params.fromRange, fromWorksheet) }],
+ type: SelectionMoveType.MOVE_END,
+ } as ISetSelectionsOperationParams,
+ });
+ }
+
+ if (includeAfterCommand) {
+ const afterInterceptors = sheetInterceptorService.afterCommandExecute(commandInfo);
+ redos.push(...afterInterceptors.redos);
+ undos.push(...afterInterceptors.undos);
+ }
+
+ if (includeAutoHeight) {
+ const { undos: autoHeightUndos, redos: autoHeightRedos } = sheetInterceptorService.generateMutationsOfAutoHeight({
+ unitId,
+ subUnitId: toSubUnitId,
+ ranges: fromSubUnitId === toSubUnitId ? [params.fromRange, params.toRange] : [params.toRange],
+ });
+
+ redos.push(...autoHeightRedos);
+ undos.push(...autoHeightUndos);
+ }
+
+ return {
+ unitId,
+ redos,
+ undos,
+ };
+}
+
export interface IRangeUnit {
unitId: string;
subUnitId: string;
@@ -240,12 +324,12 @@ export function getMoveRangeUndoRedoMutations(
// Before moveRange is executed, the target area has no merge cell yet.
// So need to get the merge info of the start cell and then transform it
-function getPrimaryAfterMove(fromRange: IRange, toRange: IRange, worksheet: Worksheet): ISelectionCell {
+function getPrimaryAfterMove(fromRange: IRange, toRange: IRange, sourceWorksheet: Worksheet, targetWorksheet: Worksheet = sourceWorksheet): ISelectionCell {
const startRow = fromRange.startRow;
const startColumn = fromRange.startColumn;
- const mergeInfo = worksheet.getMergedCell(startRow, startColumn);
+ const mergeInfo = sourceWorksheet.getMergedCell(startRow, startColumn);
- const res = getPrimaryForRange(toRange, worksheet);
+ const res = getPrimaryForRange(toRange, targetWorksheet);
if (mergeInfo) {
const mergeRowCount = mergeInfo.endRow - mergeInfo.startRow + 1;
const mergeColCount = mergeInfo.endColumn - mergeInfo.startColumn + 1;
diff --git a/packages/sheets/src/controllers/merge-cell.controller.ts b/packages/sheets/src/controllers/merge-cell.controller.ts
index 18e0bd1889..fabe3b8255 100644
--- a/packages/sheets/src/controllers/merge-cell.controller.ts
+++ b/packages/sheets/src/controllers/merge-cell.controller.ts
@@ -418,80 +418,96 @@ export class MergeCellController extends Disposable {
if (!workbook) {
return this._handleNull();
}
- const worksheet = getWorksheet(workbook, subUnitId);
- if (!worksheet) {
+
+ const sourceSubUnitId = params.fromSubUnitId ?? subUnitId;
+ const targetSubUnitId = params.toSubUnitId ?? sourceSubUnitId;
+ const sourceWorksheet = getWorksheet(workbook, sourceSubUnitId);
+ const targetWorksheet = getWorksheet(workbook, targetSubUnitId);
+ if (!sourceWorksheet || !targetWorksheet) {
return this._handleNull();
}
- const mergeData = worksheet.getMergeData();
- const fromMergeRanges = mergeData.filter((item) => Rectangle.intersects(item, params.fromRange));
- const toMergeRanges = mergeData.filter((item) => Rectangle.intersects(item, params.toRange));
+
+ const fromMergeRanges = sourceWorksheet.getMergeData().filter((item) => Rectangle.intersects(item, params.fromRange));
+ const toMergeRanges = targetWorksheet.getMergeData().filter((item) => Rectangle.intersects(item, params.toRange));
const willMoveToMergeRanges = fromMergeRanges
.map((mergeRange) => Rectangle.getRelativeRange(mergeRange, params.fromRange))
.map((relativeRange) => Rectangle.getPositionRange(relativeRange, params.toRange));
const addMergeCellRanges = getAddMergeMutationRangeByType(willMoveToMergeRanges).filter(
- (range) => !mergeData.some((mergeRange) => Rectangle.equals(range, mergeRange))
+ (range) => !targetWorksheet.getMergeData().some((mergeRange) => Rectangle.equals(range, mergeRange))
);
const redos: Array<{
id: string;
params: IAddWorksheetMergeMutationParams | IRemoveWorksheetMergeMutationParams;
- }> = [
- {
+ }> = [];
+ const undos: Array<{
+ id: string;
+ params: IAddWorksheetMergeMutationParams | IRemoveWorksheetMergeMutationParams;
+ }> = [];
+
+ if (subUnitId === sourceSubUnitId && fromMergeRanges.length > 0) {
+ redos.push({
id: RemoveWorksheetMergeMutation.id,
params: {
unitId,
- subUnitId,
+ subUnitId: sourceSubUnitId,
ranges: fromMergeRanges,
},
- },
- {
- id: RemoveWorksheetMergeMutation.id,
- params: {
- unitId,
- subUnitId,
- ranges: toMergeRanges,
- },
- },
- {
+ });
+ undos.push({
id: AddWorksheetMergeMutation.id,
params: {
unitId,
- subUnitId,
- ranges: addMergeCellRanges,
+ subUnitId: sourceSubUnitId,
+ ranges: fromMergeRanges,
},
- },
- ];
- const undos: Array<{
- id: string;
- params: IAddWorksheetMergeMutationParams | IRemoveWorksheetMergeMutationParams;
- }> = [
- {
+ });
+ }
+
+ if (subUnitId === targetSubUnitId && toMergeRanges.length > 0) {
+ redos.push({
id: RemoveWorksheetMergeMutation.id,
params: {
unitId,
- subUnitId,
- ranges: addMergeCellRanges,
+ subUnitId: targetSubUnitId,
+ ranges: toMergeRanges,
},
- },
- {
+ });
+ undos.push({
id: AddWorksheetMergeMutation.id,
params: {
unitId,
- subUnitId,
+ subUnitId: targetSubUnitId,
ranges: toMergeRanges,
},
- },
- {
+ });
+ }
+
+ if (subUnitId === targetSubUnitId && addMergeCellRanges.length > 0) {
+ redos.push({
id: AddWorksheetMergeMutation.id,
params: {
unitId,
- subUnitId,
- ranges: fromMergeRanges,
+ subUnitId: targetSubUnitId,
+ ranges: addMergeCellRanges,
},
- },
- ];
+ });
+ undos.unshift({
+ id: RemoveWorksheetMergeMutation.id,
+ params: {
+ unitId,
+ subUnitId: targetSubUnitId,
+ ranges: addMergeCellRanges,
+ },
+ });
+ }
+
+ if (redos.length === 0) {
+ return this._handleNull();
+ }
+
return { redos, undos };
}
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index 7bad97f5ac..cc40d360bf 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -101,7 +101,7 @@ export {
InsertRowCommand,
} from './commands/commands/insert-row-col.command';
export { type IInsertSheetCommandParams, InsertSheetCommand } from './commands/commands/insert-sheet.command';
-export { getMoveRangeUndoRedoMutations, type IMoveRangeCommandParams, MoveRangeCommand } from './commands/commands/move-range.command';
+export { getMoveRangeCommandMutations, getMoveRangeUndoRedoMutations, type IMoveRangeCommandParams, MoveRangeCommand } from './commands/commands/move-range.command';
export {
type IMoveColsCommandParams,
type IMoveRowsCommandParams,
diff --git a/packages/sheets/src/services/ref-range/ref-range.service.ts b/packages/sheets/src/services/ref-range/ref-range.service.ts
index 953e325711..16a649f929 100644
--- a/packages/sheets/src/services/ref-range/ref-range.service.ts
+++ b/packages/sheets/src/services/ref-range/ref-range.service.ts
@@ -209,16 +209,49 @@ export class RefRangeService extends Disposable {
}
case EffectRefRangId.MoveRangeCommandId: {
const params = command.params as IMoveRangeCommandParams;
- const target = getSheetCommandTarget(this._univerInstanceService);
- if (!target) return [];
-
- const { unitId, subUnitId } = target;
+ const sourceTarget = getSheetCommandTarget(this._univerInstanceService, {
+ unitId: params.fromUnitId,
+ subUnitId: params.fromSubUnitId,
+ });
+ const destinationTarget = getSheetCommandTarget(this._univerInstanceService, {
+ unitId: params.toUnitId ?? params.fromUnitId,
+ subUnitId: params.toSubUnitId ?? params.fromSubUnitId,
+ });
+ if (!sourceTarget && !destinationTarget) return [];
+
+ if (
+ sourceTarget
+ && destinationTarget
+ && sourceTarget.unitId === destinationTarget.unitId
+ && sourceTarget.subUnitId === destinationTarget.subUnitId
+ ) {
+ return this._checkRange(
+ [params.fromRange, params.toRange],
+ sourceTarget.unitId,
+ sourceTarget.subUnitId
+ );
+ }
- return this._checkRange(
- [params.fromRange, params.toRange],
- unitId,
- subUnitId
- );
+ const effects = [];
+ if (sourceTarget) {
+ effects.push(
+ ...this._checkRange(
+ [params.fromRange],
+ sourceTarget.unitId,
+ sourceTarget.subUnitId
+ )
+ );
+ }
+ if (destinationTarget) {
+ effects.push(
+ ...this._checkRange(
+ [params.toRange],
+ destinationTarget.unitId,
+ destinationTarget.subUnitId
+ )
+ );
+ }
+ return effects;
}
case EffectRefRangId.InsertRowCommandId: {
const params = command.params as IInsertRowCommandParams;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 17b6c61275..021c3cc2fc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2623,6 +2623,9 @@ importers:
'@univerjs-infra/shared':
specifier: workspace:*
version: link:../../common/shared
+ '@univerjs/sheets-formula':
+ specifier: workspace:*
+ version: link:../sheets-formula
'@univerjs/themes':
specifier: workspace:*
version: link:../themes