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): move rows & columns (#253)
Wenzhao Hu6e71bbeda27d
diff --git a/packages/base-sheets/package.json b/packages/base-sheets/package.jsonindex b2a7dd5b44..b02bd22e9f 100644--- a/packages/base-sheets/package.json+++ b/packages/base-sheets/package.json@@ -45,6 +45,7 @@"dependencies": {"@univerjs/base-render": "workspace:^0.0.1","@univerjs/core": "workspace:^0.0.1",+ "@univerjs/base-ui": "workspace:^0.0.1","@wendellhu/redi": "^0.12.8","react": "^18.2.0","react-dom": "^18.2.0",diff --git a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts b/packages/base-sheets/src/Controller/BasicWorksheet.controller.tsindex f1248b91e3..3691b8e031 100644--- a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts+++ b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts@@ -1,7 +1,6 @@import { Disposable, ICommandService, IStyleData, LifecycleStages, OnLifecycle } from '@univerjs/core';import { IDisposable } from '@wendellhu/redi';-import { SetZoomRatioCommand, SetZoomRatioMutation } from '..';import {AddWorksheetMergeAllCommand,AddWorksheetMergeCommand,@@ -23,7 +22,7 @@ import {InsertRowCommand,} from '../commands/commands/insert-row-col.command';import { InsertSheetCommand } from '../commands/commands/insert-sheet.command';-import { MoveRowsCommand } from '../commands/commands/move-rows.command';+import { MoveColsCommand, MoveRowsCommand } from '../commands/commands/move-rows-cols.command';import { RemoveColCommand, RemoveRowCommand } from '../commands/commands/remove-row-col.command';import { RemoveSheetCommand } from '../commands/commands/remove-sheet.command';import { RemoveWorksheetMergeCommand } from '../commands/commands/remove-worksheet-merge.command';@@ -64,6 +63,7 @@ import { DeleteRangeMutation } from '../commands/mutations/delete-range.mutationimport { InsertRangeMutation } from '../commands/mutations/insert-range.mutation';import { InsertColMutation, InsertRowMutation } from '../commands/mutations/insert-row-col.mutation';import { InsertSheetMutation } from '../commands/mutations/insert-sheet.mutation';+import { MoveColsMutation, MoveRowsMutation } from '../commands/mutations/move-rows-cols.mutation';import { RemoveColMutation, RemoveRowMutation } from '../commands/mutations/remove-row-col.mutation';import { RemoveSheetMutation } from '../commands/mutations/remove-sheet.mutation';import { RemoveWorksheetMergeMutation } from '../commands/mutations/remove-worksheet-merge.mutation';@@ -81,6 +81,7 @@ import { SetWorksheetOrderMutation } from '../commands/mutations/set-worksheet-oimport { SetWorksheetRowHeightMutation } from '../commands/mutations/set-worksheet-row-height.mutation';import { SetWorksheetRowHideMutation } from '../commands/mutations/set-worksheet-row-hide.mutation';import { SetWorksheetRowShowMutation } from '../commands/mutations/set-worksheet-row-show.mutation';+import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';export interface IStyleTypeValue<T> {type: keyof IStyleData;@@ -129,6 +130,9 @@ export class BasicWorksheetController extends Disposable implements IDisposableRemoveColCommand,RemoveColMutation,MoveRowsCommand,+ MoveColsCommand,+ MoveRowsMutation,+ MoveColsMutation,SetColWidthCommand,SetWorksheetColWidthMutation,@@ -181,8 +185,7 @@ export class BasicWorksheetController extends Disposable implements IDisposableSetFrozenCommand,SetFrozenMutation,SetFrozenCancelCommand,- SetZoomRatioCommand,- SetZoomRatioMutation,+ SetZoomRatioOperation,].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));}}diff --git a/packages/base-sheets/src/Controller/Selection.controller.ts b/packages/base-sheets/src/Controller/Selection.controller.tsindex 1e9c80e9a5..1a7af30a1e 100644--- a/packages/base-sheets/src/Controller/Selection.controller.ts+++ b/packages/base-sheets/src/Controller/Selection.controller.ts@@ -18,8 +18,8 @@ import { Inject } from '@wendellhu/redi';import { getSheetObject, ISheetObjectParam } from '../Basics/component-tools';import { VIEWPORT_KEY } from '../Basics/Const/DEFAULT_SPREADSHEET_VIEW';-import { ISetZoomRatioMutationParams, SetZoomRatioMutation } from '../commands/mutations/set-zoom-ratio.mutation';import { SetSelectionsOperation } from '../commands/operations/selection.operation';+import { ISetZoomRatioOperationParams, SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../services/selection-manager.service';import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';@@ -167,7 +167,7 @@ export class SelectionController extends Disposable {}private _commandExecutedListener() {- const updateCommandList = [SetZoomRatioMutation.id];+ const updateCommandList = [SetZoomRatioOperation.id];this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {@@ -175,7 +175,7 @@ export class SelectionController extends Disposable {const workbook = this._currentUniverService.getCurrentUniverSheetInstance();const worksheet = workbook.getActiveSheet();- const params = command.params as ISetZoomRatioMutationParams;+ const params = command.params as ISetZoomRatioOperationParams;const { workbookId, worksheetId } = params;if (!(workbookId === workbook.getUnitId() && worksheetId === worksheet.getSheetId())) {return;diff --git a/packages/base-sheets/src/Controller/header-move.controller.ts b/packages/base-sheets/src/Controller/header-move.controller.tsindex dd7f568c68..dbb44c6574 100644--- a/packages/base-sheets/src/Controller/header-move.controller.ts+++ b/packages/base-sheets/src/Controller/header-move.controller.ts@@ -23,8 +23,12 @@ import { Inject } from '@wendellhu/redi';import { getCoordByOffset, getSheetObject, ISheetObjectParam } from '../Basics/component-tools';import { SHEET_COMPONENT_HEADER_LAYER_INDEX, VIEWPORT_KEY } from '../Basics/Const/DEFAULT_SPREADSHEET_VIEW';-import { IMoveColumnsCommandParams, MoveColumnsCommand } from '../commands/commands/move-columns-to.command';-import { IMoveRowsCommandParams, MoveRowsCommand } from '../commands/commands/move-rows.command';+import {+ IMoveColsCommandParams,+ IMoveRowsCommandParams,+ MoveColsCommand,+ MoveRowsCommand,+} from '../commands/commands/move-rows-cols.command';import { SelectionManagerService } from '../services/selection-manager.service';import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';@@ -266,9 +270,9 @@ export class HeaderMoveController extends Disposable {this._changeToRow = this._changeFromRow = -1;} else {if (this._changeFromColumn !== this._changeToColumn && this._changeToColumn !== -1) {- this._commandService.executeCommand<IMoveColumnsCommandParams>(MoveColumnsCommand.id, {- fromColumn: this._changeFromColumn,- toColumn: this._changeToColumn,+ this._commandService.executeCommand<IMoveColsCommandParams>(MoveColsCommand.id, {+ fromCol: this._changeFromColumn,+ toCol: this._changeToColumn,});}diff --git a/packages/base-sheets/src/Controller/sheet-render.controller.ts b/packages/base-sheets/src/Controller/sheet-render.controller.tsindex ab28a46c8b..5e0efa5c0f 100644--- a/packages/base-sheets/src/Controller/sheet-render.controller.ts+++ b/packages/base-sheets/src/Controller/sheet-render.controller.ts@@ -19,6 +19,7 @@ import { Inject } from '@wendellhu/redi';import { SHEET_VIEW_KEY } from '../Basics/Const/DEFAULT_SPREADSHEET_VIEW';import { AddWorksheetMergeMutation } from '../commands/mutations/add-worksheet-merge.mutation';import { InsertColMutation, InsertRowMutation } from '../commands/mutations/insert-row-col.mutation';+import { MoveRowsMutation } from '../commands/mutations/move-rows-cols.mutation';import { RemoveColMutation, RemoveRowMutation } from '../commands/mutations/remove-row-col.mutation';import { RemoveWorksheetMergeMutation } from '../commands/mutations/remove-worksheet-merge.mutation';import { SetWorksheetActivateMutation } from '../commands/mutations/set-worksheet-activate.mutation';@@ -106,6 +107,7 @@ export class SheetRenderController extends Disposable {RemoveColMutation.id,AddWorksheetMergeMutation.id,RemoveWorksheetMergeMutation.id,+ MoveRowsMutation.id,];this.disposeWithMe(diff --git a/packages/base-sheets/src/Controller/zoom.controller.ts b/packages/base-sheets/src/Controller/zoom.controller.tsindex 1d7300351c..f338aa73f9 100644--- a/packages/base-sheets/src/Controller/zoom.controller.ts+++ b/packages/base-sheets/src/Controller/zoom.controller.ts@@ -11,7 +11,7 @@ import { Inject } from '@wendellhu/redi';import { getSheetObject } from '../Basics/component-tools';import { VIEWPORT_KEY } from '../Basics/Const/DEFAULT_SPREADSHEET_VIEW';-import { SetZoomRatioMutation } from '../commands/mutations/set-zoom-ratio.mutation';+import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';import { ScrollManagerService } from '../services/scroll-manager.service';import { SelectionManagerService } from '../services/selection-manager.service';import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';@@ -71,7 +71,7 @@ export class ZoomController extends Disposable {let nextRatio = +parseFloat(`${currentRatio + ratioDelta}`).toFixed(1);nextRatio = nextRatio >= 4 ? 4 : nextRatio <= 0.1 ? 0.1 : nextRatio;- this._commandService.executeCommand(SetZoomRatioMutation.id, {+ this._commandService.executeCommand(SetZoomRatioOperation.id, {zoomRatio: nextRatio,workbookId: workbook.getUnitId(),worksheetId: sheet.getSheetId(),@@ -98,7 +98,7 @@ export class ZoomController extends Disposable {}private _commandExecutedListener() {- const updateCommandList = [SetZoomRatioMutation.id];+ const updateCommandList = [SetZoomRatioOperation.id];this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {diff --git a/packages/base-sheets/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/base-sheets/src/commands/commands/__tests__/create-command-test-bed.tsindex 4ef108b9e1..2e04dc0cc7 100644--- a/packages/base-sheets/src/commands/commands/__tests__/create-command-test-bed.ts+++ b/packages/base-sheets/src/commands/commands/__tests__/create-command-test-bed.ts@@ -7,7 +7,7 @@ import {PluginType,Univer,} from '@univerjs/core';-import { Inject, Injector } from '@wendellhu/redi';+import { Dependency, Inject, Injector } from '@wendellhu/redi';import { BorderStyleManagerService } from '../../../services/border-style-manager.service';import { SelectionManagerService } from '../../../services/selection-manager.service';@@ -42,7 +42,7 @@ const TEST_WORKBOOK_DATA_DEMO: IWorkbookConfig = {timeZone: '',};-export function createCommandTestBed(workbookConfig?: IWorkbookConfig) {+export function createCommandTestBed(workbookConfig?: IWorkbookConfig, dependencies?: Dependency[]) {const univer = new Univer();let get: Injector['get'] | undefined;@@ -66,6 +66,8 @@ export function createCommandTestBed(workbookConfig?: IWorkbookConfig) {override onStarting(injector: Injector): void {injector.add([SelectionManagerService]);injector.add([BorderStyleManagerService]);++ dependencies?.forEach((d) => injector.add(d));}override onDestroy(): void {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-rows-cols.command.spec.tssimilarity index 98%rename from packages/base-sheets/src/commands/commands/__tests__/insert-remove-row-col.spec.tsrename to packages/base-sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.tsindex 606a344424..b0c8526be8 100644--- a/packages/base-sheets/src/commands/commands/__tests__/insert-remove-row-col.spec.ts+++ b/packages/base-sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts@@ -35,7 +35,7 @@ import {import { RemoveColCommand, RemoveRowCommand } from '../remove-row-col.command';import { createCommandTestBed } from './create-command-test-bed';-describe('Test insert and remove row col commands', () => {+describe('Test insert and remove rows cols commands', () => {let univer: Univer;let get: Injector['get'];let commandService: ICommandService;@@ -65,9 +65,7 @@ describe('Test insert and remove row col commands', () => {DeleteRangeMutation,AddWorksheetMergeMutation,RemoveWorksheetMergeMutation,- ].forEach((c) => {- commandService.registerCommand(c);- });+ ].forEach((c) => commandService.registerCommand(c));const selectionManagerService = get(SelectionManagerService);selectionManagerService.setCurrentSelection({@@ -324,7 +322,6 @@ const TEST_ROW_COL_INSERTION_DEMO: IWorkbookConfig = {endColumn: 1,},],- // mergeData:rowCount: 20,columnCount: 20,},diff --git a/packages/base-sheets/src/commands/commands/__tests__/insert-row-col.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/insert-row-col.spec.tsdeleted file mode 100644index 81542a8c89..0000000000--- a/packages/base-sheets/src/commands/commands/__tests__/insert-row-col.spec.ts+++ /dev/null@@ -1,306 +0,0 @@-/* 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 { createCommandTestBed } from './create-command-test-bed';--describe('Test insert 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,-- InsertColMutation,- InsertRowMutation,- InsertRangeMutation,- AddWorksheetMergeMutation,- RemoveWorksheetMergeMutation,- RemoveRowMutation,- RemoveColMutation,- DeleteRangeMutation,- ].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 });- });- });-});--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/__tests__/move-rows-cols.command.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.tsnew file mode 100644index 0000000000..87019859bf--- /dev/null+++ b/packages/base-sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts@@ -0,0 +1,399 @@+/* eslint-disable no-magic-numbers */+import { INotificationService } from '@univerjs/base-ui';+import {+ ICellData,+ ICommandService,+ ICurrentUniverService,+ IRange,+ IWorkbookConfig,+ LocaleType,+ Nullable,+ RANGE_TYPE,+ RedoCommand,+ toDisposable,+ Tools,+ UndoCommand,+ Univer,+} from '@univerjs/core';+import { Injector } from '@wendellhu/redi';+import { 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 { MoveColsMutation, MoveRowsMutation } from '../../mutations/move-rows-cols.mutation';+import { RemoveWorksheetMergeMutation } from '../../mutations/remove-worksheet-merge.mutation';+import { SetSelectionsOperation } from '../../operations/selection.operation';+import {+ IMoveColsCommandParams,+ IMoveRowsCommandParams,+ MoveColsCommand,+ MoveRowsCommand,+} from '../move-rows-cols.command';+import { createCommandTestBed } from './create-command-test-bed';++describe('Test move rows cols', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;++ beforeEach(() => {+ const testBed = createMoveRowsColsTestBed();+ univer = testBed.univer;+ get = testBed.get;++ commandService = get(ICommandService);++ [+ MoveRowsCommand,+ MoveColsCommand,+ MoveRowsMutation,+ MoveColsMutation,+ RemoveWorksheetMergeMutation,+ AddWorksheetMergeMutation,+ SetSelectionsOperation,+ ].forEach((c) => commandService.registerCommand(c));++ const selectionManagerService = get(SelectionManagerService);+ selectionManagerService.setCurrentSelection({+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,+ unitId: 'test',+ sheetId: 'sheet1',+ });+ });++ 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 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];+ }++ function getRowHeight(row: number): number {+ const currentService = get(ICurrentUniverService);+ const workbook = currentService.getCurrentUniverSheetInstance();+ const worksheet = workbook.getActiveSheet();+ return worksheet.getRowHeight(row);+ }++ function getColWidth(col: number): number {+ const currentService = get(ICurrentUniverService);+ const workbook = currentService.getCurrentUniverSheetInstance();+ const worksheet = workbook.getActiveSheet();+ return worksheet.getColumnWidth(col);+ }++ function getCurrentSelection(): IRange {+ const selectionManagerService = get(SelectionManagerService);+ const currentSelection = selectionManagerService.getSelections();+ if (!currentSelection) {+ throw new Error('No current selection');+ }+ return currentSelection[0].range;+ }++ describe('Move rows', () => {+ it('Should move forward works', async () => {+ selectRow(18, 19);++ const result = await commandService.executeCommand<IMoveRowsCommandParams>(MoveRowsCommand.id, {+ fromRow: 18,+ toRow: 1,+ });+ expect(result).toEqual(true);+ expect(getCellInfo(0, 0)?.v).toEqual('A1');+ expect(getCellInfo(3, 1)?.v).toEqual('B2');+ expect(getMergedInfo(3, 1)).toEqual({ startRow: 3, endRow: 3, startColumn: 1, endColumn: 2 });+ expect(getMergedInfo(4, 1)).toEqual({ startRow: 4, endRow: 5, startColumn: 1, endColumn: 1 });+ expect(getRowHeight(1)).toBe(19);+ expect(getRowHeight(3)).toBe(30);+ expect(getCurrentSelection()).toEqual({+ startRow: 1,+ endRow: 2,+ startColumn: 0,+ endColumn: 19,+ rangeType: RANGE_TYPE.ROW,+ });++ const undoResult = await commandService.executeCommand(UndoCommand.id);+ expect(undoResult).toEqual(true);+ expect(getCellInfo(0, 0)?.v).toEqual('A1');+ expect(getCellInfo(1, 1)?.v).toEqual('B2');+ expect(getMergedInfo(1, 1)).toEqual({ startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 });+ expect(getMergedInfo(2, 1)).toEqual({ startRow: 2, endRow: 3, startColumn: 1, endColumn: 1 });+ expect(getRowHeight(1)).toBe(30);+ expect(getCurrentSelection()).toEqual({+ startRow: 18,+ endRow: 19,+ startColumn: 0,+ endColumn: 19,+ rangeType: RANGE_TYPE.ROW,+ });++ const redoResult = await commandService.executeCommand(RedoCommand.id);+ expect(redoResult).toEqual(true);+ expect(getCellInfo(0, 0)?.v).toEqual('A1');+ expect(getCellInfo(3, 1)?.v).toEqual('B2');+ expect(getMergedInfo(3, 1)).toEqual({ startRow: 3, endRow: 3, startColumn: 1, endColumn: 2 });+ expect(getMergedInfo(4, 1)).toEqual({ startRow: 4, endRow: 5, startColumn: 1, endColumn: 1 });+ expect(getRowHeight(1)).toBe(19);+ expect(getRowHeight(3)).toBe(30);+ expect(getCurrentSelection()).toEqual({+ startRow: 1,+ endRow: 2,+ startColumn: 0,+ endColumn: 19,+ rangeType: RANGE_TYPE.ROW,+ });+ });++ it('Should forbidding moving when parts of merged cells are selected', async () => {+ selectRow(2, 2);++ const result = await commandService.executeCommand<IMoveRowsCommandParams>(MoveRowsCommand.id, {+ fromRow: 2,+ toRow: 1,+ });+ expect(result).toBeFalsy();+ });++ it('Should forbidding moving when rows are moved across a merged cell', async () => {+ selectRow(18, 19);++ const result = await commandService.executeCommand<IMoveRowsCommandParams>(MoveRowsCommand.id, {+ fromRow: 18,+ toRow: 3,+ });+ expect(result).toBeFalsy();++ const result2 = await commandService.executeCommand<IMoveRowsCommandParams>(MoveRowsCommand.id, {+ fromRow: 18,+ toRow: 4,+ });+ expect(result2).toBeTruthy();+ });+ });++ describe('Move cols', () => {+ it('Should move forward works', async () => {+ selectColumn(18, 19);++ const result = await commandService.executeCommand<IMoveColsCommandParams>(MoveColsCommand.id, {+ fromCol: 18,+ toCol: 1,+ });+ expect(result).toEqual(true);+ expect(getCellInfo(0, 0)?.v).toEqual('A1');+ expect(getCellInfo(1, 3)?.v).toEqual('B2');+ expect(getMergedInfo(1, 3)).toEqual({ startRow: 1, endRow: 1, startColumn: 3, endColumn: 4 });+ expect(getMergedInfo(2, 3)).toEqual({ startRow: 2, endRow: 3, startColumn: 3, endColumn: 3 });+ expect(getColWidth(1)).toBe(73);+ expect(getColWidth(3)).toBe(30);+ expect(getCurrentSelection()).toEqual({+ startRow: 0,+ endRow: 19,+ startColumn: 1,+ endColumn: 2,+ rangeType: RANGE_TYPE.COLUMN,+ });++ const undoResult = await commandService.executeCommand(UndoCommand.id);+ expect(undoResult).toEqual(true);+ expect(getCellInfo(0, 0)?.v).toEqual('A1');+ expect(getCellInfo(1, 1)?.v).toEqual('B2');+ expect(getMergedInfo(1, 1)).toEqual({ startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 });+ expect(getMergedInfo(2, 1)).toEqual({ startRow: 2, endRow: 3, startColumn: 1, endColumn: 1 });+ expect(getColWidth(1)).toBe(30);+ expect(getCurrentSelection()).toEqual({+ startRow: 0,+ endRow: 19,+ startColumn: 18,+ endColumn: 19,+ rangeType: RANGE_TYPE.COLUMN,+ });++ const redoResult = await commandService.executeCommand(RedoCommand.id);+ expect(redoResult).toEqual(true);+ expect(getCellInfo(0, 0)?.v).toEqual('A1');+ expect(getCellInfo(1, 3)?.v).toEqual('B2');+ expect(getMergedInfo(1, 3)).toEqual({ startRow: 1, endRow: 1, startColumn: 3, endColumn: 4 });+ expect(getMergedInfo(2, 3)).toEqual({ startRow: 2, endRow: 3, startColumn: 3, endColumn: 3 });+ expect(getColWidth(1)).toBe(73);+ expect(getColWidth(3)).toBe(30);+ expect(getCurrentSelection()).toEqual({+ startRow: 0,+ endRow: 19,+ startColumn: 1,+ endColumn: 2,+ rangeType: RANGE_TYPE.COLUMN,+ });+ });++ it('Should forbidding moving when parts of merged cells are selected', async () => {+ selectColumn(2, 2);++ const result = await commandService.executeCommand<IMoveColsCommandParams>(MoveColsCommand.id, {+ fromCol: 2,+ toCol: 1,+ });+ expect(result).toBeFalsy();+ });++ it('Should forbidding moving when columns are moved across a merged cell', async () => {+ selectColumn(18, 19);++ const result = await commandService.executeCommand<IMoveColsCommandParams>(MoveColsCommand.id, {+ fromCol: 18,+ toCol: 2,+ });+ expect(result).toBeFalsy();++ const result2 = await commandService.executeCommand<IMoveColsCommandParams>(MoveColsCommand.id, {+ fromCol: 18,+ toCol: 3,+ });+ expect(result2).toBeTruthy();+ });+ });+});++const TEST_ROWS_COLS_MOVE_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,+ },+ ],+ rowData: { '1': { h: 30 } },+ columnData: { '1': { w: 30 } },+ rowCount: 20,+ columnCount: 20,+ },+ },+ createdTime: '',+ creator: '',+ extensions: [],+ lastModifiedBy: '',+ locale: LocaleType.EN,+ modifiedTime: '',+ name: '',+ sheetOrder: [],+ styles: {},+ timeZone: '',+};++function createMoveRowsColsTestBed() {+ return createCommandTestBed(Tools.deepClone(TEST_ROWS_COLS_MOVE_DEMO), [+ [INotificationService, { useValue: { show: () => toDisposable(() => {}) } as INotificationService }],+ ]);+}diff --git a/packages/base-sheets/src/commands/commands/__tests__/set-border-command.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/set-border.command.spec.tssimilarity index 100%rename from packages/base-sheets/src/commands/commands/__tests__/set-border-command.spec.tsrename to packages/base-sheets/src/commands/commands/__tests__/set-border.command.spec.tsdiff --git a/packages/base-sheets/src/commands/commands/add-worksheet-merge.command.ts b/packages/base-sheets/src/commands/commands/add-worksheet-merge.command.tsindex bb4d6db1d6..57e37acc32 100644--- a/packages/base-sheets/src/commands/commands/add-worksheet-merge.command.ts+++ b/packages/base-sheets/src/commands/commands/add-worksheet-merge.command.ts@@ -14,10 +14,10 @@ import {IRemoveWorksheetMergeMutationParams,} from '../../Basics/Interfaces/MutationInterface';import { SelectionManagerService } from '../../services/selection-manager.service';-import { AddWorksheetMergeMutation, AddWorksheetMergeMutationFactory } from '../mutations/add-worksheet-merge.mutation';+import { AddMergeUndoMutationFactory, AddWorksheetMergeMutation } from '../mutations/add-worksheet-merge.mutation';import {+ RemoveMergeUndoMutationFactory,RemoveWorksheetMergeMutation,- RemoveWorksheetMergeMutationFactory,} from '../mutations/remove-worksheet-merge.mutation';interface addMergeCommandParams {@@ -77,7 +77,7 @@ export const AddWorksheetMergeCommand: ICommand = {worksheetId,ranges,};- const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(+ const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(accessor,removeMergeMutationParams);@@ -88,7 +88,7 @@ export const AddWorksheetMergeCommand: ICommand = {worksheetId,ranges,};- const undoMutationParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(+ const undoMutationParams: IRemoveWorksheetMergeMutationParams = AddMergeUndoMutationFactory(accessor,addMergeMutationParams);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 153b7e0865..64a1a65f54 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@@ -31,7 +31,7 @@ import {IRemoveWorksheetMergeMutationParams,} from '../../Basics/Interfaces/MutationInterface';import { SelectionManagerService } from '../../services/selection-manager.service';-import { AddWorksheetMergeMutation, AddWorksheetMergeMutationFactory } from '../mutations/add-worksheet-merge.mutation';+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 {@@ -42,8 +42,8 @@ import {} from '../mutations/insert-row-col.mutation';import { RemoveColMutation, RemoveRowMutation } from '../mutations/remove-row-col.mutation';import {+ RemoveMergeUndoMutationFactory,RemoveWorksheetMergeMutation,- RemoveWorksheetMergeMutationFactory,} from '../mutations/remove-worksheet-merge.mutation';export interface IInsertRowCommandParams {@@ -83,7 +83,7 @@ export const InsertRowCommand: ICommand = {const anchorRow = direction === Direction.UP ? startRow : startRow - 1;const height = worksheet.getRowHeight(anchorRow);- // insert rows & undos+ // insert row properties & undosconst insertRowParams: IInsertRowMutationParams = {workbookId,worksheetId,@@ -101,7 +101,7 @@ export const InsertRowCommand: ICommand = {insertRowParams);- // insert range styles & undos+ // insert range contents & styles & undosconst cellValue = new ObjectMatrix<ICellData>();const worksheetMatrix = worksheet.getCellMatrix();const cellStyleByColumn = new Map<number, string | Nullable<IStyleData>>();@@ -128,36 +128,36 @@ export const InsertRowCommand: ICommand = {// update merged cells & undos// NOTE: the problem of our algorithm is that we created a lot of merging cells mutations and un-merging cell mutations- const mergeData = Tools.deepClone(worksheet.getMergeData());- for (let i = 0; i < mergeData.length; i++) {- const merge = mergeData[i];+ const mergedCells: IRange[] = Tools.deepClone(worksheet.getMergeData());+ for (let i = 0; i < mergedCells.length; i++) {+ const mergedCell = mergedCells[i];const count = endRow - startRow + 1;- if (startRow > merge.endRow) {+ if (startRow > mergedCell.endRow) {continue;- } else if (startRow <= merge.startRow) {- merge.startRow += count;- merge.endRow += count;+ } else if (startRow <= mergedCell.startRow) {+ mergedCell.startRow += count;+ mergedCell.endRow += count;} else {- merge.endRow += count;+ mergedCell.endRow += count;}}- const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {+ const removeMergeParams: IRemoveWorksheetMergeMutationParams = {workbookId: params.workbookId,worksheetId: params.worksheetId,ranges: Tools.deepClone(worksheet.getMergeData()),};- const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(+ const undoRemoveMergeParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(accessor,- removeMergeMutationParams+ removeMergeParams);- const addMergeMutationParams: IAddWorksheetMergeMutationParams = {+ const addMergeParams: IAddWorksheetMergeMutationParams = {workbookId: params.workbookId,worksheetId: params.worksheetId,- ranges: mergeData,+ ranges: mergedCells,};- const undoAddMergeMutationParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(+ const undoAddMergeParams: IRemoveWorksheetMergeMutationParams = AddMergeUndoMutationFactory(accessor,- addMergeMutationParams+ addMergeParams);// there should be a hook to update ranges of various features@@ -167,8 +167,8 @@ export const InsertRowCommand: ICommand = {[{ id: InsertRowMutation.id, params: insertRowParams },{ id: InsertRangeMutation.id, params: insertRangeMutationParams },- { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams }, // remove all merged cells- { id: AddWorksheetMergeMutation.id, params: addMergeMutationParams }, // add all merged cells, TODO: can this be optimized?+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeParams }, // remove all merged cells+ { id: AddWorksheetMergeMutation.id, params: addMergeParams }, // add all merged cells, TODO: can this be optimized?],commandService);@@ -182,8 +182,8 @@ export const InsertRowCommand: ICommand = {[{ id: DeleteRangeMutation.id, params: undoInsertRangeMutationParams },{ id: RemoveRowMutation.id, params: undoRowInsertionParams },- { id: RemoveWorksheetMergeMutation.id, params: undoAddMergeMutationParams },- { id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams },+ { id: RemoveWorksheetMergeMutation.id, params: undoAddMergeParams },+ { id: AddWorksheetMergeMutation.id, params: undoRemoveMergeParams },],commandService)@@ -194,8 +194,8 @@ export const InsertRowCommand: ICommand = {[{ id: InsertRowMutation.id, params: insertRowParams },{ id: InsertRangeMutation.id, params: insertRangeMutationParams },- { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },- { id: AddWorksheetMergeMutation.id, params: addMergeMutationParams },+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeParams },+ { id: AddWorksheetMergeMutation.id, params: addMergeParams },],commandService)@@ -387,7 +387,7 @@ export const InsertColCommand: ICommand<IInsertColCommandParams> = {worksheetId: params.worksheetId,ranges: Tools.deepClone(worksheet.getMergeData()),};- const undoRemoveMergeParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(+ const undoRemoveMergeParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(accessor,removeMergeParams);@@ -396,7 +396,7 @@ export const InsertColCommand: ICommand<IInsertColCommandParams> = {worksheetId: params.worksheetId,ranges: mergeData,};- const undoAddMergeParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(+ const undoAddMergeParams: IRemoveWorksheetMergeMutationParams = AddMergeUndoMutationFactory(accessor,addMergeParams);diff --git a/packages/base-sheets/src/commands/commands/move-columns-to.command.ts b/packages/base-sheets/src/commands/commands/move-columns-to.command.tsdeleted file mode 100644index 0dc6b45be2..0000000000--- a/packages/base-sheets/src/commands/commands/move-columns-to.command.ts+++ /dev/null@@ -1,112 +0,0 @@-import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';--import { IInsertColMutationParams, IRemoveColMutationParams } from '../../Basics/Interfaces/MutationInterface';-import { SelectionManagerService } from '../../services/selection-manager.service';-import { InsertColMutation, InsertColMutationUndoFactory } from '../mutations/insert-row-col.mutation';-import { IRemoveColMutationFactory, RemoveColMutation } from '../mutations/remove-row-col.mutation';--export interface IMoveColumnsCommandParams {- fromColumn: number;- toColumn: number;-}--export const MoveColumnsCommand: ICommand = {- type: CommandType.COMMAND,- id: 'sheet.command.move-columns',- handler: async (accessor: IAccessor, params: IMoveColumnsCommandParams) => {- const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);- const currentUniverService = accessor.get(ICurrentUniverService);- const selectionManagerService = accessor.get(SelectionManagerService);-- const originRange = selectionManagerService.getRangeDatas()?.[0];- if (!originRange) {- return false;- }-- const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();- const worksheetId = currentUniverService- .getCurrentUniverSheetInstance()-- .getActiveSheet()- .getSheetId();- const workbook = currentUniverService.getUniverSheetInstance(workbookId);- if (!workbook) return false;- const worksheet = workbook.getSheetBySheetId(worksheetId);- if (!worksheet) return false;-- const { startColumn, endColumn } = originRange;-- const removeColumnMutationParams: IRemoveColMutationParams = {- workbookId,- worksheetId,- ranges: [- {- startColumn,- endColumn,- startRow: 0,- endRow: 0,- },- ],- };- const undoRemoveColumnMutationParams: IInsertColMutationParams = IRemoveColMutationFactory(- accessor,- removeColumnMutationParams- );-- const removeResult = commandService.executeCommand(RemoveColMutation.id, removeColumnMutationParams);-- const insertColMutationParams: IInsertColMutationParams = {- ...undoRemoveColumnMutationParams,- ranges: [- {- startColumn: params.toColumn,- endColumn: params.toColumn + endColumn - startColumn,- startRow: 0,- endRow: 0,- },- ],- };-- const undoMutationParams: IRemoveColMutationParams = InsertColMutationUndoFactory(- accessor,- insertColMutationParams- );-- const result = commandService.executeCommand(InsertColMutation.id, insertColMutationParams);-- if (removeResult && result) {- undoRedoService.pushUndoRedo({- // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面- // 通过勾子可以 hook 外部 controller 的代码来增加新的 action- URI: workbookId,- undo() {- return (- commandService.executeCommand(- InsertColMutation.id,- undoRemoveColumnMutationParams- ) as Promise<boolean>- ).then((res) => {- if (res) return commandService.executeCommand(RemoveColMutation.id, undoMutationParams);- return false;- });- },- redo() {- return (- commandService.executeCommand(- RemoveColMutation.id,- removeColumnMutationParams- ) as Promise<boolean>- ).then((res) => {- if (res) return commandService.executeCommand(InsertColMutation.id, insertColMutationParams);- return false;- });- },- });- return true;- }-- return false;- },-};diff --git a/packages/base-sheets/src/commands/commands/move-rows-cols.command.ts b/packages/base-sheets/src/commands/commands/move-rows-cols.command.tsnew file mode 100644index 0000000000..35d4a3d60e--- /dev/null+++ b/packages/base-sheets/src/commands/commands/move-rows-cols.command.ts@@ -0,0 +1,394 @@+import { INotificationService } from '@univerjs/base-ui';+import {+ CommandType,+ ICommand,+ ICommandService,+ ICurrentUniverService,+ IRange,+ IUndoRedoService,+ RANGE_TYPE,+ Rectangle,+ sequenceExecute,+ Tools,+} from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++import {+ IAddWorksheetMergeMutationParams,+ IRemoveWorksheetMergeMutationParams,+} from '../../Basics/Interfaces/MutationInterface';+import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../services/selection-manager.service';+import { AddMergeUndoMutationFactory, AddWorksheetMergeMutation } from '../mutations/add-worksheet-merge.mutation';+import {+ IMoveColumnsMutationParams,+ IMoveRowsMutationParams,+ MoveColsMutation,+ MoveColsMutationUndoFactory,+ MoveRowsMutation,+ MoveRowsMutationUndoFactory,+} from '../mutations/move-rows-cols.mutation';+import {+ RemoveMergeUndoMutationFactory,+ RemoveWorksheetMergeMutation,+} from '../mutations/remove-worksheet-merge.mutation';+import { ISetSelectionsOperationParams, SetSelectionsOperation } from '../operations/selection.operation';+import { columnAcrossMergedCell, rowAcrossMergedCell } from './utils/merged-cell-util';+import { alignToMergedCellsBorders, getPrimaryForRange } from './utils/selection-util';++export interface IMoveRowsCommandParams {+ fromRow: number;+ toRow: number;+}++/**+ * Command to move the selected rows (must currently selected) to the specified row.+ */+export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {+ id: 'sheet.command.move-rows',+ type: CommandType.COMMAND,+ handler: async (accessor: IAccessor, params: IMoveRowsCommandParams) => {+ const selectionManagerService = accessor.get(SelectionManagerService);+ const selections = selectionManagerService.getSelections();+ const { fromRow, toRow } = params;+ const filteredSelections = selections?.filter(+ (selection) =>+ selection.range.rangeType === RANGE_TYPE.ROW &&+ selection.range.startRow <= fromRow &&+ fromRow <= selection.range.endRow+ );+ if (filteredSelections?.length !== 1) {+ return false;+ }++ const currentUniverService = accessor.get(ICurrentUniverService);+ const workbook = currentUniverService.getCurrentUniverSheetInstance();+ if (!workbook) {+ return false;+ }+ const worksheet = workbook.getActiveSheet();+ if (!worksheet) {+ return false;+ }++ const workbookId = workbook.getUnitId();+ const worksheetId = worksheet.getSheetId();++ const notificationService = accessor.get(INotificationService);+ // Forbid action when some parts of a merged cell are selected.+ const rangeToMove = filteredSelections[0].range;+ const beforePrimary = filteredSelections[0].primary;+ const alignedRange = alignToMergedCellsBorders(rangeToMove, worksheet, false);+ if (!Rectangle.equals(rangeToMove, alignedRange)) {+ // TODO@wzhudev: use rightfully implemented notification service when it's ready+ notificationService.show({+ title: 'Only part of a merged cell is selected.',+ });+ return false;+ }++ if (rowAcrossMergedCell(toRow, worksheet)) {+ // TODO@wzhudev: use rightfully implemented notification service when it's ready+ notificationService.show({+ title: 'Across a merged cell',+ });+ return false;+ }++ const destinationRange: IRange = {+ ...rangeToMove,+ startRow: toRow,+ endRow: toRow + rangeToMove.endRow - rangeToMove.startRow,+ };+ const moveRowsParams: IMoveRowsMutationParams = {+ workbookId,+ worksheetId,+ sourceRange: rangeToMove,+ targetRange: destinationRange,+ };+ const undoMoveRowsParams = MoveRowsMutationUndoFactory(accessor, moveRowsParams);++ // we could just move the merged cells because other situations are not allowed+ // we should only deal with merged cell that is between the range of the rows to move+ const count = rangeToMove.endRow - rangeToMove.startRow + 1;+ const movedLength = toRow - fromRow;+ const moveBackward = movedLength < 0;+ const mergedCells: IRange[] = Tools.deepClone(worksheet.getMergeData());+ for (let i = 0; i < mergedCells.length; i++) {+ const mergedCell = mergedCells[i];+ const { startRow: mergeStartRow, endRow: mergedEndRow } = mergedCell;+ if (moveBackward) {+ // merged cells between `rangeToMove` to `destination` should be moved forward+ // merged cells in the `rangeToMove` should be moved backward+ if (Rectangle.contains(rangeToMove, mergedCell)) {+ mergedCell.startRow += movedLength;+ mergedCell.endRow += movedLength;+ } else if (mergedEndRow < rangeToMove.startRow && mergeStartRow >= destinationRange.startRow) {+ mergedCell.startRow += count;+ mergedCell.endRow += count;+ }+ } else {+ // move forward+ if (Rectangle.contains(rangeToMove, mergedCell)) {+ mergedCell.startRow += movedLength;+ mergedCell.endRow += movedLength;+ } else if (rangeToMove.endRow < mergeStartRow && mergedEndRow < destinationRange.startRow) {+ mergedCell.startRow -= count;+ mergedCell.endRow -= count;+ }+ }+ }+ const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {+ workbookId,+ worksheetId,+ ranges: Tools.deepClone(worksheet.getMergeData()),+ };+ const undoRemoveMergeMutationParams = RemoveMergeUndoMutationFactory(accessor, removeMergeMutationParams);+ const addMergeParams: IAddWorksheetMergeMutationParams = {+ workbookId,+ worksheetId,+ ranges: mergedCells,+ };+ const undoAddMergeParams = AddMergeUndoMutationFactory(accessor, addMergeParams);++ // deal with selections+ const setSelectionsParam: ISetSelectionsOperationParams = {+ workbookId,+ worksheetId,+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,+ selections: [+ { range: destinationRange, primary: getPrimaryForRange(destinationRange, worksheet), style: null },+ ],+ };+ const undoSetSelectionsParam: ISetSelectionsOperationParams = {+ workbookId,+ worksheetId,+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,+ selections: [{ range: rangeToMove, primary: beforePrimary, style: null }],+ };++ const commandService = accessor.get(ICommandService);+ const result = await sequenceExecute(+ [+ { id: MoveRowsMutation.id, params: moveRowsParams },+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },+ { id: AddWorksheetMergeMutation.id, params: addMergeParams },+ { id: SetSelectionsOperation.id, params: setSelectionsParam },+ ],+ commandService+ );++ if (result.result) {+ const undoRedoService = accessor.get(IUndoRedoService);+ undoRedoService.pushUndoRedo({+ URI: workbookId,+ async undo() {+ // NOTE: This may be affect by collaboration programming. But in google sheet, the merged cells are reverted as well :(+ const undoResult = await sequenceExecute(+ [+ { id: MoveRowsMutation.id, params: undoMoveRowsParams },+ { id: RemoveWorksheetMergeMutation.id, params: undoAddMergeParams },+ { id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams },+ { id: SetSelectionsOperation.id, params: undoSetSelectionsParam },+ ],+ commandService+ );++ return undoResult.result;+ },+ async redo() {+ const redoResult = await sequenceExecute(+ [+ { id: MoveRowsMutation.id, params: moveRowsParams },+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },+ { id: AddWorksheetMergeMutation.id, params: addMergeParams },+ { id: SetSelectionsOperation.id, params: setSelectionsParam },+ ],+ commandService+ );+ return redoResult.result;+ },+ });+ return true;+ }++ return false;+ },+};++export interface IMoveColsCommandParams {+ fromCol: number;+ toCol: number;+}++export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {+ id: 'sheet.command.move-cols',+ type: CommandType.COMMAND,+ handler: async (accessor: IAccessor, params: IMoveColsCommandParams) => {+ const selectionManagerService = accessor.get(SelectionManagerService);+ const selections = selectionManagerService.getSelections();+ const { fromCol, toCol } = params;+ const filteredSelections = selections?.filter(+ (selection) =>+ selection.range.rangeType === RANGE_TYPE.COLUMN &&+ selection.range.startColumn <= fromCol &&+ fromCol <= selection.range.endColumn+ );+ if (filteredSelections?.length !== 1) {+ return false;+ }++ const currentUniverService = accessor.get(ICurrentUniverService);+ const workbook = currentUniverService.getCurrentUniverSheetInstance();+ if (!workbook) {+ return false;+ }+ const worksheet = workbook.getActiveSheet();+ if (!worksheet) {+ return false;+ }++ const workbookId = workbook.getUnitId();+ const worksheetId = worksheet.getSheetId();++ const notificationService = accessor.get(INotificationService);+ // Forbid action when some parts of a merged cell are selected.+ const rangeToMove = filteredSelections[0].range;+ const beforePrimary = filteredSelections[0].primary;+ const alignedRange = alignToMergedCellsBorders(rangeToMove, worksheet, false);+ if (!Rectangle.equals(rangeToMove, alignedRange)) {+ // TODO@wzhudev: use rightfully implemented notification service when it's ready+ notificationService.show({+ title: 'Only part of a merged cell is selected.',+ });+ return false;+ }++ if (columnAcrossMergedCell(toCol, worksheet)) {+ // TODO@wzhudev: use rightfully implemented notification service when it's ready+ notificationService.show({+ title: 'Across a merged cell',+ });+ return false;+ }++ const destinationRange: IRange = {+ ...rangeToMove,+ startColumn: toCol,+ endColumn: toCol + rangeToMove.endColumn - rangeToMove.startColumn,+ };+ const moveColsParams: IMoveColumnsMutationParams = {+ workbookId,+ worksheetId,+ sourceRange: rangeToMove,+ targetRange: destinationRange,+ };+ const undoMoveColsParams = MoveColsMutationUndoFactory(accessor, moveColsParams);++ // we could just move the merged cells because other situations are not allowed+ // we should only deal with merged cell that is between the range of the cols to move+ const count = rangeToMove.endColumn - rangeToMove.startColumn + 1;+ const movedLength = toCol - fromCol;+ const moveBackward = movedLength < 0;+ const mergedCells: IRange[] = Tools.deepClone(worksheet.getMergeData());+ for (let i = 0; i < mergedCells.length; i++) {+ const mergedCell = mergedCells[i];+ const { startColumn: mergeStartCol, endColumn: mergedEndCol } = mergedCell;+ if (moveBackward) {+ // merged cells between `rangeToMove` to `destination` should be moved forward+ // merged cells in the `rangeToMove` should be moved backward+ if (Rectangle.contains(rangeToMove, mergedCell)) {+ mergedCell.startColumn += movedLength;+ mergedCell.endColumn += movedLength;+ } else if (mergedEndCol < rangeToMove.startColumn && mergeStartCol >= destinationRange.startColumn) {+ mergedCell.startColumn += count;+ mergedCell.endColumn += count;+ }+ } else {+ // move forward+ if (Rectangle.contains(rangeToMove, mergedCell)) {+ mergedCell.startColumn += movedLength;+ mergedCell.endColumn += movedLength;+ } else if (rangeToMove.endColumn < mergeStartCol && mergedEndCol < destinationRange.startColumn) {+ mergedCell.startColumn -= count;+ mergedCell.endColumn -= count;+ }+ }+ }++ const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {+ workbookId,+ worksheetId,+ ranges: Tools.deepClone(worksheet.getMergeData()),+ };+ const undoRemoveMergeMutationParams = RemoveMergeUndoMutationFactory(accessor, removeMergeMutationParams);+ const addMergeParams: IAddWorksheetMergeMutationParams = {+ workbookId,+ worksheetId,+ ranges: mergedCells,+ };+ const undoAddMergeParams = AddMergeUndoMutationFactory(accessor, addMergeParams);++ // deal with selections+ const setSelectionsParam: ISetSelectionsOperationParams = {+ workbookId,+ worksheetId,+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,+ selections: [+ { range: destinationRange, primary: getPrimaryForRange(destinationRange, worksheet), style: null },+ ],+ };+ const undoSetSelectionsParam: ISetSelectionsOperationParams = {+ workbookId,+ worksheetId,+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,+ selections: [{ range: rangeToMove, primary: beforePrimary, style: null }],+ };++ const commandService = accessor.get(ICommandService);+ const result = await sequenceExecute(+ [+ { id: MoveColsMutation.id, params: moveColsParams },+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },+ { id: AddWorksheetMergeMutation.id, params: addMergeParams },+ { id: SetSelectionsOperation.id, params: setSelectionsParam },+ ],+ commandService+ );++ if (result.result) {+ const undoRedoService = accessor.get(IUndoRedoService);+ undoRedoService.pushUndoRedo({+ URI: workbookId,+ async undo() {+ // NOTE: This may be affect by collaboration programming. But in google sheet, the merged cells are reverted as well :(+ const undoResult = await sequenceExecute(+ [+ { id: MoveColsMutation.id, params: undoMoveColsParams },+ { id: RemoveWorksheetMergeMutation.id, params: undoAddMergeParams },+ { id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams },+ { id: SetSelectionsOperation.id, params: undoSetSelectionsParam },+ ],+ commandService+ );++ return undoResult.result;+ },+ async redo() {+ const redoResult = await sequenceExecute(+ [+ { id: MoveColsMutation.id, params: moveColsParams },+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },+ { id: AddWorksheetMergeMutation.id, params: addMergeParams },+ { id: SetSelectionsOperation.id, params: setSelectionsParam },+ ],+ commandService+ );+ return redoResult.result;+ },+ });+ return true;+ }++ return true;+ },+};diff --git a/packages/base-sheets/src/commands/commands/move-rows.command.ts b/packages/base-sheets/src/commands/commands/move-rows.command.tsdeleted file mode 100644index de0da602ea..0000000000--- a/packages/base-sheets/src/commands/commands/move-rows.command.ts+++ /dev/null@@ -1,117 +0,0 @@-import {- CommandType,- ICommand,- ICommandService,- ICurrentUniverService,- IUndoRedoService,- RANGE_TYPE,-} from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';--import { IInsertRowMutationParams, IRemoveRowsMutationParams } from '../../Basics/Interfaces/MutationInterface';-import { SelectionManagerService } from '../../services/selection-manager.service';-import { InsertRowMutation, InsertRowMutationUndoFactory } from '../mutations/insert-row-col.mutation';-import { RemoveRowMutation, RemoveRowsMutationFactory } from '../mutations/remove-row-col.mutation';--export interface IMoveRowsCommandParams {- fromRow: number;- toRow: number;-}--/**- * Command to move the selected rows (must currently selected) to the specified row.- */-export const MoveRowsCommand: ICommand = {- type: CommandType.COMMAND,- id: 'sheet.command.move-rows',- handler: async (accessor: IAccessor, params: IMoveRowsCommandParams) => {- const selectionManagerService = accessor.get(SelectionManagerService);-- const selections = selectionManagerService.getSelections();- if (!selections?.length) {- return false;- }-- const findMoveRanges = selections.filter(- (s) =>- s.range.rangeType === RANGE_TYPE.ROW &&- s.range.startRow <= params.fromRow &&- params.fromRow <= s.range.endRow- );- if (findMoveRanges.length !== 1) {- return false;- }-- const movedRanges = findMoveRanges[0];- const currentUniverService = accessor.get(ICurrentUniverService);- const workbook = currentUniverService.getCurrentUniverSheetInstance();- if (!workbook) return false;- const workbookId = workbook.getUnitId();- const worksheet = workbook.getActiveSheet();- if (!worksheet) return false;- const worksheetId = worksheet.getSheetId();-- // TODO: we should add a move row mutation instead of using an insert mutation and a delete mutation- // they are not logically the same-- const { startRow, endRow } = movedRanges.range;- const removeRowMutationParams: IRemoveRowsMutationParams = {- workbookId,- worksheetId,- ranges: [- {- startColumn: 0,- endColumn: 0,- startRow,- endRow,- },- ],- };- const undoRemoveRowMutationParams: IInsertRowMutationParams = RemoveRowsMutationFactory(- removeRowMutationParams,- worksheet- );-- const insertRowMutationParams: IInsertRowMutationParams = {- ...undoRemoveRowMutationParams,- ranges: [- {- startColumn: 0,- endColumn: 0,- startRow: params.toRow,- endRow: params.toRow + endRow - startRow,- },- ],- };- const undoMutationParams: IRemoveRowsMutationParams = InsertRowMutationUndoFactory(- accessor,- insertRowMutationParams- );-- // TODO: we should expose a hook on a service to let other features to hook in mutations when rows are moved-- const commandService = accessor.get(ICommandService);- const removeResult = commandService.executeCommand(RemoveRowMutation.id, removeRowMutationParams);- const insertResult = commandService.executeCommand(InsertRowMutation.id, insertRowMutationParams);-- if (removeResult && insertResult) {- accessor.get(IUndoRedoService).pushUndoRedo({- URI: workbookId,- async undo() {- const res = await commandService.executeCommand(InsertRowMutation.id, undoRemoveRowMutationParams);- if (res) return commandService.executeCommand(RemoveRowMutation.id, undoMutationParams);- return false;- },- async redo() {- const res = await commandService.executeCommand(RemoveRowMutation.id, removeRowMutationParams);- if (res) return commandService.executeCommand(InsertRowMutation.id, insertRowMutationParams);- return false;- },- });-- return true;- }-- return false;- },-};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 6234edd131..d602415e0f 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@@ -24,19 +24,19 @@ import {IRemoveWorksheetMergeMutationParams,} from '../../Basics/Interfaces/MutationInterface';import { SelectionManagerService } from '../../services/selection-manager.service';-import { AddWorksheetMergeMutation, AddWorksheetMergeMutationFactory } from '../mutations/add-worksheet-merge.mutation';+import { AddMergeUndoMutationFactory, AddWorksheetMergeMutation } from '../mutations/add-worksheet-merge.mutation';import { DeleteRangeMutation, DeleteRangeUndoMutationFactory } from '../mutations/delete-range.mutation';import { InsertRangeMutation } from '../mutations/insert-range.mutation';import { InsertColMutation, InsertRowMutation } from '../mutations/insert-row-col.mutation';import {- IRemoveColMutationFactory,RemoveColMutation,+ RemoveColMutationFactory,RemoveRowMutation,- RemoveRowsMutationFactory,+ RemoveRowsUndoMutationFactory,} from '../mutations/remove-row-col.mutation';import {+ RemoveMergeUndoMutationFactory,RemoveWorksheetMergeMutation,- RemoveWorksheetMergeMutationFactory,} from '../mutations/remove-worksheet-merge.mutation';/**@@ -45,7 +45,6 @@ import {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 selections = selectionManagerService.getSelections();@@ -72,7 +71,10 @@ export const RemoveRowCommand: ICommand = {worksheetId,ranges,};- const undoRemoveRowsParams: IInsertRowMutationParams = RemoveRowsMutationFactory(removeRowsParams, worksheet);+ const undoRemoveRowsParams: IInsertRowMutationParams = RemoveRowsUndoMutationFactory(+ removeRowsParams,+ worksheet+ );// cells' contentsconst deleteRangeValueParams: IDeleteRangeMutationParams = {@@ -128,7 +130,7 @@ export const RemoveRowCommand: ICommand = {worksheetId,ranges: Tools.deepClone(worksheet.getMergeData()),};- const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(+ const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(accessor,removeMergeMutationParams);@@ -137,7 +139,7 @@ export const RemoveRowCommand: ICommand = {worksheetId,ranges: mergeData,};- const deleteMergeMutationParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(+ const deleteMergeMutationParams: IRemoveWorksheetMergeMutationParams = AddMergeUndoMutationFactory(accessor,addMergeMutationParams);@@ -221,7 +223,7 @@ export const RemoveColCommand: ICommand = {worksheetId,ranges,};- const undoRemoveColParams: IInsertColMutationParams = IRemoveColMutationFactory(accessor, removeColParams);+ const undoRemoveColParams: IInsertColMutationParams = RemoveColMutationFactory(accessor, removeColParams);// cells' contentsconst removeRangeValuesParams: IDeleteRangeMutationParams = {@@ -273,7 +275,7 @@ export const RemoveColCommand: ICommand = {worksheetId,ranges: Tools.deepClone(worksheet.getMergeData()),};- const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(+ const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(accessor,removeMergeMutationParams);@@ -282,7 +284,7 @@ export const RemoveColCommand: ICommand = {worksheetId,ranges: mergeData,};- const undoAddMergeParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(+ const undoAddMergeParams: IRemoveWorksheetMergeMutationParams = AddMergeUndoMutationFactory(accessor,addMergeMutationParams);diff --git a/packages/base-sheets/src/commands/commands/remove-worksheet-merge.command.ts b/packages/base-sheets/src/commands/commands/remove-worksheet-merge.command.tsindex 537d5520a7..8b9fdb8a44 100644--- a/packages/base-sheets/src/commands/commands/remove-worksheet-merge.command.ts+++ b/packages/base-sheets/src/commands/commands/remove-worksheet-merge.command.ts@@ -15,8 +15,8 @@ import {import { SelectionManagerService } from '../../services/selection-manager.service';import { AddWorksheetMergeMutation } from '../mutations/add-worksheet-merge.mutation';import {+ RemoveMergeUndoMutationFactory,RemoveWorksheetMergeMutation,- RemoveWorksheetMergeMutationFactory,} from '../mutations/remove-worksheet-merge.mutation';export const RemoveWorksheetMergeCommand: ICommand = {@@ -60,7 +60,7 @@ export const RemoveWorksheetMergeCommand: ICommand = {});if (!hasMerge) return false;- const undoMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(+ const undoMutationParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(accessor,removeMergeMutationParams);diff --git a/packages/base-sheets/src/commands/commands/set-zoom-ratio.command.ts b/packages/base-sheets/src/commands/commands/set-zoom-ratio.command.tsdeleted file mode 100644index c868d6df22..0000000000--- a/packages/base-sheets/src/commands/commands/set-zoom-ratio.command.ts+++ /dev/null@@ -1,68 +0,0 @@-import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';--import {- ISetZoomRatioMutationParams,- SetZoomRatioMutation,- SetZoomRatioUndoMutationFactory,-} from '../mutations/set-zoom-ratio.mutation';--export interface ISetZoomRatioCommandParams {- zoomRatio?: number;- workbookId?: string;- worksheetId?: string;-}--export const SetZoomRatioCommand: ICommand = {- type: CommandType.COMMAND,- id: 'sheet.command.set-zoom-ratio',-- handler: async (accessor: IAccessor, params?: ISetZoomRatioCommandParams) => {- const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);- const currentUniverService = accessor.get(ICurrentUniverService);-- let workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();- let worksheetId = currentUniverService- .getCurrentUniverSheetInstance()-- .getActiveSheet()- .getSheetId();- let zoomRatio = 1;-- if (params) {- workbookId = params.workbookId ?? workbookId;- worksheetId = params.worksheetId ?? worksheetId;- zoomRatio = params.zoomRatio ?? zoomRatio;- }-- const workbook = currentUniverService.getUniverSheetInstance(workbookId);- if (!workbook) return false;- const worksheet = workbook.getSheetBySheetId(worksheetId);- if (!worksheet) return false;-- const setZoomRatioMutationParams: ISetZoomRatioMutationParams = {- zoomRatio,- workbookId,- worksheetId,- };-- const undoMutationParams = SetZoomRatioUndoMutationFactory(accessor, setZoomRatioMutationParams);- const result = commandService.executeCommand(SetZoomRatioMutation.id, setZoomRatioMutationParams);-- if (result) {- undoRedoService.pushUndoRedo({- URI: workbookId,- undo() {- return commandService.executeCommand(SetZoomRatioMutation.id, undoMutationParams);- },- redo() {- return commandService.executeCommand(SetZoomRatioMutation.id, setZoomRatioMutationParams);- },- });- return true;- }-- return false;- },-};diff --git a/packages/base-sheets/src/commands/commands/utils/merged-cell-util.ts b/packages/base-sheets/src/commands/commands/utils/merged-cell-util.tsnew file mode 100644index 0000000000..7ab3985fb3--- /dev/null+++ b/packages/base-sheets/src/commands/commands/utils/merged-cell-util.ts@@ -0,0 +1,12 @@+import { Worksheet } from '@univerjs/core';++/**+ * @param row after this row+ */+export function rowAcrossMergedCell(row: number, worksheet: Worksheet): boolean {+ return worksheet.getMergeData().some((mergedCell) => mergedCell.startRow < row && row <= mergedCell.endRow);+}++export function columnAcrossMergedCell(col: number, worksheet: Worksheet): boolean {+ return worksheet.getMergeData().some((mergedCell) => mergedCell.startColumn < col && col <= mergedCell.endColumn);+}diff --git a/packages/base-sheets/src/commands/commands/utils/selection-util.ts b/packages/base-sheets/src/commands/commands/utils/selection-util.tsindex 5c7eead499..303fd5b19e 100644--- a/packages/base-sheets/src/commands/commands/utils/selection-util.ts+++ b/packages/base-sheets/src/commands/commands/utils/selection-util.ts@@ -606,3 +606,31 @@ export function checkIfShrink(selection: ISelection, direction: Direction, worksreturn anchorRange.startColumn > range.startColumn;}}++/**+ * Get the default primary cell (the most top-left cell) of a range.+ * @param range+ * @param worksheet+ */+export function getPrimaryForRange(range: IRange, worksheet: Worksheet): ISelectionCell {+ const mergedRange = worksheet.getMergedCell(range.startRow, range.startColumn);+ if (!mergedRange) {+ return {+ ...range,+ actualRow: range.startRow,+ actualColumn: range.startColumn,+ rangeType: RANGE_TYPE.NORMAL,+ isMerged: false,+ isMergedMainCell: false,+ };+ }++ return {+ ...mergedRange,+ actualRow: range.startRow,+ actualColumn: range.startColumn,+ rangeType: RANGE_TYPE.NORMAL,+ isMerged: true,+ isMergedMainCell: true,+ };+}diff --git a/packages/base-sheets/src/commands/mutations/add-worksheet-merge.mutation.ts b/packages/base-sheets/src/commands/mutations/add-worksheet-merge.mutation.tsindex aa293012ff..9b67934274 100644--- a/packages/base-sheets/src/commands/mutations/add-worksheet-merge.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/add-worksheet-merge.mutation.ts@@ -6,7 +6,7 @@ import {IRemoveWorksheetMergeMutationParams,} from '../../Basics/Interfaces/MutationInterface';-export const AddWorksheetMergeMutationFactory = (+export const AddMergeUndoMutationFactory = (accessor: IAccessor,params: IAddWorksheetMergeMutationParams): IRemoveWorksheetMergeMutationParams => {diff --git a/packages/base-sheets/src/commands/mutations/delete-range.mutation.ts b/packages/base-sheets/src/commands/mutations/delete-range.mutation.tsindex cff629ea28..61590977ce 100644--- a/packages/base-sheets/src/commands/mutations/delete-range.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/delete-range.mutation.ts@@ -37,7 +37,6 @@ export const DeleteRangeUndoMutationFactory = (for (let i = 0; i < params.ranges.length; i++) {const { startRow, endRow, startColumn, endColumn } = params.ranges[i];-if (params.shiftDimension === Dimension.ROWS) {// build new datafor (let r = startRow; r <= lastEndRow; r++) {diff --git a/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.ts b/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.tsindex f95d69f610..8ff2d315ed 100644--- a/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.ts@@ -43,9 +43,9 @@ export const InsertRowMutation: IMutation<IInsertRowMutationParams> = {throw new Error('worksheet is null error!');}- const manager = worksheet.getRowManager();- const rowPrimitive = manager.getRowData().toJSON();- const rowWrapper = new ObjectArray(rowPrimitive);+ // TODO@wzhudev: should not expose row data and let outside modules to modify it directly+ // the correct way to do this is to provide a method from RowManager to modify row data+ const rowWrapper = worksheet.getRowManager().getRowData();const defaultRowInfo = {h: worksheet.getConfig().defaultRowHeight,hd: 0,diff --git a/packages/base-sheets/src/commands/mutations/move-rows-cols.mutation.ts b/packages/base-sheets/src/commands/mutations/move-rows-cols.mutation.tsnew file mode 100644index 0000000000..1b64f9f0b3--- /dev/null+++ b/packages/base-sheets/src/commands/mutations/move-rows-cols.mutation.ts@@ -0,0 +1,153 @@+import { CommandType, ICurrentUniverService, IMutation, IRange, Rectangle } from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++// TODO@wzhudev: maybe we should do some error handling in these mutators++export interface IMoveRowsMutationParams {+ workbookId: string;+ worksheetId: string;+ /**+ * The rows to be moved.+ */+ sourceRange: IRange;+ /**+ * The destination range to move the source rows to. Note that the range is before the movement has occurred.+ */+ targetRange: IRange;+}++/**+ * Get an undo mutation for the move rows mutation.+ * @param accessor+ * @param params+ */+export function MoveRowsMutationUndoFactory(+ _accessor: IAccessor,+ params: IMoveRowsMutationParams+): IMoveRowsMutationParams {+ const { workbookId, worksheetId, sourceRange, targetRange } = params;+ const movingBackward = sourceRange.startRow > targetRange.startRow;+ const count = sourceRange.endRow - sourceRange.startRow + 1;+ if (movingBackward) {+ // If is moving backward, target range should be `count` offset.+ return {+ workbookId,+ worksheetId,+ sourceRange: Rectangle.clone(targetRange),+ targetRange: { ...sourceRange, endRow: sourceRange.endRow + count, startRow: sourceRange.startRow + count },+ };+ }+ return {+ workbookId,+ worksheetId,+ targetRange: Rectangle.clone(sourceRange),+ sourceRange: Rectangle.clone(targetRange),+ };+}++export const MoveRowsMutation: IMutation<IMoveRowsMutationParams> = {+ id: 'sheet.mutation.move-rows',+ type: CommandType.MUTATION,+ handler: async (accessor, params) => {+ const { workbookId, worksheetId, sourceRange, targetRange } = params;+ const currentUniverService = accessor.get(ICurrentUniverService);++ const univerSheet = currentUniverService.getUniverSheetInstance(workbookId);+ if (!univerSheet) {+ throw new Error('[MoveRowMutation] univerSheet is null!');+ }++ const worksheet = univerSheet.getSheetBySheetId(worksheetId);+ if (!worksheet) {+ throw new Error('[MoveRowMutation] worksheet is null!');+ }++ const fromRow = sourceRange.startRow;+ const count = sourceRange.endRow - sourceRange.startRow + 1;+ const toRow = targetRange.startRow;++ // move row properties by directing mutating+ const rowWrapper = worksheet.getRowManager().getRowData();+ rowWrapper.move(fromRow, count, toRow);++ // move cells contents by directly mutating worksheetCellMatrix+ const cellMatrix = worksheet.getCellMatrix();+ cellMatrix.moveRows(fromRow, count, toRow);++ return true;+ },+};++export interface IMoveColumnsMutationParams {+ workbookId: string;+ worksheetId: string;+ /**+ * The cols to be moved.+ */+ sourceRange: IRange;+ /**+ * The destination range to move the source cols to. Note that the range is before the movement has occurred.+ */+ targetRange: IRange;+}++export function MoveColsMutationUndoFactory(+ _accessor: IAccessor,+ params: IMoveColumnsMutationParams+): IMoveColumnsMutationParams {+ const { workbookId, worksheetId, sourceRange, targetRange } = params;+ const movingBackward = sourceRange.startColumn > targetRange.startColumn;+ const count = sourceRange.endColumn - sourceRange.startColumn + 1;+ if (movingBackward) {+ // If is moving backward, target range should be `count` offset.+ return {+ workbookId,+ worksheetId,+ sourceRange: Rectangle.clone(targetRange),+ targetRange: {+ ...sourceRange,+ endColumn: sourceRange.endColumn + count,+ startColumn: sourceRange.startColumn + count,+ },+ };+ }+ return {+ workbookId,+ worksheetId,+ targetRange: Rectangle.clone(sourceRange),+ sourceRange: Rectangle.clone(targetRange),+ };+}++export const MoveColsMutation: IMutation<IMoveColumnsMutationParams> = {+ id: 'sheet.mutation.move-columns',+ type: CommandType.MUTATION,+ handler: async (accessor, params) => {+ const { workbookId, worksheetId, sourceRange, targetRange } = params;+ const currentUniverService = accessor.get(ICurrentUniverService);++ const univerSheet = currentUniverService.getUniverSheetInstance(workbookId);+ if (!univerSheet) {+ throw new Error('[MoveColumnMutation] univerSheet is null!');+ }++ const worksheet = univerSheet.getSheetBySheetId(worksheetId);+ if (!worksheet) {+ throw new Error('[MoveColumnMutation] worksheet is null!');+ }++ const fromCol = sourceRange.startColumn;+ const count = sourceRange.endColumn - sourceRange.startColumn + 1;+ const toCol = targetRange.startColumn;++ // move column properties by directing mutating+ const columnWrapper = worksheet.getColumnManager().getColumnData();+ columnWrapper.move(fromCol, count, toCol);++ // move cells contents by directly mutating worksheetCellMatrix+ const cellMatrix = worksheet.getCellMatrix();+ cellMatrix.moveColumns(fromCol, count, toCol);++ return true;+ },+};diff --git a/packages/base-sheets/src/commands/mutations/remove-row-col.mutation.ts b/packages/base-sheets/src/commands/mutations/remove-row-col.mutation.tsindex 62ecd0c109..5036696f2f 100644--- a/packages/base-sheets/src/commands/mutations/remove-row-col.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/remove-row-col.mutation.ts@@ -16,7 +16,7 @@ import {IRemoveRowsMutationParams,} from '../../Basics/Interfaces/MutationInterface';-export const RemoveRowsMutationFactory = (+export const RemoveRowsUndoMutationFactory = (params: IRemoveRowsMutationParams,worksheet: Worksheet): IInsertRowMutationParams => {@@ -40,7 +40,7 @@ export const RemoveRowsMutationFactory = (};export const RemoveRowMutation: IMutation<IRemoveRowsMutationParams> = {- id: 'sheet.mutation.remove-row',+ id: 'sheet.mutation.remove-rows',type: CommandType.MUTATION,handler: async (accessor, params) => {const currentUniverService = accessor.get(ICurrentUniverService);@@ -75,7 +75,7 @@ export const RemoveRowMutation: IMutation<IRemoveRowsMutationParams> = {},};-export const IRemoveColMutationFactory = (+export const RemoveColMutationFactory = (accessor: IAccessor,params: IRemoveColMutationParams): IInsertColMutationParams => {diff --git a/packages/base-sheets/src/commands/mutations/remove-worksheet-merge.mutation.ts b/packages/base-sheets/src/commands/mutations/remove-worksheet-merge.mutation.tsindex dcedfdddf8..f034e98935 100644--- a/packages/base-sheets/src/commands/mutations/remove-worksheet-merge.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/remove-worksheet-merge.mutation.ts@@ -6,7 +6,7 @@ import {IRemoveWorksheetMergeMutationParams,} from '../../Basics/Interfaces/MutationInterface';-export const RemoveWorksheetMergeMutationFactory = (+export const RemoveMergeUndoMutationFactory = (accessor: IAccessor,params: IRemoveWorksheetMergeMutationParams): IAddWorksheetMergeMutationParams => {diff --git a/packages/base-sheets/src/commands/operations/selection.operation.ts b/packages/base-sheets/src/commands/operations/selection.operation.tsindex fdca06cfd4..d1cdfed101 100644--- a/packages/base-sheets/src/commands/operations/selection.operation.ts+++ b/packages/base-sheets/src/commands/operations/selection.operation.ts@@ -6,8 +6,8 @@ import { CommandType, IOperation } from '@univerjs/core';import { SelectionManagerService } from '../../services/selection-manager.service';export interface ISetSelectionsOperationParams {- unitId: string;- sheetId: string;+ workbookId: string;+ worksheetId: string;pluginName: string;selections: ISelectionWithStyle[];}@@ -18,9 +18,6 @@ export const SetSelectionsOperation: IOperation<ISetSelectionsOperationParams> =handler: async (accessor, params) => {const selectionManagerService = accessor.get(SelectionManagerService);selectionManagerService.replace(params!.selections);- // const models = selectionManager.getCurrentModels();- // models?.forEach((m) => m.setCurrentCell());- // selectionManager.renderCurrentControls(false);return true;},};diff --git a/packages/base-sheets/src/commands/mutations/set-zoom-ratio.mutation.ts b/packages/base-sheets/src/commands/operations/set-zoom-ratio.operation.tssimilarity index 57%rename from packages/base-sheets/src/commands/mutations/set-zoom-ratio.mutation.tsrename to packages/base-sheets/src/commands/operations/set-zoom-ratio.operation.tsindex 5945d2d343..601feacca4 100644--- a/packages/base-sheets/src/commands/mutations/set-zoom-ratio.mutation.ts+++ b/packages/base-sheets/src/commands/operations/set-zoom-ratio.operation.ts@@ -1,7 +1,7 @@-import { CommandType, ICurrentUniverService, IMutation, Tools } from '@univerjs/core';+import { CommandType, ICurrentUniverService, IOperation, Tools } from '@univerjs/core';import { IAccessor } from '@wendellhu/redi';-export interface ISetZoomRatioMutationParams {+export interface ISetZoomRatioOperationParams {zoomRatio: number;workbookId: string;worksheetId: string;@@ -9,8 +9,8 @@ export interface ISetZoomRatioMutationParams {export const SetZoomRatioUndoMutationFactory = (accessor: IAccessor,- params: ISetZoomRatioMutationParams-): ISetZoomRatioMutationParams => {+ params: ISetZoomRatioOperationParams+): ISetZoomRatioOperationParams => {const workbook = accessor.get(ICurrentUniverService).getUniverSheetInstance(params.workbookId);const worksheet = workbook!.getSheetBySheetId(params.worksheetId);const old = worksheet!.getConfig().zoomRatio;@@ -20,14 +20,20 @@ export const SetZoomRatioUndoMutationFactory = (};};-export const SetZoomRatioMutation: IMutation<ISetZoomRatioMutationParams> = {- id: 'sheet.mutation.set-zoom-ratio',- type: CommandType.MUTATION,- handler: async (accessor, params) => {+export const SetZoomRatioOperation: IOperation<ISetZoomRatioOperationParams> = {+ id: 'sheet.operation.set-zoom-ratio',+ type: CommandType.OPERATION,+ handler: async (accessor, params: ISetZoomRatioOperationParams) => {const workbook = accessor.get(ICurrentUniverService).getUniverSheetInstance(params.workbookId);- if (!workbook) return false;+ if (!workbook) {+ return false;+ }+const worksheet = workbook.getSheetBySheetId(params.worksheetId);- if (!worksheet) return false;+ if (!worksheet) {+ return false;+ }+worksheet.getConfig().zoomRatio = params.zoomRatio;return true;diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.tsindex 8e27806f18..9c7c2b0d87 100644--- a/packages/base-sheets/src/index.ts+++ b/packages/base-sheets/src/index.ts@@ -92,7 +92,6 @@ export { SetRowHeightCommand as SetWorksheetRowHeightCommand } from './commands/export { SetWorksheetRowHideCommand } from './commands/commands/set-worksheet-row-hide.command';export { SetWorksheetRowShowCommand } from './commands/commands/set-worksheet-row-show.command';export { SetWorksheetShowCommand } from './commands/commands/set-worksheet-show.command';-export { SetZoomRatioCommand } from './commands/commands/set-zoom-ratio.command';export {InsertColMutation,InsertColMutationUndoFactory as InsertColMutationFactory,@@ -120,8 +119,8 @@ export {type ISetWorksheetRowHeightMutationParams,SetWorksheetRowHeightMutation,} from './commands/mutations/set-worksheet-row-height.mutation';-export { SetZoomRatioMutation } from './commands/mutations/set-zoom-ratio.mutation';export { SetSelectionsOperation } from './commands/operations/selection.operation';+export { SetZoomRatioOperation as SetZoomRatioMutation } from './commands/operations/set-zoom-ratio.operation';export * from './Locale';// #endregiondiff --git a/packages/base-ui/src/services/notification/desktop-notification.service.ts b/packages/base-ui/src/services/notification/desktop-notification.service.tsindex bda2404509..5c5e8a8ce5 100644--- a/packages/base-ui/src/services/notification/desktop-notification.service.ts+++ b/packages/base-ui/src/services/notification/desktop-notification.service.ts@@ -1,10 +1,12 @@import { toDisposable } from '@univerjs/core';import { IDisposable } from '@wendellhu/redi';-import { INotificationService } from './notification.service';+import { INotificationService, INotificationShowParams } from './notification.service';export class DesktopNotificationService implements INotificationService {- show(): IDisposable {+ show(params: INotificationShowParams): IDisposable {+ window.alert(params.title);+return toDisposable(() => {});}}diff --git a/packages/base-ui/src/services/notification/notification.service.ts b/packages/base-ui/src/services/notification/notification.service.tsindex 2a5c89770b..67f5a70e76 100644--- a/packages/base-ui/src/services/notification/notification.service.ts+++ b/packages/base-ui/src/services/notification/notification.service.ts@@ -2,6 +2,10 @@ import { createIdentifier, IDisposable } from '@wendellhu/redi';export const INotificationService = createIdentifier<INotificationService>('univer.notification-service');+export interface INotificationShowParams {+ title: string;+}+export interface INotificationService {- show(): IDisposable;+ show(params: INotificationShowParams): IDisposable;}diff --git a/packages/core/src/Shared/ObjectArray.ts b/packages/core/src/Shared/ObjectArray.tsindex c49101cea0..837126e835 100644--- a/packages/core/src/Shared/ObjectArray.ts+++ b/packages/core/src/Shared/ObjectArray.ts@@ -52,7 +52,7 @@ const likeArr = (value: object): number => {* @beta*/export class ObjectArray<T> {- private _array!: ObjectArrayPrimitiveType<T>;+ private _objectArray!: ObjectArrayPrimitiveType<T>;private _length: number = 0;@@ -64,19 +64,19 @@ export class ObjectArray<T> {constructor(...argument: any) {switch (argument.length) {case 0: {- this._array = {};+ this._objectArray = {};this._length = 0;return;}case 1: {if (typeof argument[0] === 'number') {- this._array = {};+ this._objectArray = {};this._length = argument[0];return;}const length = likeArr(argument[0]);if (length > -1) {- this._array = argument[0];+ this._objectArray = argument[0];this._length = length;return;}@@ -84,7 +84,7 @@ export class ObjectArray<T> {}case 2: {if (likeArr(argument[0]) > -1) {- this._array = argument[0];+ this._objectArray = argument[0];this._length = argument[1];return;}@@ -119,22 +119,22 @@ export class ObjectArray<T> {}obtain(index: number, defaultValue: T): T {- return this._array[index] ?? defaultValue;+ return this._objectArray[index] ?? defaultValue;}getKeys(): string[] {- return ObjectArray.objectKeys(this._array);+ return ObjectArray.objectKeys(this._objectArray);}get(index: number): Nullable<T> {- return this._array[index];+ return this._objectArray[index];}set(index: number, value: T): void {// Accept NULL, for cell clear all// if (define(value)) {const length = this._length;- this._array[index] = value;+ this._objectArray[index] = value;if (index >= length) {this._length = index + 1;}@@ -143,7 +143,7 @@ export class ObjectArray<T> {pop(): Nullable<T> {const length = this._length;- const array = this._array;+ const array = this._objectArray;if (length > 0) {const lastIndex = length - 1;const lastValue = array[lastIndex];@@ -159,35 +159,35 @@ export class ObjectArray<T> {push(value: T): void {if (define(value)) {let length = this._length;- const array = this._array;+ const array = this._objectArray;array[length++] = value;this._length = length;}}first(): Nullable<T> {- return this._array[0];+ return this._objectArray[0];}last(): Nullable<T> {const length = this._length - 1;- return this._array[length];+ return this._objectArray[length];}shift(): Nullable<T> {const length = this._length;if (length > 0) {- const first = this._array[0];+ const first = this._objectArray[0];const sizeOf = length - 1;let next: T;for (let i = 0; i < sizeOf; i++) {- next = this._array[i + 1];+ next = this._objectArray[i + 1];if (define(next)) {- this._array[i] = next;+ this._objectArray[i] = next;}}this._length--;- delete this._array[sizeOf];+ delete this._objectArray[sizeOf];return first;}return null;@@ -196,11 +196,11 @@ export class ObjectArray<T> {unshift(topValue: T): void {if (define(topValue)) {const length = this._length;- const array = this._array;+ const array = this._objectArray;const sizeOf = length + 1;let last = array[0];for (let i = 1; i < sizeOf; i++) {- const temp = this._array[i];+ const temp = this._objectArray[i];if (define(last)) {array[i] = last;}@@ -212,7 +212,7 @@ export class ObjectArray<T> {}clear(): void {- this._array = {};+ this._objectArray = {};this._length = 0;}@@ -221,18 +221,18 @@ export class ObjectArray<T> {}getSizeOf(): number {- const array = this._array;+ const array = this._objectArray;const keys = Object.keys(array);return keys.length;}toJSON(): ObjectArrayPrimitiveType<T> {- return this._array;+ return this._objectArray;}toArray(): T[] {const native = new Array<T>();- const array = this._array;+ const array = this._objectArray;const keys = Object.keys(array);const length = keys.length;for (let i = 0; i < length; i++) {@@ -243,7 +243,7 @@ export class ObjectArray<T> {}forEach(callback: PredicateFunction<T>): ObjectArray<T> {- const array = this._array;+ const array = this._objectArray;const keys = Object.keys(array);const length = keys.length;for (let i = 0; i < length; i++) {@@ -271,7 +271,7 @@ export class ObjectArray<T> {}isEmpty(): boolean {- const array = this._array;+ const array = this._objectArray;const keys = Object.keys(array);return keys.length === 0;}@@ -288,7 +288,7 @@ export class ObjectArray<T> {const length = this._length;if (length > 0) {const end = index + 1;- const array = this._array;+ const array = this._objectArray;let effective = 0;const splice: ObjectArrayPrimitiveType<T> = {};for (let i = index; i < end; i++) {@@ -303,7 +303,7 @@ export class ObjectArray<T> {}includes(target: T): boolean {- const array = this._array;+ const array = this._objectArray;const keys = Object.keys(array);const length = keys.length;for (let i = 0; i < length; i++) {@@ -317,7 +317,7 @@ export class ObjectArray<T> {}slice(start: number, end: number): ObjectArray<T> {- const array = this._array;+ const array = this._objectArray;const length = this._length;if (length > 0) {const fragment: IKeyValue = {};@@ -335,16 +335,16 @@ export class ObjectArray<T> {}concat(target: ObjectArray<T>): ObjectArray<T> {- const srcArray = this._array;+ const srcArray = this._objectArray;const srcKeys = Object.keys(srcArray) as unknown as number[];const srcLength = srcKeys.length;- const targetArray = target._array;+ const targetArray = target._objectArray;const targetKeys = Object.keys(targetArray) as unknown as number[];const targetLength = targetKeys.length;const container = new ObjectArray<T>(srcLength + targetLength);- const containerArray = container._array;+ const containerArray = container._objectArray;let master = 0;for (let i = 0; i < srcLength; i++, master++) {@@ -360,7 +360,7 @@ export class ObjectArray<T> {}find(callback: PredicateFunction<T>): Nullable<T> {- const array = this._array;+ const array = this._objectArray;const keys = Object.keys(array);const length = keys.length;for (let i = 0; i < length; i++) {@@ -378,7 +378,7 @@ export class ObjectArray<T> {const length = this._length;if (length > 0) {const end = start + count;- const array = this._array;+ const array = this._objectArray;let effective = 0;const splice: ObjectArrayPrimitiveType<T> = {};for (let i = start; i < end; i++) {@@ -395,7 +395,7 @@ export class ObjectArray<T> {this._length -= diff;if (this._length <= 0) {- this._array = {};+ this._objectArray = {};this._length = 0;} else {for (let i = end; i < last; i++) {@@ -412,7 +412,7 @@ export class ObjectArray<T> {}findIndex(callback: PredicateFunction<T>): number {- const array = this._array;+ const array = this._objectArray;const keys = Object.keys(array);const length = keys.length;for (let i = 0; i < length; i++) {@@ -426,7 +426,7 @@ export class ObjectArray<T> {}map<S>(callback: Function<T, S>): ObjectArray<S> {- const array = this._array;+ const array = this._objectArray;const keys = Object.keys(array);const length = keys.length;const result: ObjectArrayPrimitiveType<S> = {};@@ -439,7 +439,7 @@ export class ObjectArray<T> {}filter(callback: PredicateFunction<T>): ObjectArray<T> {- const array = this._array;+ const array = this._objectArray;const keys = Object.keys(array);const length = keys.length;const filter: ObjectArrayPrimitiveType<T> = {};@@ -455,22 +455,89 @@ export class ObjectArray<T> {return new ObjectArray(filter, master);}- insert(index: number, value: T): ObjectArray<T> {+ // TODO: insert should support adding multi items at the same time for it+ // could improve performance+ insert(index: number, value: T): this {const length = this._length;- const array = this._array;+ const array = this._objectArray;++ // move all items after index in backward orderfor (let i = length - 1; i >= index; i--) {array[i + 1] = array[i];}+array[index] = value;this._length = length + 1;return this;}+ /**+ * Move some items some to another position+ * @param fromIndex index to move from, fromIndex is not necessary lesser than toIndex+ * @param count numbers of items to move+ * @param toIndex index moving to+ * @returns this+ */+ move(fromIndex: number, count: number, toIndex: number): this {+ const moveBackward = fromIndex > toIndex;+ if (!moveBackward && fromIndex + count > toIndex) {+ throw new Error('Invalid move operation');+ }++ if (moveBackward) {+ this._moveBackward(fromIndex, count, toIndex);+ } else {+ this._moveForward(fromIndex, count, toIndex);+ }++ return this;+ }++ private _moveBackward(fromIndex: number, count: number, toIndex: number): void {+ const array = this._objectArray;++ // cache item should be removed+ const toMove: T[] = [];+ for (let i = fromIndex; i < fromIndex + count; i++) {+ toMove.push(array[i]);+ }++ // move all items after toIndex in backward order+ for (let i = fromIndex - 1; i >= toIndex; i--) {+ array[i + count] = array[i];+ }++ // insert cached items to toIndex+ toMove.forEach((item, index) => {+ array[toIndex + index] = item;+ });+ }++ private _moveForward(fromIndex: number, count: number, toIndex: number): void {+ const array = this._objectArray;++ // cache item should be removed+ const toMove: T[] = [];+ for (let i = fromIndex; i < fromIndex + count; i++) {+ toMove.push(array[i]);+ }++ // move all items after toIndex in forward order+ for (let i = fromIndex + count; i < toIndex; i++) {+ array[i - count] = array[i];+ }++ // insert cached items to toIndex+ toMove.forEach((item, index) => {+ array[toIndex + index - count] = item;+ });+ }+inserts(index: number, target: ObjectArray<T>): ObjectArray<T> {- const targetArray = target._array;+ const targetArray = target._objectArray;const targetLength = target._length;- const srcArray = this._array;+ const srcArray = this._objectArray;const srcLength = this._length;const lastIndex = srcLength - 1;diff --git a/packages/core/src/Shared/ObjectMatrix.ts b/packages/core/src/Shared/ObjectMatrix.tsindex 474a510e2a..9ef3a3b199 100644--- a/packages/core/src/Shared/ObjectMatrix.ts+++ b/packages/core/src/Shared/ObjectMatrix.ts@@ -161,6 +161,18 @@ export class ObjectMatrix<T> {this._option.push(row.toJSON() as ObjectArrayPrimitiveType<T>);}+ moveRows(start: number, count: number, target: number): void {+ this._option.move(start, count, target);+ }++ moveColumns(start: number, count: number, target: number): void {+ // loop all rows and move column one by one, because our matrix is row-first+ this._option.forEach((row, value) => {+ const array = new ObjectArray(value);+ array.move(start, count, target);+ });+ }+insertRow(rowIndex: number, row: ObjectArray<T>): void {this._option.insert(rowIndex, row.toJSON() as ObjectArrayPrimitiveType<T>);}diff --git a/packages/core/src/Sheets/Domain/RowManager.ts b/packages/core/src/Sheets/Domain/RowManager.tsindex 606513c27e..731a6b4ac7 100644--- a/packages/core/src/Sheets/Domain/RowManager.ts+++ b/packages/core/src/Sheets/Domain/RowManager.ts@@ -32,37 +32,19 @@ export class RowManager {return rowData;}- /**- * Get the height of given row- * @param rowPos row index- * @returns- */getRowHeight(rowPos: number): number;- /**- * Get the height of more rows- * @param rowPos row index- * @param numRows row count- * @returns- */- getRowHeight(rowPos: number, numRows: number): number;- getRowHeight(...argument: any): number {+ getRowHeight(rowPos: number, count: number): number;+ getRowHeight(rowPos: number, count: number = 1): number {const { _rowData } = this;const config = this._config;let height: number = 0;- if (argument.length === 1) {- const row = _rowData.obtain(argument[0], {++ for (let i = 0; i < count; i++) {+ const row = _rowData.obtain(i + rowPos, {hd: BooleanNumber.FALSE,h: config.defaultRowHeight,});- height = row.h;- } else if (argument.length === 2) {- for (let i = argument[0]; i < argument[0] + argument[1]; i++) {- const row = _rowData.obtain(i, {- hd: BooleanNumber.FALSE,- h: config.defaultRowHeight,- });- height += row.h;- }+ height += row.h;}return height;diff --git a/packages/core/src/Sheets/Domain/Worksheet.ts b/packages/core/src/Sheets/Domain/Worksheet.tsindex 4a07ac18c6..adcc664e59 100644--- a/packages/core/src/Sheets/Domain/Worksheet.ts+++ b/packages/core/src/Sheets/Domain/Worksheet.ts@@ -122,6 +122,12 @@ export class Worksheet {return this._snapshot.mergeData;}+ /**+ * @deprecated use `getMergedCell` instead+ * @param row+ * @param col+ * @returns+ */getMergedCells(row: number, col: number): Nullable<IRange[]> {const _rectangleList = this._snapshot.mergeData;const rectList = [];@@ -135,6 +141,17 @@ export class Worksheet {return rectList.length ? rectList : null;}+ getMergedCell(row: number, col: number): Nullable<IRange> {+ const rectangleList = this._snapshot.mergeData;+ for (let i = 0; i < rectangleList.length; i++) {+ const range = rectangleList[i];+ if (Rectangle.intersects({ startRow: row, startColumn: col, endRow: row, endColumn: col }, range)) {+ return range;+ }+ }+ return null;+ }+/*** Get cell matrix from a given range and pick out non-first cells of merged cells.*/diff --git a/packages/core/src/Types/Interfaces/IRowData.ts b/packages/core/src/Types/Interfaces/IRowData.tsindex b10882cfdf..26d8e6ce41 100644--- a/packages/core/src/Types/Interfaces/IRowData.ts+++ b/packages/core/src/Types/Interfaces/IRowData.ts@@ -5,7 +5,7 @@ import { BooleanNumber } from '../Enum';*/export interface IRowData {/**- * height+ * height in pixel*/h: number;/**diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex cd9d1da8c6..e7e6e81bbc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -474,6 +474,9 @@ importers:'@univerjs/base-render':specifier: workspace:^0.0.1version: link:../base-render+ '@univerjs/base-ui':+ specifier: workspace:^0.0.1+ version: link:../base-ui'@univerjs/core':specifier: workspace:^0.0.1version: link:../core