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
feat(sheet): remove rows & cols (#236)
Wenzhao Hufd3812535418
diff --git a/packages/base-sheets/src/Basics/Interfaces/MutationInterface.ts b/packages/base-sheets/src/Basics/Interfaces/MutationInterface.tsindex 9bc7880f35..f529ced1b3 100644--- a/packages/base-sheets/src/Basics/Interfaces/MutationInterface.ts+++ b/packages/base-sheets/src/Basics/Interfaces/MutationInterface.ts@@ -56,7 +56,7 @@ export interface IRemoveColMutationParams {export interface IDeleteRangeMutationParams {workbookId: string;worksheetId: string;- range: IRange[];+ ranges: IRange[];shiftDimension: Dimension;}@@ -64,7 +64,7 @@ export interface IDeleteRangeMutationParams {export interface IInsertRangeMutationParams {workbookId: string;worksheetId: string;- range: IRange[];+ ranges: IRange[];shiftDimension: Dimension;cellValue: ObjectMatrixPrimitiveType<ICellData>;}diff --git a/packages/base-sheets/src/commands/commands/__tests__/insert-remove-row-col.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/insert-remove-row-col.spec.tsnew file mode 100644index 0000000000..606a344424--- /dev/null+++ b/packages/base-sheets/src/commands/commands/__tests__/insert-remove-row-col.spec.ts@@ -0,0 +1,346 @@+/* eslint-disable no-magic-numbers */+import {+ ICellData,+ ICommandService,+ ICurrentUniverService,+ IRange,+ IStyleData,+ IWorkbookConfig,+ LocaleType,+ Nullable,+ RANGE_TYPE,+ RedoCommand,+ Tools,+ UndoCommand,+ Univer,+} from '@univerjs/core';+import { Injector } from '@wendellhu/redi';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';+import { AddWorksheetMergeMutation } from '../../mutations/add-worksheet-merge.mutation';+import { DeleteRangeMutation } from '../../mutations/delete-range.mutation';+import { InsertRangeMutation } from '../../mutations/insert-range.mutation';+import { InsertColMutation, InsertRowMutation } from '../../mutations/insert-row-col.mutation';+import { RemoveColMutation, RemoveRowMutation } from '../../mutations/remove-row-col.mutation';+import { RemoveWorksheetMergeMutation } from '../../mutations/remove-worksheet-merge.mutation';+import {+ InsertColAfterCommand,+ InsertColBeforeCommand,+ InsertColCommand,+ InsertRowAfterCommand,+ InsertRowBeforeCommand,+ InsertRowCommand,+} from '../insert-row-col.command';+import { RemoveColCommand, RemoveRowCommand } from '../remove-row-col.command';+import { createCommandTestBed } from './create-command-test-bed';++describe('Test insert and remove row col commands', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;++ beforeEach(() => {+ const testBed = createInsertRowColTestBed();+ univer = testBed.univer;+ get = testBed.get;++ commandService = get(ICommandService);++ [+ InsertRowCommand,+ InsertRowBeforeCommand,+ InsertRowAfterCommand,+ InsertColAfterCommand,+ InsertColBeforeCommand,+ InsertColCommand,+ RemoveRowCommand,+ RemoveColCommand,++ InsertColMutation,+ InsertRowMutation,+ InsertRangeMutation,+ RemoveRowMutation,+ RemoveColMutation,+ DeleteRangeMutation,+ AddWorksheetMergeMutation,+ RemoveWorksheetMergeMutation,+ ].forEach((c) => {+ commandService.registerCommand(c);+ });++ const selectionManagerService = get(SelectionManagerService);+ selectionManagerService.setCurrentSelection({+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,+ unitId: 'test',+ sheetId: 'sheet1',+ });+ });++ afterEach(() => univer.dispose());++ function selectRow(rowStart: number, rowEnd: number): void {+ const selectionManagerService = get(SelectionManagerService);+ const endColumn = getColCount() - 1;+ selectionManagerService.add([+ {+ range: { startRow: rowStart, startColumn: 0, endColumn, endRow: rowEnd, rangeType: RANGE_TYPE.ROW },+ primary: {+ startRow: rowStart,+ endRow: rowEnd,+ startColumn: 0,+ endColumn,+ actualColumn: 0,+ actualRow: rowStart,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ },+ ]);+ }++ function selectColumn(columnStart: number, columnEnd: number): void {+ const selectionManagerService = get(SelectionManagerService);+ const endRow = getRowCount() - 1;+ selectionManagerService.add([+ {+ range: {+ startRow: 0,+ startColumn: columnStart,+ endColumn: columnEnd,+ endRow,+ rangeType: RANGE_TYPE.COLUMN,+ },+ primary: {+ startRow: 0,+ endRow,+ startColumn: columnStart,+ endColumn: columnEnd,+ actualColumn: columnStart,+ actualRow: 0,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ },+ ]);+ }++ function getRowCount(): number {+ const currentService = get(ICurrentUniverService);+ const workbook = currentService.getCurrentUniverSheetInstance();+ const worksheet = workbook.getActiveSheet();+ return worksheet.getRowCount();+ }++ function getColCount(): number {+ const currentService = get(ICurrentUniverService);+ const workbook = currentService.getCurrentUniverSheetInstance();+ const worksheet = workbook.getActiveSheet();+ return worksheet.getColumnCount();+ }++ function getCellStyle(row: number, col: number): Nullable<string | IStyleData> {+ return getCellInfo(row, col)?.s;+ }++ function getCellInfo(row: number, col: number): Nullable<ICellData> {+ const currentService = get(ICurrentUniverService);+ const workbook = currentService.getCurrentUniverSheetInstance();+ const worksheet = workbook.getActiveSheet();+ return worksheet.getCellMatrix().getValue(row, col);+ }++ function getMergedInfo(row: number, col: number): Nullable<IRange> {+ const currentService = get(ICurrentUniverService);+ const workbook = currentService.getCurrentUniverSheetInstance();+ const worksheet = workbook.getActiveSheet();+ return worksheet.getMergedCells(row, col)?.[0];+ }++ describe('Insert rows', () => {+ /**+ * In a test case we should examine+ * 1. The rows are actually inserted+ * 2. Row heights are correct+ * 3. Merged cells are correctly adjusted+ * 4. Selections are correctly adjusted+ */+ it("Should 'insert before' work", async () => {+ selectRow(2, 2);++ expect(getRowCount()).toBe(20);+ expect(getCellStyle(2, 1)).toBe('s4');+ const result = await commandService.executeCommand(InsertRowBeforeCommand.id);+ expect(result).toBeTruthy();+ expect(getRowCount()).toBe(21);+ expect(getCellStyle(2, 1)).toBe(getCellStyle(3, 1)); // the style should be copied from the cell above+ // the merged cell should be moved down+ expect(getMergedInfo(3, 1)).toEqual({ startRow: 3, endRow: 4, startColumn: 1, endColumn: 1 });++ await commandService.executeCommand(UndoCommand.id);+ expect(getRowCount()).toBe(20);++ await commandService.executeCommand(RedoCommand.id);+ expect(getRowCount()).toBe(21);+ });++ it("Should 'insert after' work", async () => {+ selectRow(2, 2);++ expect(getRowCount()).toBe(20);+ expect(getCellStyle(2, 1)).toBe('s4');+ expect(getMergedInfo(2, 1)).toEqual({ startRow: 2, endRow: 3, startColumn: 1, endColumn: 1 });+ const result = await commandService.executeCommand(InsertRowBeforeCommand.id);+ // TODO: expect row height+ expect(result).toBeTruthy();+ expect(getRowCount()).toBe(21);+ // the merged cell should expand+ expect(getMergedInfo(3, 1)).toEqual({ startRow: 3, endRow: 4, startColumn: 1, endColumn: 1 });++ await commandService.executeCommand(UndoCommand.id);+ expect(getRowCount()).toBe(20);++ await commandService.executeCommand(RedoCommand.id);+ expect(getRowCount()).toBe(21);+ });+ });++ describe('Insert columns', () => {+ it("Should 'insert before' work", async () => {+ selectColumn(1, 1);+ expect(getColCount()).toBe(20);++ const result = await commandService.executeCommand(InsertColBeforeCommand.id);+ expect(result).toBeTruthy();+ expect(getColCount()).toBe(21);++ const undoResult = await commandService.executeCommand(UndoCommand.id);+ expect(undoResult).toBeTruthy();+ expect(getColCount()).toBe(20);++ await commandService.executeCommand(RedoCommand.id);+ expect(getColCount()).toBe(21);+ });++ it("Should 'insert after' work", async () => {+ selectColumn(1, 1);++ const result = await commandService.executeCommand(InsertColAfterCommand.id);+ expect(result).toBeTruthy();+ expect(getColCount()).toBe(21);+ // expect a merged cell to expand and a merged cell to move+ expect(getMergedInfo(1, 1)).toEqual({ startRow: 1, endRow: 1, startColumn: 1, endColumn: 3 });+ expect(getMergedInfo(1, 4)).toEqual({ startRow: 1, endRow: 1, startColumn: 4, endColumn: 5 });+ });+ });++ describe('Remove rows', () => {+ it('Should removing selected rows works', async () => {+ selectRow(2, 2);+ expect(getRowCount()).toBe(20);++ const result = await commandService.executeCommand(RemoveRowCommand.id);+ expect(result).toBeTruthy();+ expect(getRowCount()).toBe(19);+ expect(getMergedInfo(2, 1)).toBeUndefined(); // expect the merged cell info to be deleted++ await commandService.executeCommand(UndoCommand.id);+ expect(getRowCount()).toBe(20);+ expect(getMergedInfo(2, 1)).toEqual({ startRow: 2, endRow: 3, startColumn: 1, endColumn: 1 }); // the merged cell should be restored++ await commandService.executeCommand(RedoCommand.id);+ expect(getRowCount()).toBe(19);+ });+ });++ describe('Remove columns', () => {+ it('Should removing selected rows works', async () => {+ selectColumn(1, 1);+ expect(getColCount()).toBe(20);++ const result = await commandService.executeCommand(RemoveColCommand.id);+ expect(result).toBeTruthy();+ expect(getColCount()).toBe(19);+ expect(getMergedInfo(1, 1)).toBeUndefined(); // expect the merged cell info to be deleted+ expect(getMergedInfo(1, 2)).toEqual({ startRow: 1, endRow: 1, startColumn: 2, endColumn: 3 }); // expect the merged cell to be moved left++ await commandService.executeCommand(UndoCommand.id);+ expect(getColCount()).toBe(20);++ await commandService.executeCommand(RedoCommand.id);+ expect(getColCount()).toBe(19);+ });+ });+});++const TEST_ROW_COL_INSERTION_DEMO: IWorkbookConfig = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ // 1+ // 2-3-+ // 4+ // |+ sheet1: {+ id: 'sheet1',+ cellData: {+ '0': {+ '0': {+ v: 'A1',+ s: 's1',+ },+ },+ '1': {+ '1': {+ v: 'B2',+ s: 's2',+ },+ '4': {+ v: 'E2',+ s: 's3',+ },+ },+ '2': {+ '1': {+ v: 'B3',+ s: 's4',+ },+ },+ },+ mergeData: [+ { startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 },+ {+ startRow: 1,+ endRow: 1,+ startColumn: 3,+ endColumn: 4,+ },+ {+ startRow: 2,+ endRow: 3,+ startColumn: 1,+ endColumn: 1,+ },+ ],+ // mergeData:+ rowCount: 20,+ columnCount: 20,+ },+ },+ createdTime: '',+ creator: '',+ extensions: [],+ lastModifiedBy: '',+ locale: LocaleType.EN,+ modifiedTime: '',+ name: '',+ sheetOrder: [],+ styles: {},+ timeZone: '',+};++function createInsertRowColTestBed() {+ return createCommandTestBed(Tools.deepClone(TEST_ROW_COL_INSERTION_DEMO));+}diff --git a/packages/base-sheets/src/commands/commands/delete-range-move-left.command.ts b/packages/base-sheets/src/commands/commands/delete-range-move-left.command.tsindex 7401f1c06c..1fd0672180 100644--- a/packages/base-sheets/src/commands/commands/delete-range-move-left.command.ts+++ b/packages/base-sheets/src/commands/commands/delete-range-move-left.command.ts@@ -42,7 +42,7 @@ export const DeleteRangeMoveLeftCommand: ICommand = {if (!worksheet) return false;const deleteRangeMutationParams: IDeleteRangeMutationParams = {- range,+ ranges: range,worksheetId,workbookId,shiftDimension: Dimension.COLUMNS,diff --git a/packages/base-sheets/src/commands/commands/delete-range-move-up.command.ts b/packages/base-sheets/src/commands/commands/delete-range-move-up.command.tsindex d8f90ad777..96ce77ff34 100644--- a/packages/base-sheets/src/commands/commands/delete-range-move-up.command.ts+++ b/packages/base-sheets/src/commands/commands/delete-range-move-up.command.ts@@ -42,7 +42,7 @@ export const DeleteRangeMoveUpCommand: ICommand = {if (!worksheet) return false;const deleteRangeMutationParams: IDeleteRangeMutationParams = {- range,+ ranges: range,worksheetId,workbookId,shiftDimension: Dimension.ROWS,diff --git a/packages/base-sheets/src/commands/commands/insert-range-move-down.command.ts b/packages/base-sheets/src/commands/commands/insert-range-move-down.command.tsindex 07b11f5ff6..d409d7ba42 100644--- a/packages/base-sheets/src/commands/commands/insert-range-move-down.command.ts+++ b/packages/base-sheets/src/commands/commands/insert-range-move-down.command.ts@@ -54,7 +54,7 @@ export const InsertRangeMoveDownCommand: ICommand = {}const insertRangeMutationParams: IInsertRangeMutationParams = {- range,+ ranges: range,worksheetId,workbookId,shiftDimension: Dimension.ROWS,diff --git a/packages/base-sheets/src/commands/commands/insert-range-move-right.command.ts b/packages/base-sheets/src/commands/commands/insert-range-move-right.command.tsindex fbac80b815..503ee247a4 100644--- a/packages/base-sheets/src/commands/commands/insert-range-move-right.command.ts+++ b/packages/base-sheets/src/commands/commands/insert-range-move-right.command.ts@@ -54,7 +54,7 @@ export const InsertRangeMoveRightCommand: ICommand = {}const insertRangeMutationParams: IInsertRangeMutationParams = {- range,+ ranges: range,worksheetId,workbookId,shiftDimension: Dimension.COLUMNS,diff --git a/packages/base-sheets/src/commands/commands/insert-row-col.command.ts b/packages/base-sheets/src/commands/commands/insert-row-col.command.tsindex 85a3a9da36..153b7e0865 100644--- a/packages/base-sheets/src/commands/commands/insert-row-col.command.ts+++ b/packages/base-sheets/src/commands/commands/insert-row-col.command.ts@@ -117,7 +117,7 @@ export const InsertRowCommand: ICommand = {const insertRangeMutationParams: IInsertRangeMutationParams = {workbookId: params.workbookId,worksheetId: params.worksheetId,- range: [params.range],+ ranges: [params.range],shiftDimension: Dimension.ROWS,cellValue: cellValue.getData(),};@@ -359,7 +359,7 @@ export const InsertColCommand: ICommand<IInsertColCommandParams> = {const insertRangeMutationParams: IInsertRangeMutationParams = {workbookId: params.workbookId,worksheetId: params.worksheetId,- range: [params.range],+ ranges: [params.range],shiftDimension: Dimension.COLUMNS,cellValue: cellValue.getData(),};diff --git a/packages/base-sheets/src/commands/commands/remove-row-col.command.ts b/packages/base-sheets/src/commands/commands/remove-row-col.command.tsindex f88aa2c34b..6234edd131 100644--- a/packages/base-sheets/src/commands/commands/remove-row-col.command.ts+++ b/packages/base-sheets/src/commands/commands/remove-row-col.command.ts@@ -4,9 +4,11 @@ import {ICommand,ICommandService,ICurrentUniverService,+ IRange,IUndoRedoService,Nullable,Rectangle,+ sequenceExecute,Tools,} from '@univerjs/core';import { IAccessor } from '@wendellhu/redi';@@ -37,78 +39,85 @@ import {RemoveWorksheetMergeMutationFactory,} from '../mutations/remove-worksheet-merge.mutation';+/**+ * This command would remove the selected rows. These selected rows can be non-continuous.+ */export const RemoveRowCommand: ICommand = {type: CommandType.COMMAND,id: 'sheet.command.remove-row',// eslint-disable-next-line max-lines-per-functionhandler: async (accessor: IAccessor) => {const selectionManagerService = accessor.get(SelectionManagerService);- const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);- const currentUniverService = accessor.get(ICurrentUniverService);-- const selections = selectionManagerService.getRangeDatas();- const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();- const worksheetId = currentUniverService- .getCurrentUniverSheetInstance()+ const selections = selectionManagerService.getSelections();+ if (!selections?.length) {+ return false;+ }- .getActiveSheet()- .getSheetId();- if (!selections?.length) return false;- const workbook = currentUniverService.getUniverSheetInstance(workbookId);- if (!workbook) return false;- const worksheet = workbook.getSheetBySheetId(worksheetId);- if (!worksheet) return false;+ const currentUniverService = accessor.get(ICurrentUniverService);+ const workbook = currentUniverService.getCurrentUniverSheetInstance();+ const worksheet = workbook.getActiveSheet();- selections.forEach((item) => {+ const workbookId = workbook.getUnitId();+ const worksheetId = worksheet.getSheetId();+ const ranges = selections.map((s) => Rectangle.clone(s.range));+ const lastColumnIndex = worksheet.getMaxColumns() - 1;+ ranges.forEach((item) => {item.startColumn = 0;- item.endColumn = worksheet.getMaxColumns();+ item.endColumn = lastColumnIndex;});- const redoMutationParams: IRemoveRowsMutationParams = {+ // row count+ const removeRowsParams: IRemoveRowsMutationParams = {workbookId,worksheetId,- ranges: selections,+ ranges,};+ const undoRemoveRowsParams: IInsertRowMutationParams = RemoveRowsMutationFactory(removeRowsParams, worksheet);- const undoMutationParams: IInsertRowMutationParams = RemoveRowsMutationFactory(redoMutationParams, worksheet);- const result = commandService.executeCommand(RemoveRowMutation.id, redoMutationParams);-- const deleteRangeValueMutationParams: IDeleteRangeMutationParams = {+ // cells' contents+ const deleteRangeValueParams: IDeleteRangeMutationParams = {workbookId,worksheetId,- range: selections,+ ranges,shiftDimension: Dimension.ROWS,};-- const insertRangeMutationParams: Nullable<IInsertRangeMutationParams> = DeleteRangeUndoMutationFactory(+ const undoDeleteRangeValueParams: Nullable<IInsertRangeMutationParams> = DeleteRangeUndoMutationFactory(accessor,- deleteRangeValueMutationParams+ deleteRangeValueParams);- if (!insertRangeMutationParams) return false;- const deleteResult = commandService.executeCommand(DeleteRangeMutation.id, deleteRangeValueMutationParams);- const mergeData = Tools.deepClone(worksheet.getMergeData());+ if (!undoDeleteRangeValueParams) return false;++ // adjust merged cells+ const mergeData: IRange[] = Tools.deepClone(worksheet.getMergeData());for (let i = 0; i < mergeData.length; i++) {const merge = mergeData[i];- for (let j = 0; j < selections.length; j++) {- const { startRow, endRow } = selections[j];+ const { startRow: mergeStartRow, endRow: mergeEndRow } = merge;+ const mergedCellRowCount = mergeEndRow - mergeStartRow + 1;+ for (let j = 0; j < ranges.length; j++) {+ const { startRow, endRow } = ranges[j];const count = endRow - startRow + 1;- if (endRow < merge.startRow) {+ if (endRow < mergeStartRow) {+ // this merged cell should be moved upmerge.startRow -= count;- } else if (startRow > merge.endRow) {+ merge.endRow -= count;+ } else if (startRow > mergeEndRow) {+ // this merged cell would not be affectedcontinue;- } else if (startRow < merge.startRow && endRow > merge.endRow) {- mergeData.splice(i);+ } else if (startRow <= mergeStartRow && endRow >= mergeEndRow) {+ // this merged cell should be removed+ mergeData.splice(i, 1);i--;} else {- const intersects = Rectangle.getIntersects(selections[j], merge)!;+ const intersects = Rectangle.getIntersects(ranges[j], merge)!;const interLength = intersects.endRow - intersects.startRow + 1;- const length = merge.endRow - merge.startRow + 1;- if (interLength === length) {- mergeData.splice(i);++ if (interLength === mergedCellRowCount - 1) {+ // if the merged cell's row count is reduced to 1 we should remove it as a merged cell+ mergeData.splice(i, 1);i--;} else {+ // otherwise we only need to shrink the merged cell's row countmerge.endRow -= intersects.endRow - intersects.startRow + 1;}}@@ -123,8 +132,6 @@ export const RemoveRowCommand: ICommand = {accessor,removeMergeMutationParams);- const removeResult = commandService.executeCommand(RemoveWorksheetMergeMutation.id, removeMergeMutationParams);-const addMergeMutationParams: IAddWorksheetMergeMutationParams = {workbookId,worksheetId,@@ -134,61 +141,45 @@ export const RemoveRowCommand: ICommand = {accessor,addMergeMutationParams);- const mergeResult = commandService.executeCommand(AddWorksheetMergeMutation.id, addMergeMutationParams);- if (result && deleteResult && removeResult && mergeResult) {- undoRedoService.pushUndoRedo({+ const commandService = accessor.get(ICommandService);+ const result = await sequenceExecute(+ [+ { id: DeleteRangeMutation.id, params: deleteRangeValueParams },+ { id: RemoveRowMutation.id, params: removeRowsParams },+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },+ { id: AddWorksheetMergeMutation.id, params: addMergeMutationParams },+ ],+ commandService+ );++ if (result.result) {+ accessor.get(IUndoRedoService).pushUndoRedo({URI: workbookId,- undo() {- return (commandService.executeCommand(InsertRowMutation.id, undoMutationParams) as Promise<boolean>)- .then((res) => {- if (res)- return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);- return false;- })- .then((res) => {- if (res)- return commandService.executeCommand(- RemoveWorksheetMergeMutation.id,- deleteMergeMutationParams- );- return false;- })- .then((res) => {- if (res)- return commandService.executeCommand(- AddWorksheetMergeMutation.id,- undoRemoveMergeMutationParams- );- return false;- });+ undo: async () => {+ const undoResult = await sequenceExecute(+ [+ { id: InsertRowMutation.id, params: undoRemoveRowsParams },+ { id: InsertRangeMutation.id, params: undoDeleteRangeValueParams },+ { id: RemoveWorksheetMergeMutation.id, params: deleteMergeMutationParams },+ { id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams },+ ],+ commandService+ );+ return undoResult.result;},- redo() {- return (commandService.executeCommand(RemoveRowMutation.id, redoMutationParams) as Promise<boolean>)- .then((res) => {- if (res)- return commandService.executeCommand(- DeleteRangeMutation.id,- deleteRangeValueMutationParams- );- return false;- })- .then((res) => {- if (res)- return commandService.executeCommand(- RemoveWorksheetMergeMutation.id,- removeMergeMutationParams- );- return false;- })- .then((res) => {- if (res)- return commandService.executeCommand(- AddWorksheetMergeMutation.id,- addMergeMutationParams- );- return false;- });+ redo: async () => {+ const result = await sequenceExecute(+ [+ { id: DeleteRangeMutation.id, params: deleteRangeValueParams },+ { id: RemoveRowMutation.id, params: removeRowsParams },+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },+ { id: AddWorksheetMergeMutation.id, params: addMergeMutationParams },+ ],+ commandService+ );++ return result.result;},});return true;@@ -197,78 +188,79 @@ export const RemoveRowCommand: ICommand = {},};+/**+ * This command would remove the selected columns. These selected rows can be non-continuous.+ */export const RemoveColCommand: ICommand = {type: CommandType.COMMAND,id: 'sheet.command.remove-col',// eslint-disable-next-line max-lines-per-functionhandler: async (accessor: IAccessor) => {const selectionManagerService = accessor.get(SelectionManagerService);- const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);- const currentUniverService = accessor.get(ICurrentUniverService);-- const selections = selectionManagerService.getRangeDatas();- const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();- const worksheetId = currentUniverService- .getCurrentUniverSheetInstance()+ const selections = selectionManagerService.getSelections();+ if (!selections?.length) {+ return false;+ }- .getActiveSheet()- .getSheetId();- if (!selections?.length) return false;- const workbook = currentUniverService.getUniverSheetInstance(workbookId);- if (!workbook) return false;- const worksheet = workbook.getSheetBySheetId(worksheetId);- if (!worksheet) return false;+ const currentUniverService = accessor.get(ICurrentUniverService);+ const workbook = currentUniverService.getCurrentUniverSheetInstance();+ const worksheet = workbook.getActiveSheet();- selections.forEach((item) => {+ const workbookId = workbook.getUnitId();+ const worksheetId = worksheet.getSheetId();+ const ranges = selections.map((s) => Rectangle.clone(s.range));+ const lastRowIndex = worksheet.getMaxRows() - 1;+ ranges.forEach((item) => {item.startRow = 0;- item.endRow = worksheet.getMaxRows();+ item.endRow = lastRowIndex;});- const redoMutationParams: IRemoveColMutationParams = {+ // col count+ const removeColParams: IRemoveColMutationParams = {workbookId,worksheetId,- ranges: selections,+ ranges,};+ const undoRemoveColParams: IInsertColMutationParams = IRemoveColMutationFactory(accessor, removeColParams);- const undoMutationParams: IInsertColMutationParams = IRemoveColMutationFactory(accessor, redoMutationParams);- const result = commandService.executeCommand(RemoveColMutation.id, redoMutationParams);-- const deleteRangeValueMutationParams: IDeleteRangeMutationParams = {+ // cells' contents+ const removeRangeValuesParams: IDeleteRangeMutationParams = {workbookId,worksheetId,- range: selections,+ ranges,shiftDimension: Dimension.COLUMNS,};- const insertRangeMutationParams: Nullable<IInsertRangeMutationParams> = DeleteRangeUndoMutationFactory(+ const undoRemoveRangeValuesParams: Nullable<IInsertRangeMutationParams> = DeleteRangeUndoMutationFactory(accessor,- deleteRangeValueMutationParams+ removeRangeValuesParams);- if (!insertRangeMutationParams) return false;- const deleteResult = commandService.executeCommand(DeleteRangeMutation.id, deleteRangeValueMutationParams);+ if (!undoRemoveRangeValuesParams) {+ throw new Error();+ }- const mergeData = Tools.deepClone(worksheet.getMergeData());+ // adjust merged cells+ const mergeData: IRange[] = Tools.deepClone(worksheet.getMergeData());for (let i = 0; i < mergeData.length; i++) {const merge = mergeData[i];- for (let j = 0; j < selections.length; j++) {- const { startColumn, endColumn } = selections[j];+ const { startColumn: mergeStartColumn, endColumn: mergeEndColumn } = merge;+ const mergedCellColumnCount = mergeEndColumn - mergeStartColumn + 1;+ for (let j = 0; j < ranges.length; j++) {+ const { startColumn, endColumn } = ranges[j];const count = endColumn - startColumn + 1;if (endColumn < merge.startColumn) {merge.startColumn -= count;+ merge.endColumn -= count;} else if (startColumn > merge.endColumn) {continue;- } else if (- (startColumn < merge.startColumn && endColumn > merge.endColumn) ||- (startColumn === merge.startColumn && endColumn === merge.endColumn)- ) {- mergeData.splice(i);+ } else if (startColumn <= merge.startColumn && endColumn >= merge.endColumn) {+ mergeData.splice(i, 1);i--;} else {- const intersects = Rectangle.getIntersects(selections[j], merge)!;+ const intersects = Rectangle.getIntersects(ranges[j], merge)!;const interLength = intersects.endColumn - intersects.startColumn + 1;- const length = endColumn - startColumn + 1;- if (interLength === length) {- mergeData.splice(i);++ if (interLength === mergedCellColumnCount - 1) {+ mergeData.splice(i, 1);i--;} else {merge.endColumn -= intersects.endColumn - intersects.startColumn + 1;@@ -276,7 +268,6 @@ export const RemoveColCommand: ICommand = {}}}-const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {workbookId,worksheetId,@@ -286,72 +277,54 @@ export const RemoveColCommand: ICommand = {accessor,removeMergeMutationParams);- const removeResult = commandService.executeCommand(RemoveWorksheetMergeMutation.id, removeMergeMutationParams);-const addMergeMutationParams: IAddWorksheetMergeMutationParams = {workbookId,worksheetId,ranges: mergeData,};- const deleteMergeMutationParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(+ const undoAddMergeParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(accessor,addMergeMutationParams);- const mergeResult = commandService.executeCommand(AddWorksheetMergeMutation.id, addMergeMutationParams);- if (result && deleteResult && removeResult && mergeResult) {+ const commandService = accessor.get(ICommandService);+ const result = await sequenceExecute(+ [+ { id: RemoveColMutation.id, params: removeColParams },+ { id: DeleteRangeMutation.id, params: removeRangeValuesParams },+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },+ { id: AddWorksheetMergeMutation.id, params: addMergeMutationParams },+ ],+ commandService+ );++ if (result.result) {+ const undoRedoService = accessor.get(IUndoRedoService);undoRedoService.pushUndoRedo({URI: workbookId,- undo() {- return (commandService.executeCommand(InsertColMutation.id, undoMutationParams) as Promise<boolean>)- .then((res) => {- if (res)- return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);- return false;- })- .then((res) => {- if (res)- return commandService.executeCommand(- RemoveWorksheetMergeMutation.id,- deleteMergeMutationParams- );- return false;- })- .then((res) => {- if (res)- return commandService.executeCommand(- AddWorksheetMergeMutation.id,- undoRemoveMergeMutationParams- );- return false;- });+ undo: async () => {+ const undoResult = await sequenceExecute(+ [+ { id: InsertColMutation.id, params: undoRemoveColParams },+ { id: InsertRangeMutation.id, params: undoRemoveRangeValuesParams },+ { id: RemoveWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams },+ { id: AddWorksheetMergeMutation.id, params: undoAddMergeParams },+ ],+ commandService+ );+ return undoResult.result;},- redo() {- return (commandService.executeCommand(RemoveColMutation.id, redoMutationParams) as Promise<boolean>)- .then((res) => {- if (res)- return commandService.executeCommand(- DeleteRangeMutation.id,- deleteRangeValueMutationParams- );- return false;- })- .then((res) => {- if (res)- return commandService.executeCommand(- RemoveWorksheetMergeMutation.id,- removeMergeMutationParams- );- return false;- })- .then((res) => {- if (res)- return commandService.executeCommand(- AddWorksheetMergeMutation.id,- addMergeMutationParams- );- return false;- });+ redo: async () => {+ const result = await sequenceExecute(+ [+ { id: RemoveColMutation.id, params: removeColParams },+ { id: DeleteRangeMutation.id, params: removeRangeValuesParams },+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },+ { id: AddWorksheetMergeMutation.id, params: addMergeMutationParams },+ ],+ commandService+ );+ return result.result;},});diff --git a/packages/base-sheets/src/commands/mutations/delete-range.mutation.ts b/packages/base-sheets/src/commands/mutations/delete-range.mutation.tsindex 41ac696b18..cff629ea28 100644--- a/packages/base-sheets/src/commands/mutations/delete-range.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/delete-range.mutation.ts@@ -35,8 +35,8 @@ export const DeleteRangeUndoMutationFactory = (const lastEndRow = worksheet.getConfig().rowCount;const lastEndColumn = worksheet.getConfig().columnCount;- for (let i = 0; i < params.range.length; i++) {- const { startRow, endRow, startColumn, endColumn } = params.range[i];+ for (let i = 0; i < params.ranges.length; i++) {+ const { startRow, endRow, startColumn, endColumn } = params.ranges[i];if (params.shiftDimension === Dimension.ROWS) {// build new data@@ -88,8 +88,8 @@ export const DeleteRangeMutation: IMutation<IDeleteRangeMutationParams, boolean>const lastEndRow = worksheet.getConfig().rowCount;const lastEndColumn = worksheet.getConfig().columnCount;- for (let i = 0; i < params.range.length; i++) {- const { startRow, endRow, startColumn, endColumn } = params.range[i];+ for (let i = 0; i < params.ranges.length; i++) {+ const { startRow, endRow, startColumn, endColumn } = params.ranges[i];const rows = endRow - startRow + 1;const columns = endColumn - startColumn + 1;diff --git a/packages/base-sheets/src/commands/mutations/insert-range.mutation.ts b/packages/base-sheets/src/commands/mutations/insert-range.mutation.tsindex a82f304326..c74e89e848 100644--- a/packages/base-sheets/src/commands/mutations/insert-range.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/insert-range.mutation.ts@@ -16,7 +16,7 @@ export const InsertRangeUndoMutationFactory = (): IDeleteRangeMutationParams => ({workbookId: params.workbookId,worksheetId: params.worksheetId,- range: params.range,+ ranges: params.ranges,shiftDimension: params.shiftDimension,});@@ -34,8 +34,8 @@ export const InsertRangeMutation: IMutation<IInsertRangeMutationParams, boolean>const lastEndRow = worksheet.getLastRowWithContent();const lastEndColumn = worksheet.getLastColumnWithContent();- for (let i = 0; i < params.range.length; i++) {- const { startRow, endRow, startColumn, endColumn } = params.range[i];+ for (let i = 0; i < params.ranges.length; i++) {+ const { startRow, endRow, startColumn, endColumn } = params.ranges[i];const rows = endRow - startRow + 1;const columns = endColumn - startColumn + 1;diff --git a/packages/ui-plugin-sheets/src/controller/shortcuts/value.shortcut.ts b/packages/ui-plugin-sheets/src/controller/shortcuts/value.shortcut.tsindex 7c7b014524..b6bbc18f85 100644--- a/packages/ui-plugin-sheets/src/controller/shortcuts/value.shortcut.ts+++ b/packages/ui-plugin-sheets/src/controller/shortcuts/value.shortcut.ts@@ -5,6 +5,7 @@ import { FOCUSING_SHEET } from '@univerjs/core';export const ClearSelectionValueShortcutItem: IShortcutItem = {id: ClearSelectionContentCommand.id,preconditions: (contextService) =>+ // when focusing on any other input tag do not trigger this shortcutcontextService.getContextValue(FOCUSING_SHEET) && document.activeElement?.tagName === 'canvas',binding: KeyCode.BACKSPACE,};