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): insert range handle row/column,merge (#309)
Dushusirde9acd755eeb
diff --git a/packages/base-sheets/src/commands/commands/__tests__/delete-range.command.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/delete-range.command.spec.tsnew file mode 100644index 0000000000..fe14c0831e--- /dev/null+++ b/packages/base-sheets/src/commands/commands/__tests__/delete-range.command.spec.ts@@ -0,0 +1,343 @@+import {+ ICellData,+ ICommandService,+ IRange,+ IStyleData,+ IUniverInstanceService,+ IWorkbookConfig,+ LocaleType,+ Nullable,+ RANGE_TYPE,+ Rectangle,+ RedoCommand,+ 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 { DeleteRangeMoveLeftCommand } from '../delete-range-move-left.command';+import { DeleteRangeMoveUpCommand } from '../delete-range-move-up.command';+import { createCommandTestBed } from './create-command-test-bed';++const mergeData = [+ {+ startRow: 0,+ endRow: 1,+ startColumn: 2,+ endColumn: 2,+ },+ {+ startRow: 1,+ endRow: 2,+ startColumn: 3,+ endColumn: 3,+ },+ {+ startRow: 1,+ endRow: 1,+ startColumn: 6,+ endColumn: 7,+ },+ {+ startRow: 1,+ endRow: 1,+ startColumn: 9,+ endColumn: 11,+ },+ {+ startRow: 2,+ endRow: 2,+ startColumn: 5,+ endColumn: 6,+ },+ {+ startRow: 2,+ endRow: 2,+ startColumn: 9,+ endColumn: 10,+ },+ {+ startRow: 4,+ endRow: 6,+ startColumn: 2,+ endColumn: 2,+ },+ {+ startRow: 5,+ endRow: 6,+ startColumn: 3,+ endColumn: 3,+ },+];+const WORKBOOK_DATA_DEMO: IWorkbookConfig = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ cellData: {+ '0': {+ '0': {+ v: 'A1',+ },+ '1': {+ v: 'B1',+ },+ '2': {+ v: 'C1',+ },+ },+ '1': {+ '0': {+ v: 'A2',+ },+ '1': {+ v: 'B2',+ },+ '3': {+ v: 'D2',+ },+ '6': {+ v: 'G2',+ },+ '9': {+ v: 'J2',+ },+ },+ '2': {+ '5': {+ v: 'F3',+ },+ '9': {+ v: 'J3',+ },+ },+ '4': {+ '2': {+ v: 'C5',+ },+ },+ '5': {+ '3': {+ v: 'D6',+ },+ },+ },+ mergeData,+ },+ },+ createdTime: '',+ creator: '',+ extensions: [],+ lastModifiedBy: '',+ locale: LocaleType.EN,+ modifiedTime: '',+ name: '',+ sheetOrder: [],+ styles: {},+ timeZone: '',+};++describe('Test delete range commands', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;+ let selectionManager: SelectionManagerService;+ let getValueByPosition: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Nullable<ICellData>;+ let getStyleByPosition: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Nullable<IStyleData>;+ let getValues: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Array<Array<Nullable<ICellData>>> | undefined;+ let getMergedCells: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => IRange[] | undefined;++ beforeEach(() => {+ const testBed = createCommandTestBed(WORKBOOK_DATA_DEMO);+ univer = testBed.univer;+ get = testBed.get;++ commandService = get(ICommandService);+ commandService.registerCommand(DeleteRangeMoveUpCommand);+ commandService.registerCommand(DeleteRangeMoveLeftCommand);+ commandService.registerCommand(InsertRangeMutation);+ commandService.registerCommand(DeleteRangeMutation);+ commandService.registerCommand(AddWorksheetMergeMutation);+ commandService.registerCommand(RemoveWorksheetMergeMutation);+ commandService.registerCommand(InsertColMutation);+ commandService.registerCommand(RemoveColMutation);+ commandService.registerCommand(InsertRowMutation);+ commandService.registerCommand(RemoveRowMutation);++ selectionManager = get(SelectionManagerService);+ selectionManager.setCurrentSelection({+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,+ unitId: 'test',+ sheetId: 'sheet1',+ });++ getValueByPosition = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Nullable<ICellData> =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')+ ?.getRange(startRow, startColumn, endRow, endColumn)+ .getValue();++ getStyleByPosition = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Nullable<IStyleData> => {+ const value = getValueByPosition(startRow, startColumn, endRow, endColumn);+ const styles = get(IUniverInstanceService).getUniverSheetInstance('test')?.getStyles();+ if (value && styles) {+ return styles.getStyleByCell(value);+ }+ };++ getValues = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Array<Array<Nullable<ICellData>>> | undefined =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')+ ?.getRange(startRow, startColumn, endRow, endColumn)+ .getValues();++ getMergedCells = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): IRange[] | undefined =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')+ ?.getMergeData()+ .filter((rect) => Rectangle.intersects({ startRow, startColumn, endRow, endColumn }, rect));+ });++ afterEach(() => {+ univer.dispose();+ });+ describe('Delete range move left', () => {+ describe('correct situations', () => {+ it('will insert range when there is a selected range, no merged cells', async () => {+ selectionManager.replace([+ {+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);+ expect(await commandService.executeCommand(DeleteRangeMoveLeftCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: 'B1',+ });++ // undo+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: 'A1',+ });+ expect(getValueByPosition(0, 1, 0, 1)).toStrictEqual({+ v: 'B1',+ });++ // redo+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: 'B1',+ });++ // reset data for next test+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });+ });++ describe('fault situations', () => {+ it('will not apply when there is no selected ranges', async () => {+ selectionManager.clear();+ const result = await commandService.executeCommand(DeleteRangeMoveLeftCommand.id);+ expect(result).toBeFalsy();+ });+ });+ });+ describe('Delete range move up', () => {+ describe('correct situations', () => {+ it('will insert range when there is a selected range, no merged cells', async () => {+ selectionManager.replace([+ {+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);++ expect(await commandService.executeCommand(DeleteRangeMoveUpCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: 'A2',+ });++ // undo+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: 'A1',+ });+ expect(getValueByPosition(1, 0, 1, 0)).toStrictEqual({+ v: 'A2',+ });++ // redo+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: 'A2',+ });++ // reset data for next test+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });+ });++ describe('fault situations', () => {+ it('will not apply when there is no selected ranges', async () => {+ selectionManager.clear();+ const result = await commandService.executeCommand(DeleteRangeMoveUpCommand.id);+ expect(result).toBeFalsy();+ });+ });+ });+});diff --git a/packages/base-sheets/src/commands/commands/__tests__/insert-range.command.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/insert-range.command.spec.tsnew file mode 100644index 0000000000..18b729ae88--- /dev/null+++ b/packages/base-sheets/src/commands/commands/__tests__/insert-range.command.spec.ts@@ -0,0 +1,514 @@+import {+ ICellData,+ ICommandService,+ IRange,+ IStyleData,+ IUniverInstanceService,+ IWorkbookConfig,+ LocaleType,+ Nullable,+ RANGE_TYPE,+ Rectangle,+ RedoCommand,+ 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 { InsertRangeMoveDownCommand } from '../insert-range-move-down.command';+import { InsertRangeMoveRightCommand } from '../insert-range-move-right.command';+import { createCommandTestBed } from './create-command-test-bed';++const mergeData = [+ {+ startRow: 0,+ endRow: 1,+ startColumn: 2,+ endColumn: 2,+ },+ {+ startRow: 1,+ endRow: 2,+ startColumn: 3,+ endColumn: 3,+ },+ {+ startRow: 1,+ endRow: 1,+ startColumn: 6,+ endColumn: 7,+ },+ {+ startRow: 1,+ endRow: 1,+ startColumn: 9,+ endColumn: 11,+ },+ {+ startRow: 2,+ endRow: 2,+ startColumn: 5,+ endColumn: 6,+ },+ {+ startRow: 2,+ endRow: 2,+ startColumn: 9,+ endColumn: 10,+ },+ {+ startRow: 4,+ endRow: 6,+ startColumn: 2,+ endColumn: 2,+ },+ {+ startRow: 5,+ endRow: 6,+ startColumn: 3,+ endColumn: 3,+ },+];+const WORKBOOK_DATA_DEMO: IWorkbookConfig = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ cellData: {+ '0': {+ '0': {+ v: 'A1',+ },+ '1': {+ v: 'B1',+ },+ '2': {+ v: 'C1',+ },+ },+ '1': {+ '0': {+ v: 'A2',+ },+ '1': {+ v: 'B2',+ },+ '3': {+ v: 'D2',+ },+ '6': {+ v: 'G2',+ },+ '9': {+ v: 'J2',+ },+ },+ '2': {+ '5': {+ v: 'F3',+ },+ '9': {+ v: 'J3',+ },+ },+ '4': {+ '2': {+ v: 'C5',+ },+ },+ '5': {+ '3': {+ v: 'D6',+ },+ },+ },+ mergeData,+ },+ },+ createdTime: '',+ creator: '',+ extensions: [],+ lastModifiedBy: '',+ locale: LocaleType.EN,+ modifiedTime: '',+ name: '',+ sheetOrder: [],+ styles: {},+ timeZone: '',+};++describe('Test insert range commands', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;+ let selectionManager: SelectionManagerService;+ let getValueByPosition: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Nullable<ICellData>;+ let getStyleByPosition: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Nullable<IStyleData>;+ let getValues: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Array<Array<Nullable<ICellData>>> | undefined;+ let getMergedCells: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => IRange[] | undefined;++ beforeEach(() => {+ const testBed = createCommandTestBed(WORKBOOK_DATA_DEMO);+ univer = testBed.univer;+ get = testBed.get;++ commandService = get(ICommandService);+ commandService.registerCommand(InsertRangeMoveDownCommand);+ commandService.registerCommand(InsertRangeMoveRightCommand);+ commandService.registerCommand(InsertRangeMutation);+ commandService.registerCommand(DeleteRangeMutation);+ commandService.registerCommand(AddWorksheetMergeMutation);+ commandService.registerCommand(RemoveWorksheetMergeMutation);+ commandService.registerCommand(InsertColMutation);+ commandService.registerCommand(RemoveColMutation);+ commandService.registerCommand(InsertRowMutation);+ commandService.registerCommand(RemoveRowMutation);++ selectionManager = get(SelectionManagerService);+ selectionManager.setCurrentSelection({+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,+ unitId: 'test',+ sheetId: 'sheet1',+ });++ getValueByPosition = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Nullable<ICellData> =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')+ ?.getRange(startRow, startColumn, endRow, endColumn)+ .getValue();++ getStyleByPosition = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Nullable<IStyleData> => {+ const value = getValueByPosition(startRow, startColumn, endRow, endColumn);+ const styles = get(IUniverInstanceService).getUniverSheetInstance('test')?.getStyles();+ if (value && styles) {+ return styles.getStyleByCell(value);+ }+ };++ getValues = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Array<Array<Nullable<ICellData>>> | undefined =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')+ ?.getRange(startRow, startColumn, endRow, endColumn)+ .getValues();++ getMergedCells = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): IRange[] | undefined =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')+ ?.getMergeData()+ .filter((rect) => Rectangle.intersects({ startRow, startColumn, endRow, endColumn }, rect));+ });++ afterEach(() => {+ univer.dispose();+ });+ describe('Insert range move right', () => {+ describe('correct situations', () => {+ it('will insert range when there is a selected range, no merged cells', async () => {+ selectionManager.replace([+ {+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);+ expect(await commandService.executeCommand(InsertRangeMoveRightCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: '',+ m: '',+ });+ expect(getValueByPosition(0, 1, 0, 1)).toStrictEqual({+ v: 'A1',+ });++ // undo+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: 'A1',+ });+ expect(getValueByPosition(0, 1, 0, 1)).toStrictEqual({+ v: 'B1',+ });++ // redo+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: '',+ m: '',+ });+ expect(getValueByPosition(0, 1, 0, 1)).toStrictEqual({+ v: 'A1',+ });++ // reset data for next test+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });+ it('will insert range when there is a selected range, with merged cells of 2 rows and 1 column, break merged cells on the right', async () => {+ selectionManager.replace([+ {+ range: { startRow: 0, startColumn: 2, endRow: 1, endColumn: 2, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);+ expect(await commandService.executeCommand(InsertRangeMoveRightCommand.id)).toBeTruthy();++ // cell value+ expect(getValueByPosition(0, 2, 0, 2)).toStrictEqual({+ v: '',+ m: '',+ });+ expect(getValueByPosition(0, 3, 0, 3)).toStrictEqual({+ v: 'C1',+ });+ expect(getValueByPosition(1, 4, 1, 4)).toStrictEqual({+ v: 'D2',+ });++ const mergedCells = getMergedCells(0, 2, 2, 4);+ expect(mergedCells).toStrictEqual([+ {+ startRow: 0,+ startColumn: 3,+ endRow: 1,+ endColumn: 3,+ },+ ]);++ // TODO@Dushusir: test undo redo after delete range completed++ // reset data for next test+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });+ it('will insert range when there is a selected range, with merged cells of 3 rows and 1 column, will not break merged cells on the right', async () => {+ selectionManager.replace([+ {+ range: { startRow: 4, startColumn: 2, endRow: 6, endColumn: 2, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);+ expect(await commandService.executeCommand(InsertRangeMoveRightCommand.id)).toBeTruthy();++ // cell value+ expect(getValueByPosition(4, 2, 4, 2)).toStrictEqual({+ v: '',+ m: '',+ });+ expect(getValueByPosition(4, 3, 4, 3)).toStrictEqual({+ v: 'C5',+ });+ expect(getValueByPosition(5, 4, 5, 4)).toStrictEqual({+ v: 'D6',+ });++ const mergedCells = getMergedCells(4, 2, 6, 4);+ expect(mergedCells).toStrictEqual([+ {+ startRow: 4,+ startColumn: 3,+ endRow: 6,+ endColumn: 3,+ },+ {+ startRow: 5,+ startColumn: 4,+ endRow: 6,+ endColumn: 4,+ },+ ]);++ // reset data for next test+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });+ });++ describe('fault situations', () => {+ it('will not apply when there is no selected ranges', async () => {+ selectionManager.clear();+ const result = await commandService.executeCommand(InsertRangeMoveRightCommand.id);+ expect(result).toBeFalsy();+ });+ });+ });+ describe('Insert range move down', () => {+ describe('correct situations', () => {+ it('will insert range when there is a selected range, no merged cells', async () => {+ selectionManager.replace([+ {+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);++ expect(await commandService.executeCommand(InsertRangeMoveDownCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: '',+ m: '',+ });+ expect(getValueByPosition(1, 0, 1, 0)).toStrictEqual({+ v: 'A1',+ });++ // undo+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: 'A1',+ });+ expect(getValueByPosition(1, 0, 1, 0)).toStrictEqual({+ v: 'A2',+ });++ // redo+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getValueByPosition(0, 0, 0, 0)).toStrictEqual({+ v: '',+ m: '',+ });+ expect(getValueByPosition(1, 0, 1, 0)).toStrictEqual({+ v: 'A1',+ });++ // reset data for next test+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });++ it('will insert range when there is a selected range, with merged cells of 1 row and 2 columns, break merged cells on the bottom', async () => {+ selectionManager.replace([+ {+ range: { startRow: 1, startColumn: 6, endRow: 1, endColumn: 7, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);+ expect(await commandService.executeCommand(InsertRangeMoveDownCommand.id)).toBeTruthy();++ // cell value+ expect(getValueByPosition(1, 6, 1, 6)).toStrictEqual({+ v: '',+ m: '',+ });+ expect(getValueByPosition(2, 6, 2, 6)).toStrictEqual({+ v: 'G2',+ });+ expect(getValueByPosition(2, 5, 2, 5)).toStrictEqual({+ v: 'F3',+ });++ const mergedCells = getMergedCells(1, 5, 3, 7);+ expect(mergedCells).toStrictEqual([+ {+ startRow: 2,+ startColumn: 6,+ endRow: 2,+ endColumn: 7,+ },+ ]);++ // reset data for next test+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });+ it('will insert range when there is a selected range, with merged cells of 1 row and 3 columns, will not break merged cells on the bottom', async () => {+ selectionManager.replace([+ {+ range: { startRow: 1, startColumn: 9, endRow: 1, endColumn: 11, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);+ expect(await commandService.executeCommand(InsertRangeMoveDownCommand.id)).toBeTruthy();++ // cell value+ expect(getValueByPosition(1, 9, 1, 9)).toStrictEqual({+ v: '',+ m: '',+ });+ expect(getValueByPosition(2, 9, 2, 9)).toStrictEqual({+ v: 'J2',+ });+ expect(getValueByPosition(3, 9, 3, 9)).toStrictEqual({+ v: 'J3',+ });++ const mergedCells = getMergedCells(1, 9, 3, 11);+ expect(mergedCells).toStrictEqual([+ {+ startRow: 3,+ startColumn: 9,+ endRow: 3,+ endColumn: 10,+ },+ {+ startRow: 2,+ startColumn: 9,+ endRow: 2,+ endColumn: 11,+ },+ ]);++ // reset data for next test+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });+ });++ describe('fault situations', () => {+ it('will not apply when there is no selected ranges', async () => {+ selectionManager.clear();+ const result = await commandService.executeCommand(InsertRangeMoveDownCommand.id);+ expect(result).toBeFalsy();+ });+ });+ });+});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 4914b479fc..e42c5a1ae5 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@@ -1,19 +1,42 @@import {+ BooleanNumber,CommandType,Dimension,ICellData,ICommand,+ ICommandInfo,ICommandService,+ ILogService,+ IRange,+ IRowData,IUndoRedoService,IUniverInstanceService,+ ObjectArray,ObjectMatrix,+ Rectangle,+ sequenceExecute,} from '@univerjs/core';import { IAccessor } from '@wendellhu/redi';-import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';+import {+ IAddWorksheetMergeMutationParams,+ IDeleteRangeMutationParams,+ IInsertRangeMutationParams,+ IInsertRowMutationParams,+ IRemoveRowsMutationParams,+ IRemoveWorksheetMergeMutationParams,+} from '../../Basics/Interfaces/MutationInterface';import { SelectionManagerService } from '../../services/selection-manager.service';+import { AddMergeUndoMutationFactory, AddWorksheetMergeMutation } from '../mutations/add-worksheet-merge.mutation';import { DeleteRangeMutation } from '../mutations/delete-range.mutation';import { InsertRangeMutation, InsertRangeUndoMutationFactory } from '../mutations/insert-range.mutation';+import { InsertRowMutation, InsertRowMutationUndoFactory } from '../mutations/insert-row-col.mutation';+import { RemoveRowMutation } from '../mutations/remove-row-col.mutation';+import {+ RemoveMergeUndoMutationFactory,+ RemoveWorksheetMergeMutation,+} from '../mutations/remove-worksheet-merge.mutation';+import { calculateTotalLength, IInterval } from './utils/selection-util';/*** The command to insert range.@@ -26,8 +49,15 @@ export const InsertRangeMoveDownCommand: ICommand = {const commandService = accessor.get(ICommandService);const undoRedoService = accessor.get(IUndoRedoService);const univerInstanceService = accessor.get(IUniverInstanceService);+ const logService = accessor.get(ILogService);const selectionManagerService = accessor.get(SelectionManagerService);+ if (selectionManagerService.isOverlapping()) {+ // TODO@Dushusir: use Dialog after Dialog component completed+ logService.error('Cannot use that command on overlapping selections.');+ return false;+ }+const workbookId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();const worksheetId = univerInstanceService.getCurrentUniverSheetInstance()@@ -42,6 +72,10 @@ export const InsertRangeMoveDownCommand: ICommand = {const worksheet = workbook.getSheetBySheetId(worksheetId);if (!worksheet) return false;+ const redoMutations: ICommandInfo[] = [];+ const undoMutations: ICommandInfo[] = [];++ // 1. insert rangeconst cellValue = new ObjectMatrix<ICellData>();for (let i = 0; i < range.length; i++) {const { startRow, endRow, startColumn, endColumn } = range[i];@@ -61,24 +95,148 @@ export const InsertRangeMoveDownCommand: ICommand = {cellValue: cellValue.getData(),};+ redoMutations.push({ id: InsertRangeMutation.id, params: insertRangeMutationParams });+const deleteRangeMutationParams: IDeleteRangeMutationParams = InsertRangeUndoMutationFactory(accessor,insertRangeMutationParams);+ undoMutations.push({ id: DeleteRangeMutation.id, params: deleteRangeMutationParams });++ // 2. insert row+ // Only required when the last row has a value, and the row height is set to the row height of the last row+ let hasValueInLastRow = false;+ let lastRowHeight = 0;+ const lastRowIndex = worksheet.getMaxRows() - 1;+ const rowsObject: IInterval = {};+ for (let i = 0; i < range.length; i++) {+ const { startRow, endRow, startColumn, endColumn } = range[i];+ rowsObject[`${i}`] = [startRow, endRow];+ for (let column = startColumn; column <= endColumn; column++) {+ const lastCell = worksheet.getCell(lastRowIndex, column);+ const lastCellValue = lastCell?.v;+ if (lastCellValue && lastCellValue !== '') {+ hasValueInLastRow = true;+ lastRowHeight = worksheet.getRowHeight(lastRowIndex);+ break;+ }+ }+ }++ // There may be overlap and deduplication is required+ const rowsCount = calculateTotalLength(rowsObject);+ if (hasValueInLastRow) {+ const lastRowRange = {+ startRow: lastRowIndex,+ endRow: lastRowIndex,+ startColumn: range[0].startColumn,+ endColumn: range[0].endColumn,+ };+ const insertRowParams: IInsertRowMutationParams = {+ workbookId,+ worksheetId,+ ranges: [lastRowRange],+ rowInfo: new ObjectArray<IRowData>(+ new Array(rowsCount).fill(undefined).map(() => ({+ h: lastRowHeight,+ hd: BooleanNumber.FALSE,+ }))+ ),+ };++ redoMutations.push({+ id: InsertRowMutation.id,+ params: insertRowParams,+ });++ const undoRowInsertionParams: IRemoveRowsMutationParams = InsertRowMutationUndoFactory(+ accessor,+ insertRowParams+ );++ undoMutations.push({ id: RemoveRowMutation.id, params: undoRowInsertionParams });+ }++ // 3. change merge cells+ // All merged cells that intersect with the area to the bottom of rang are removed+ // Merge cells completely in the bottom area of the range, added after recalculating the position+ const mergeData = worksheet.getMergeData();+ const removeMergeData: IRange[] = [];+ const addMergeData: IRange[] = [];+ mergeData.forEach((rect) => {+ for (let i = 0; i < range.length; i++) {+ const { startRow, startColumn, endColumn } = range[i];++ const intersects = Rectangle.intersects(+ { startRow, startColumn, endRow: lastRowIndex, endColumn },+ rect+ );++ // If the merge cell intersects with the range, it is removed+ if (intersects) {+ removeMergeData.push(rect);+ const contains = Rectangle.contains(+ { startRow, startColumn, endRow: lastRowIndex, endColumn },+ rect+ );++ // If the merge cell is completely contained in the range, it is added after recalculating the position+ if (contains) {+ const currentRowsCount = rowsObject[`${i}`][1] - rowsObject[`${i}`][0] + 1;+ addMergeData.push({+ startRow: rect.startRow + currentRowsCount,+ startColumn: rect.startColumn,+ endRow: rect.endRow + currentRowsCount,+ endColumn: rect.endColumn,+ });+ break;+ }+ }+ }+ });++ if (removeMergeData.length > 0) {+ const removeMergeParams: IRemoveWorksheetMergeMutationParams = {+ workbookId,+ worksheetId,+ ranges: removeMergeData,+ };+ redoMutations.push({+ id: RemoveWorksheetMergeMutation.id,+ params: removeMergeParams,+ });+ const undoRemoveMergeParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(+ accessor,+ removeMergeParams+ );+ undoMutations.push({ id: AddWorksheetMergeMutation.id, params: undoRemoveMergeParams });+ }++ if (addMergeData.length > 0) {+ const addMergeParams: IAddWorksheetMergeMutationParams = {+ workbookId,+ worksheetId,+ ranges: addMergeData,+ };+ redoMutations.push({+ id: AddWorksheetMergeMutation.id,+ params: addMergeParams,+ });+ const undoAddMergeParams: IRemoveWorksheetMergeMutationParams = AddMergeUndoMutationFactory(+ accessor,+ addMergeParams+ );+ undoMutations.push({ id: RemoveWorksheetMergeMutation.id, params: undoAddMergeParams });+ }+// execute do mutations and add undo mutations to undo stack if completed- const result = commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);+ const result = await sequenceExecute(redoMutations, commandService);if (result) {undoRedoService.pushUndoRedo({- // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面- // 通过勾子可以 hook 外部 controller 的代码来增加新的 actionURI: workbookId,- undo() {- return commandService.executeCommand(DeleteRangeMutation.id, deleteRangeMutationParams);- },- redo() {- return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);- },+ undo: async () => (await sequenceExecute(undoMutations.reverse(), commandService)).result,+ redo: async () => (await sequenceExecute(redoMutations, commandService)).result,});return true;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 7b641da955..dd78f87bd0 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@@ -1,19 +1,42 @@import {+ BooleanNumber,CommandType,Dimension,ICellData,+ IColumnData,ICommand,+ ICommandInfo,ICommandService,+ ILogService,+ IRange,IUndoRedoService,IUniverInstanceService,+ ObjectArray,ObjectMatrix,+ Rectangle,+ sequenceExecute,} from '@univerjs/core';import { IAccessor } from '@wendellhu/redi';-import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';+import {+ IAddWorksheetMergeMutationParams,+ IDeleteRangeMutationParams,+ IInsertColMutationParams,+ IInsertRangeMutationParams,+ IRemoveColMutationParams,+ IRemoveWorksheetMergeMutationParams,+} from '../../Basics/Interfaces/MutationInterface';import { SelectionManagerService } from '../../services/selection-manager.service';+import { AddMergeUndoMutationFactory, AddWorksheetMergeMutation } from '../mutations/add-worksheet-merge.mutation';import { DeleteRangeMutation } from '../mutations/delete-range.mutation';import { InsertRangeMutation, InsertRangeUndoMutationFactory } from '../mutations/insert-range.mutation';+import { InsertColMutation, InsertColMutationUndoFactory } from '../mutations/insert-row-col.mutation';+import { RemoveColMutation } from '../mutations/remove-row-col.mutation';+import {+ RemoveMergeUndoMutationFactory,+ RemoveWorksheetMergeMutation,+} from '../mutations/remove-worksheet-merge.mutation';+import { calculateTotalLength, IInterval } from './utils/selection-util';/*** The command to insert range.@@ -26,14 +49,17 @@ export const InsertRangeMoveRightCommand: ICommand = {const commandService = accessor.get(ICommandService);const undoRedoService = accessor.get(IUndoRedoService);const univerInstanceService = accessor.get(IUniverInstanceService);+ const logService = accessor.get(ILogService);const selectionManagerService = accessor.get(SelectionManagerService);- const workbookId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();- const worksheetId = univerInstanceService- .getCurrentUniverSheetInstance()+ if (selectionManagerService.isOverlapping()) {+ // TODO@Dushusir: use Dialog after Dialog component completed+ logService.error('Cannot use that command on overlapping selections.');+ return false;+ }- .getActiveSheet()- .getSheetId();+ const workbookId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();+ const worksheetId = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId();const range = selectionManagerService.getRangeDatas();if (!range?.length) return false;@@ -42,6 +68,10 @@ export const InsertRangeMoveRightCommand: ICommand = {const worksheet = workbook.getSheetBySheetId(worksheetId);if (!worksheet) return false;+ const redoMutations: ICommandInfo[] = [];+ const undoMutations: ICommandInfo[] = [];++ // 1. insert rangeconst cellValue = new ObjectMatrix<ICellData>();for (let i = 0; i < range.length; i++) {const { startRow, endRow, startColumn, endColumn } = range[i];@@ -61,24 +91,160 @@ export const InsertRangeMoveRightCommand: ICommand = {cellValue: cellValue.getData(),};+ redoMutations.push({ id: InsertRangeMutation.id, params: insertRangeMutationParams });+const deleteRangeMutationParams: IDeleteRangeMutationParams = InsertRangeUndoMutationFactory(accessor,insertRangeMutationParams);+ undoMutations.push({ id: DeleteRangeMutation.id, params: deleteRangeMutationParams });++ // 2. insert column+ // Only required when the last column has a value, and the column width is set to the column width of the last column+ let hasValueInLastColumn = false;+ let lastColumnWidth = 0;+ const lastColumnIndex = worksheet.getMaxColumns() - 1;+ const columnsObject: IInterval = {};+ for (let i = 0; i < range.length; i++) {+ const { startRow, endRow, startColumn, endColumn } = range[i];++ columnsObject[`${i}`] = [startColumn, endColumn];+ for (let row = startRow; row <= endRow; row++) {+ const lastCell = worksheet.getCell(row, lastColumnIndex);+ const lastCellValue = lastCell?.v;+ if (lastCellValue && lastCellValue !== '') {+ hasValueInLastColumn = true;+ lastColumnWidth = worksheet.getColumnWidth(lastColumnIndex);+ break;+ }+ }+ }++ // There may be overlap and deduplication is required+ const columnsCount = calculateTotalLength(columnsObject);+ if (hasValueInLastColumn) {+ const lastColumnRange = {+ startRow: range[0].startRow,+ endRow: range[0].endRow,+ startColumn: lastColumnIndex,+ endColumn: lastColumnIndex,+ };+ const insertColParams: IInsertColMutationParams = {+ workbookId,+ worksheetId,+ ranges: [lastColumnRange],+ colInfo: new ObjectArray<IColumnData>(+ new Array(columnsCount).fill(undefined).map(() => ({+ w: lastColumnWidth,+ hd: BooleanNumber.FALSE,+ }))+ ),+ };++ redoMutations.push({+ id: InsertColMutation.id,+ params: insertColParams,+ });++ const undoColInsertionParams: IRemoveColMutationParams = InsertColMutationUndoFactory(+ accessor,+ insertColParams+ );++ undoMutations.push({ id: RemoveColMutation.id, params: undoColInsertionParams });+ }++ // 3. change merge cells+ // All merged cells that intersect with the area to the right of rang are removed+ // Merge cells completely in the right area of the range, added after recalculating the position+ const mergeData = worksheet.getMergeData();+ const removeMergeData: IRange[] = [];+ const addMergeData: IRange[] = [];+ mergeData.forEach((rect) => {+ for (let i = 0; i < range.length; i++) {+ const { startRow, endRow, startColumn } = range[i];++ const intersects = Rectangle.intersects(+ {+ startRow,+ startColumn,+ endRow,+ endColumn: lastColumnIndex,+ },+ rect+ );++ // If the merge cell intersects with the range, it is removed+ if (intersects) {+ removeMergeData.push(rect);+ const contains = Rectangle.contains(+ {+ startRow,+ startColumn,+ endRow,+ endColumn: lastColumnIndex,+ },+ rect+ );++ // If the merge cell is completely contained in the range, it is added after recalculating the position++ if (contains) {+ const currentColumnsCount = columnsObject[`${i}`][1] - columnsObject[`${i}`][0] + 1;+ addMergeData.push({+ startRow: rect.startRow,+ startColumn: rect.startColumn + currentColumnsCount,+ endRow: rect.endRow,+ endColumn: rect.endColumn + currentColumnsCount,+ });+ break;+ }+ }+ }+ });++ if (removeMergeData.length > 0) {+ const removeMergeParams: IRemoveWorksheetMergeMutationParams = {+ workbookId,+ worksheetId,+ ranges: removeMergeData,+ };+ redoMutations.push({+ id: RemoveWorksheetMergeMutation.id,+ params: removeMergeParams,+ });+ const undoRemoveMergeParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(+ accessor,+ removeMergeParams+ );+ undoMutations.push({ id: AddWorksheetMergeMutation.id, params: undoRemoveMergeParams });+ }++ if (addMergeData.length > 0) {+ const addMergeParams: IAddWorksheetMergeMutationParams = {+ workbookId,+ worksheetId,+ ranges: addMergeData,+ };+ redoMutations.push({+ id: AddWorksheetMergeMutation.id,+ params: addMergeParams,+ });+ const undoAddMergeParams: IRemoveWorksheetMergeMutationParams = AddMergeUndoMutationFactory(+ accessor,+ addMergeParams+ );+ undoMutations.push({ id: RemoveWorksheetMergeMutation.id, params: undoAddMergeParams });+ }+// execute do mutations and add undo mutations to undo stack if completed- const result = commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);- if (result) {+ const result = await sequenceExecute(redoMutations, commandService);+ if (result.result) {undoRedoService.pushUndoRedo({- // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面- // 通过勾子可以 hook 外部 controller 的代码来增加新的 actionURI: workbookId,- undo() {- return commandService.executeCommand(DeleteRangeMutation.id, deleteRangeMutationParams);- },- redo() {- return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);- },+ undo: async () => (await sequenceExecute(undoMutations.reverse(), commandService)).result,+ redo: async () => (await sequenceExecute(redoMutations, commandService)).result,});return true;diff --git a/packages/base-sheets/src/commands/commands/utils/selection-util.ts b/packages/base-sheets/src/commands/commands/utils/selection-util.tsindex efbfc683c4..4140ae5785 100644--- a/packages/base-sheets/src/commands/commands/utils/selection-util.ts+++ b/packages/base-sheets/src/commands/commands/utils/selection-util.ts@@ -668,3 +668,36 @@ export function getPrimaryForRange(range: IRange, worksheet: Worksheet): ISelectisMergedMainCell: true,};}++export interface IInterval {+ [index: string]: [start: number, end: number];+}++/**+ * Calculate the real length of the intervals+ * @param intervalsObject+ * @returns+ */+export function calculateTotalLength(intervalsObject: IInterval): number {+ const points: number[] = [];++ // Put the start and end points of the interval into the points array++ Object.keys(intervalsObject).forEach((key: string) => {+ const [start, end] = intervalsObject[key];+ points.push(start, end);+ });++ // Sort the points array+ points.sort((a, b) => a - b);++ let totalLength = 0;+ for (let i = 0; i < points.length - 1; i++) {+ const start = points[i];+ const end = points[i + 1];+ const length = end - start;+ totalLength += length;+ }++ return totalLength + 1;+}diff --git a/packages/base-sheets/src/commands/mutations/delete-range.mutation.ts b/packages/base-sheets/src/commands/mutations/delete-range.mutation.tsindex c0c6936a68..e407a9db58 100644--- a/packages/base-sheets/src/commands/mutations/delete-range.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/delete-range.mutation.ts@@ -84,8 +84,8 @@ export const DeleteRangeMutation: IMutation<IDeleteRangeMutationParams, boolean>if (!worksheet) return false;const cellMatrix = worksheet.getCellMatrix();- const lastEndRow = worksheet.getConfig().rowCount;- const lastEndColumn = worksheet.getConfig().columnCount;+ const lastEndRow = worksheet.getLastRowWithContent();+ const lastEndColumn = worksheet.getLastColumnWithContent();for (let i = 0; i < params.ranges.length; i++) {const { startRow, endRow, startColumn, endColumn } = params.ranges[i];@@ -99,17 +99,7 @@ export const DeleteRangeMutation: IMutation<IDeleteRangeMutationParams, boolean>for (let c = startColumn; c <= endColumn; c++) {// get value blow current rangeconst value = cellMatrix.getValue(r + rows, c);- if (value) {- cellMatrix.setValue(r, c, Tools.deepClone(value as ICellData));- } else {- // null means delete- const originValue = cellMatrix.getValue(r, c);- if (originValue) {- cellMatrix.deleteValue(r, c);- // Deleting data will cause the column number to change, so subtract 1 here in advance- c--;- }- }+ cellMatrix.setValue(r, c, value || {});}}} else if (params.shiftDimension === Dimension.COLUMNS) {@@ -119,19 +109,7 @@ export const DeleteRangeMutation: IMutation<IDeleteRangeMutationParams, boolean>// get value blow current rangeconst value = cellMatrix.getValue(r, c + columns);- if (value) {- cellMatrix.setValue(r, c, Tools.deepClone(value as ICellData));- } else {- // null means delete- const originValue = cellMatrix.getValue(r, c);- if (originValue) {- for (let i = 0; i <= endColumn; i++) {- cellMatrix.deleteValue(r, c);- }- break;- // Deleting data will cause the column number to change, so subtract 1 here in advance- }- }+ cellMatrix.setValue(r, c, value || {});}}}diff --git a/packages/base-sheets/src/commands/mutations/insert-range.mutation.ts b/packages/base-sheets/src/commands/mutations/insert-range.mutation.tsindex d491f2d237..9a293a496f 100644--- a/packages/base-sheets/src/commands/mutations/insert-range.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/insert-range.mutation.ts@@ -65,11 +65,6 @@ export const InsertRangeMutation: IMutation<IInsertRangeMutationParams, boolean>}}// insert cell value from user- // for (let r = endRow; r >= startRow; r--) {- // for (let c = startColumn; c <= endColumn; c++) {- // cellMatrix.setValue(r, c, (cellValue as ICellData)[r - startRow][c - startColumn]);- // }- // }for (let r = startRow; r <= endRow; r++) {for (let c = endColumn; c >= startColumn; c--) {cellMatrix.setValue(r, c, params.cellValue[r][c]);diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.tsindex 0d8912f922..9631ab56c8 100644--- a/packages/base-sheets/src/index.ts+++ b/packages/base-sheets/src/index.ts@@ -29,6 +29,8 @@ export { ClearSelectionFormatCommand } from './commands/commands/clear-selectionexport { CopySheetCommand } from './commands/commands/copy-worksheet.command';export { DeleteRangeMoveLeftCommand } from './commands/commands/delete-range-move-left.command';export { DeleteRangeMoveUpCommand } from './commands/commands/delete-range-move-up.command';+export { InsertRangeMoveDownCommand } from './commands/commands/insert-range-move-down.command';+export { InsertRangeMoveRightCommand } from './commands/commands/insert-range-move-right.command';export type { IInsertColCommandParams, IInsertRowCommandParams } from './commands/commands/insert-row-col.command';export {InsertColAfterCommand,diff --git a/packages/base-sheets/src/services/selection-manager.service.ts b/packages/base-sheets/src/services/selection-manager.service.tsindex 275be46e62..b72e3c1ebd 100644--- a/packages/base-sheets/src/services/selection-manager.service.ts+++ b/packages/base-sheets/src/services/selection-manager.service.ts@@ -236,6 +236,30 @@ export class SelectionManagerService implements IDisposable {};}+ /**+ * Determine whether multiple current selections overlap+ */+ isOverlapping(): boolean {+ const selectionDataList = this.getSelections();+ if (selectionDataList == null) {+ return false;+ }++ return selectionDataList.some(({ range }, index) =>+ selectionDataList.some(({ range: range2 }, index2) => {+ if (index === index2) {+ return false;+ }+ return (+ range.startRow <= range2.endRow &&+ range.endRow >= range2.startRow &&+ range.startColumn <= range2.endColumn &&+ range.endColumn >= range2.startColumn+ );+ })+ );+ }+private _getSelectionDatas(param: Nullable<ISelectionManagerSearchParam>) {if (param == null) {return;@@ -284,7 +308,6 @@ export class SelectionManagerService implements IDisposable {this.refresh({ pluginName, unitId, sheetId });}-private _replaceByParam(insertParam: ISelectionManagerInsertParam) {const { pluginName, unitId, sheetId, selectionDatas } = insertParam;diff --git a/packages/core/src/Shared/ObjectMatrix.ts b/packages/core/src/Shared/ObjectMatrix.tsindex 9ef3a3b199..fad5b8d840 100644--- a/packages/core/src/Shared/ObjectMatrix.ts+++ b/packages/core/src/Shared/ObjectMatrix.ts@@ -257,16 +257,15 @@ export class ObjectMatrix<T> {getRange(): IRange {const startRow = 0;const startColumn = 0;- const endRow = this.getSizeOf();+ const endRow = this.getLength() - 1;let endColumn = 0;const length = this.getLength();+ // OPTIMIZE: It may be possible to reduce the number of cyclesfor (let i = 0; i < length; i++) {const row = this.getRow(i);if (row) {- const sizeof = row.getSizeOf();- if (row.getSizeOf() > endColumn) {- endColumn = sizeof - 1;- }+ const columnLength = row.getLength() - 1;+ endColumn = columnLength > endColumn ? columnLength : endColumn;}}return {diff --git a/packages/core/src/sheets/__tests__/create-core-test-bed.ts b/packages/core/src/sheets/__tests__/create-core-test-bed.tsnew file mode 100644index 0000000000..1a2249bcd7--- /dev/null+++ b/packages/core/src/sheets/__tests__/create-core-test-bed.ts@@ -0,0 +1,81 @@+import { Dependency, Inject, Injector } from '@wendellhu/redi';++import { Univer } from '../../Basics/Univer';+import { Plugin, PluginType } from '../../plugin/plugin';+import { IUniverInstanceService } from '../../services/instance/instance.service';+import { ILogService } from '../../services/log/log.service';+import { LocaleType } from '../../Types/Enum/LocaleType';+import { IWorkbookConfig } from '../../Types/Interfaces/IWorkbookData';++const TEST_WORKBOOK_DATA: IWorkbookConfig = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ cellData: {+ '0': {+ '0': {+ v: 'A1',+ },+ '1': {+ v: 'B1',+ },+ },+ },+ },+ },+ createdTime: '',+ creator: '',+ extensions: [],+ lastModifiedBy: '',+ locale: LocaleType.EN,+ modifiedTime: '',+ name: '',+ sheetOrder: [],+ styles: {},+ timeZone: '',+};++export function createCoreTestBed(workbookConfig?: IWorkbookConfig, dependencies?: Dependency[]) {+ const univer = new Univer();++ let get: Injector['get'] | undefined;++ class TestSpyPlugin extends Plugin {+ static override type = PluginType.Sheet;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super('test-spy-plugin');++ this._injector = _injector;+ get = this._injector.get.bind(_injector);+ }++ override onDestroy(): void {+ get = undefined;+ }+ }++ univer.registerPlugin(TestSpyPlugin);+ const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA);++ if (get === undefined) {+ throw new Error('[TestPlugin]: not hooked on!');+ }++ const univerInstanceService = get(IUniverInstanceService);+ univerInstanceService.focusUniverInstance('test');++ const logService = get(ILogService);+ logService.toggleLogEnabled(false);++ return {+ univer,+ get,+ sheet,+ };+}diff --git a/packages/core/src/sheets/__tests__/worksheet.spec.ts b/packages/core/src/sheets/__tests__/worksheet.spec.tsnew file mode 100644index 0000000000..b2e1af20b5--- /dev/null+++ b/packages/core/src/sheets/__tests__/worksheet.spec.ts@@ -0,0 +1,72 @@+import { Injector } from '@wendellhu/redi';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { Univer } from '../../Basics/Univer';+import { IUniverInstanceService } from '../../services/instance/instance.service';+import { LocaleType } from '../../Types/Enum/LocaleType';+import { IWorkbookConfig } from '../../Types/Interfaces/IWorkbookData';+import { createCoreTestBed } from './create-core-test-bed';++const WORKBOOK_DATA: IWorkbookConfig = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ cellData: {+ '2': {+ '2': {+ v: 'C3',+ },+ '3': {+ v: 'D3',+ },+ },+ '3': {+ '2': {+ v: 'C4',+ },+ '3': {+ v: 'D4',+ },+ },+ },+ },+ },+ createdTime: '',+ creator: '',+ extensions: [],+ lastModifiedBy: '',+ locale: LocaleType.EN,+ modifiedTime: '',+ name: '',+ sheetOrder: [],+ styles: {},+ timeZone: '',+};++describe('Test SheetInterceptorService', () => {+ let univer: Univer;+ let get: Injector['get'];++ beforeEach(() => {+ const testBed = createCoreTestBed(WORKBOOK_DATA);+ univer = testBed.univer;+ get = testBed.get;+ });++ afterEach(() => univer.dispose());++ describe('Test worksheet', () => {+ it('getLastRowWithContent', () => {+ const univerInstanceService = get(IUniverInstanceService);+ const sheet = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet()!;+ expect(sheet.getLastRowWithContent()).toBe(3);+ });+ it('getLastColumnWithContent', () => {+ const univerInstanceService = get(IUniverInstanceService);+ const sheet = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet()!;+ expect(sheet.getLastColumnWithContent()).toBe(3);+ });+ });+});diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.tsindex 18cc03dfec..1672f1550a 100644--- a/packages/core/src/sheets/worksheet.ts+++ b/packages/core/src/sheets/worksheet.ts@@ -425,7 +425,7 @@ export class Worksheet {* @returns the position of the last row that has content.*/getLastRowWithContent(): number {- return this._cellData.getLength();+ return this._cellData.getLength() - 1;}/**diff --git a/packages/ui-plugin-sheets/src/Locale/en.ts b/packages/ui-plugin-sheets/src/Locale/en.tsindex 50060db8cb..ac1543ac88 100644--- a/packages/ui-plugin-sheets/src/Locale/en.ts+++ b/packages/ui-plugin-sheets/src/Locale/en.ts@@ -431,6 +431,7 @@ export default {insertColumn: 'InsertColumn',delete: 'Delete',deleteCell: 'Delete cell',+ insertCell: 'Insert cell',deleteSelected: 'Delete selected ',hide: 'Hide',hideSelected: 'Hide selected ',@@ -454,6 +455,8 @@ export default {bottom: 'Bottom',moveLeft: 'Move left',moveUp: 'Move up',+ moveRight: 'Move right',+ moveDown: 'Move down',add: 'Add',row: 'Row',column: 'Column',diff --git a/packages/ui-plugin-sheets/src/Locale/zh.ts b/packages/ui-plugin-sheets/src/Locale/zh.tsindex 347606633d..68d3e5397d 100644--- a/packages/ui-plugin-sheets/src/Locale/zh.ts+++ b/packages/ui-plugin-sheets/src/Locale/zh.ts@@ -294,6 +294,7 @@ export default {insertRow: '插入行',insertColumn: '插入列',deleteCell: '删除单元格',+ insertCell: '插入单元格',deleteSelected: '删除选中',hide: '隐藏',hideSelected: '隐藏选中',@@ -317,6 +318,8 @@ export default {bottom: '下',moveLeft: '左移',moveUp: '上移',+ moveRight: '右移',+ moveDown: '下移',add: '增加',row: '行',column: '列',diff --git a/packages/ui-plugin-sheets/src/controller/menu/menu.ts b/packages/ui-plugin-sheets/src/controller/menu/menu.tsindex 7d12260339..e2ca230263 100644--- a/packages/ui-plugin-sheets/src/controller/menu/menu.ts+++ b/packages/ui-plugin-sheets/src/controller/menu/menu.ts@@ -7,6 +7,8 @@ import {DeleteRangeMoveUpCommand,InsertColAfterCommand,InsertColBeforeCommand,+ InsertRangeMoveDownCommand,+ InsertRangeMoveRightCommand,InsertRowAfterCommand,InsertRowBeforeCommand,RemoveColCommand,@@ -1350,6 +1352,34 @@ export function DeleteRangeMoveUpMenuItemFactory(): IMenuButtonItem {positions: DELETE_RANGE_MENU_ID,};}+const INSERT_RANGE_MENU_ID = 'sheet.menu.insert-range';+export function InsertRangeMenuItemFactory(): IMenuSelectorItem<string> {+ return {+ id: INSERT_RANGE_MENU_ID,+ type: MenuItemType.SUBITEMS,+ title: 'rightClick.insertCell',+ positions: [MenuPosition.CONTEXT_MENU],+ selectType: SelectTypes.NEO,+ };+}++export function InsertRangeMoveRightMenuItemFactory(): IMenuButtonItem {+ return {+ id: InsertRangeMoveRightCommand.id,+ type: MenuItemType.BUTTON,+ title: 'rightClick.moveRight',+ positions: INSERT_RANGE_MENU_ID,+ };+}++export function InsertRangeMoveDownMenuItemFactory(): IMenuButtonItem {+ return {+ id: InsertRangeMoveDownCommand.id,+ type: MenuItemType.BUTTON,+ title: 'rightClick.moveDown',+ positions: INSERT_RANGE_MENU_ID,+ };+}// right menu in main sheet barexport function DeleteSheetMenuItemFactory(): IMenuButtonItem {diff --git a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.tsindex 4b07d39349..e04ba05719 100644--- a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts+++ b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts@@ -54,6 +54,9 @@ import {HorizontalAlignMenuItemFactory,InsertColAfterMenuItemFactory,InsertColBeforeMenuItemFactory,+ InsertRangeMenuItemFactory,+ InsertRangeMoveDownMenuItemFactory,+ InsertRangeMoveRightMenuItemFactory,InsertRowAfterMenuItemFactory,InsertRowBeforeMenuItemFactory,ItalicMenuItemFactory,@@ -188,6 +191,9 @@ export class SheetUIController extends Disposable {DeleteRangeMenuItemFactory,DeleteRangeMoveLeftMenuItemFactory,DeleteRangeMoveUpMenuItemFactory,+ InsertRangeMenuItemFactory,+ InsertRangeMoveRightMenuItemFactory,+ InsertRangeMoveDownMenuItemFactory,FrozenMenuItemFactory,// toolbar