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): reimplement selection expand & shrink (#180)
Wenzhao Huc28d4627ba4f
diff --git a/packages/base-sheets/src/commands/commands/__tests__/set-selections.command.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/set-selections.command.spec.tsnew file mode 100644index 0000000000..4a199b9a64--- /dev/null+++ b/packages/base-sheets/src/commands/commands/__tests__/set-selections.command.spec.ts@@ -0,0 +1,25 @@+import { describe, it } from 'node:test';++import { expect } from 'vitest';++// This spec file also tests selection-util.ts++describe('Test commands used for change selections', () => {+ describe('Simple movement', () => {+ it('placeholder', () => {+ expect(true).toBeTruthy();+ });+ });++ describe('Move to next gap cell', () => {+ expect(true).toBeTruthy();+ });++ describe('Expand to next selection or shrink', () => {+ expect(true).toBeTruthy();+ });++ describe('Expand to next gap position or shrink', () => {+ expect(true).toBeTruthy();+ });+});diff --git a/packages/base-sheets/src/commands/commands/set-selections.command.ts b/packages/base-sheets/src/commands/commands/set-selections.command.tsindex 9ad1c81b41..33181719ec 100644--- a/packages/base-sheets/src/commands/commands/set-selections.command.ts+++ b/packages/base-sheets/src/commands/commands/set-selections.command.ts@@ -13,14 +13,22 @@ import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../serimport { SetSelectionsOperation } from '../operations/selection.operation';import {expandToContinuousRange,+ expandToNextCell,expandToNextGapCell,expandToWholeSheet,- findNextGapCell,+ findNextGapRange,+ findNextRange,+ getRangeAtPosition,+ shrinkToNextCell,+ shrinkToNextGapCell,} from './utils/selection-util';+// TODO@wzhudev: we also need to handle when the current selection is the whole spreadsheet, whole rows or whole columns+export interface IChangeSelectionCommandParams {direction: Direction;- toNextGap?: boolean;++ jumpOver?: boolean;expand?: boolean;}@@ -34,58 +42,21 @@ export const ChangeSelectionCommand: ICommand<IChangeSelectionCommandParams> = {const selectionManagerService = accessor.get(SelectionManagerService);const commandService = accessor.get(ICommandService);- const selections = selectionManagerService.getRangeDatas();- if (!selections?.length || params == null) {+ const selection = selectionManagerService.getLast();+ if (!selection || !params) {return false;}- const { direction, toNextGap, expand } = params;- const startRange = selections[selections.length - 1];+ const { direction, jumpOver } = params;+ const startRange = selection.rangeData;+ let destRange = jumpOver+ ? findNextGapRange(startRange, direction, currentWorksheet)+ : findNextRange(startRange, direction, currentWorksheet);- let destRange: ISelectionRange = { ...startRange };+ destRange = getRangeAtPosition(destRange.startRow, destRange.startColumn, currentWorksheet);- if (!toNextGap) {- // navigation must be within the worksheet's range- switch (direction) {- case Direction.UP:- destRange.startRow = Math.max(0, startRange.startRow - 1);- destRange.endRow = destRange.startRow;- break;- case Direction.DOWN:- destRange.startRow = Math.min(startRange.endRow + 1, currentWorksheet.getRowCount() - 1);- destRange.endRow = destRange.startRow;- break;- case Direction.LEFT:- destRange.startColumn = Math.max(0, startRange.startColumn - 1);- destRange.endColumn = destRange.startColumn;- break;- case Direction.RIGHT:- destRange.startColumn = Math.min(startRange.endColumn + 1, currentWorksheet.getColumnCount() - 1);- destRange.endColumn = destRange.startColumn;- break;- default:- break;- }-- // deal with merged cells- currentWorksheet- .getMatrixWithMergedCells(- destRange.startRow,- destRange.startColumn,- destRange.startRow,- destRange.startColumn- )- .forValue((row, col, value) => {- destRange.startRow = row;- destRange.startColumn = col;- destRange.endRow = row + (value.rowSpan !== undefined ? value.rowSpan - 1 : 0);- destRange.endColumn = col + (value.colSpan !== undefined ? value.colSpan - 1 : 0);- });- } else if (!expand) {- destRange = findNextGapCell(destRange, direction, currentWorksheet);- } else {- destRange = expandToNextGapCell(destRange, direction, currentWorksheet);- console.log('debug expand to:', destRange);+ if (Rectangle.equals(destRange, startRange)) {+ return false;}return commandService.executeCommand(SetSelectionsOperation.id, {@@ -95,16 +66,7 @@ export const ChangeSelectionCommand: ICommand<IChangeSelectionCommandParams> = {selections: [{rangeData: destRange,- cellRange: {- row: destRange.startRow,- column: destRange.startColumn,- isMerged: false,- isMergedMainCell: false,- startRow: destRange.startRow,- startColumn: destRange.startColumn,- endRow: destRange.endRow,- endColumn: destRange.endColumn,- },+ cellRange: getRangeAtPosition(destRange.startRow, destRange.startColumn, currentWorksheet),},],});@@ -113,14 +75,79 @@ export const ChangeSelectionCommand: ICommand<IChangeSelectionCommandParams> = {export interface IExpandSelectionCommandParams {direction: Direction;- toNextGap?: boolean;- expand?: boolean;++ jumpOver?: boolean;}+// Though the command's name is "expand-selection", it actually does not expand but shrink the selection.+// That depends on the position of currentCell and the whole selection.export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {id: 'sheet.command.expand-selection',type: CommandType.COMMAND,- handler: async (accessor, params) => true,+ handler: async (accessor, params) => {+ const currentUniverService = accessor.get(ICurrentUniverService);+ const currentWorkbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();+ const currentWorksheet = currentWorkbook.getActiveSheet();+ const selectionManagerService = accessor.get(SelectionManagerService);+ const commandService = accessor.get(ICommandService);++ const selection = selectionManagerService.getLast();+ if (!selection || !params) {+ return false;+ }++ const startRange = selection.rangeData;+ const cellRange = selection.cellRange;+ if (!cellRange) {+ return false;+ }++ if (cellRange.startRow === -1) {+ // FIXME@DR-Univer+ // It maybe be related to click event handling. Try to click on C10 cell and use shift+arrow to expand selection.+ throw new Error('startRow is -1! @DR-Univer');+ }++ const { jumpOver, direction } = params;+ const isShrink = (function isShrink() {+ switch (direction) {+ case Direction.DOWN:+ return startRange.startRow < cellRange.startRow;+ case Direction.UP:+ return startRange.endRow > cellRange.endRow;+ case Direction.LEFT:+ return startRange.endColumn > cellRange.endColumn;+ case Direction.RIGHT:+ return startRange.startColumn < cellRange.startColumn;+ }+ })();++ const destRange = !isShrink+ ? jumpOver+ ? expandToNextGapCell(startRange, direction, currentWorksheet)+ : expandToNextCell(startRange, direction, currentWorksheet)+ : jumpOver+ ? shrinkToNextGapCell(startRange, cellRange, direction, currentWorksheet)+ : shrinkToNextCell(startRange, cellRange, direction, currentWorksheet);++ if (Rectangle.equals(destRange, startRange)) {+ return false;+ }++ return commandService.executeCommand(SetSelectionsOperation.id, {+ unitId: currentWorkbook.getUnitId(),+ sheetId: currentWorksheet.getSheetId(),+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,+ selections: [+ {+ rangeData: destRange,+ // cellRange: expand+ // ? selection.cellRange+ cellRange, // this remains unchanged+ },+ ],+ });+ },};export interface ISelectAllCommandParams {diff --git a/packages/base-sheets/src/commands/commands/utils/selection-util.ts b/packages/base-sheets/src/commands/commands/utils/selection-util.tsindex 15efd5fb09..e3f65602be 100644--- a/packages/base-sheets/src/commands/commands/utils/selection-util.ts+++ b/packages/base-sheets/src/commands/commands/utils/selection-util.ts@@ -1,4 +1,14 @@-import { Direction, ICellData, ISelectionRange, ObjectMatrix, Worksheet } from '@univerjs/core';+import {+ Direction,+ getReverseDirection,+ ICellData,+ ISelectionCell,+ ISelectionRange,+ ObjectMatrix,+ Rectangle,+ selectionToArray,+ Worksheet,+} from '@univerjs/core';export interface IExpandParams {left?: boolean;@@ -7,41 +17,18 @@ export interface IExpandParams {down?: boolean;}-/**- * If the current cell has value- */-export function findNextGapCell(- startRange: ISelectionRange,- direction: Direction,- worksheet: Worksheet-): ISelectionRange {- const params: IExpandParams = {- left: Direction.LEFT === direction,- right: Direction.RIGHT === direction,- up: Direction.UP === direction,- down: Direction.DOWN === direction,- };+export function getRangeAtPosition(row: number, col: number, worksheet: Worksheet): ISelectionCell {+ let destRange: ISelectionCell | null = null;- const expandedRange = expandToNextGapCell(startRange, direction, worksheet);- const row =- Direction.UP === direction- ? expandedRange.startRow- : Direction.DOWN === direction- ? expandedRange.endRow- : startRange.startRow;- const column =- Direction.LEFT === direction- ? expandedRange.startColumn- : Direction.RIGHT === direction- ? expandedRange.endColumn- : startRange.startColumn;- const matrix = worksheet.getMatrixWithMergedCells(row, column, row, column);-- let destRange: ISelectionRange | null = null;+ const matrix = worksheet.getMatrixWithMergedCells(row, col, row, col);matrix.forValue((row, col, value) => {destRange = {+ row,+ column: col,startRow: row,startColumn: col,+ isMerged: value.rowSpan !== undefined || value.colSpan !== undefined,+ isMergedMainCell: value.rowSpan !== undefined && value.colSpan !== undefined,endRow: row + (value.rowSpan !== undefined ? value.rowSpan - 1 : 0),endColumn: col + (value.colSpan !== undefined ? value.colSpan - 1 : 0),};@@ -54,52 +41,234 @@ export function findNextGapCell(return destRange;}-export function expandToNextGapCell(+export function findNextRange(startRange: ISelectionRange,direction: Direction,worksheet: Worksheet): ISelectionRange {- const params: IExpandParams = {- left: Direction.LEFT === direction,- right: Direction.RIGHT === direction,- up: Direction.UP === direction,- down: Direction.DOWN === direction,- };+ const destRange: ISelectionRange = { ...startRange };+ switch (direction) {+ case Direction.UP:+ destRange.startRow = Math.max(0, startRange.startRow - 1);+ destRange.endRow = destRange.startRow;+ break;+ case Direction.DOWN:+ destRange.startRow = Math.min(startRange.endRow + 1, worksheet.getRowCount() - 1);+ destRange.endRow = destRange.startRow;+ break;+ case Direction.LEFT:+ destRange.startColumn = Math.max(0, startRange.startColumn - 1);+ destRange.endColumn = destRange.startColumn;+ break;+ case Direction.RIGHT:+ destRange.startColumn = Math.min(startRange.endColumn + 1, worksheet.getColumnCount() - 1);+ destRange.endColumn = destRange.startColumn;+ break;+ default:+ break;+ }- const destRange = { ...startRange };+ return destRange;+}++export function findNextGapRange(+ startRange: ISelectionRange,+ direction: Direction,+ worksheet: Worksheet+): ISelectionRange {+ let destRange = { ...startRange };const maxRow = worksheet.getMaxRows();- function rangeHasValue(- row: number,- col: number,- rowEnd: number,- colEnd: number- ): {- hasValue: boolean;- matrix: ObjectMatrix<ICellData & { rowSpan?: number; colSpan?: number }>;- } {- let hasValue = false;-- const matrix = worksheet.getMatrixWithMergedCells(row, col, rowEnd, colEnd).forValue((_, __, value) => {- if (value.v) {- hasValue = true;- return false; // stop looping+ const { startRow, startColumn, endRow, endColumn } = getLastArrayOfRange(startRange, direction, worksheet);+ let currentPositionHasValue = rangeHasValue(worksheet, startRow, startColumn, endRow, endColumn).hasValue;+ let firstMove = true;+ let shouldContinue = true;++ while (shouldContinue) {+ if (Direction.UP === direction) {+ if (destRange.startRow === 0) {+ shouldContinue = false;+ break;}- });- return {- hasValue,- matrix,- };+ const destRow = destRange.startRow - 1; // it may decrease if there are merged cell+ const { hasValue: nextRangeHasValue, matrix } = rangeHasValue(+ worksheet,+ destRow,+ destRange.startColumn,+ destRow,+ destRange.endColumn+ );++ if (currentPositionHasValue && !nextRangeHasValue && !firstMove) {+ shouldContinue = false;+ break;+ } else {+ const r = {+ startColumn: destRange.startColumn,+ endColumn: destRange.endColumn,+ startRow: 1_000_000_000,+ endRow: 0,+ };+ matrix.forValue((row, _, value) => {+ r.startRow = Math.min(row, r.startRow);+ r.endRow = Math.max(row + (value.rowSpan || 1) - 1, r.endRow);+ });+ destRange = r;++ if (!currentPositionHasValue && nextRangeHasValue) {+ shouldContinue = false;+ break;+ }++ currentPositionHasValue = nextRangeHasValue;+ firstMove = false;+ }+ }++ if (Direction.DOWN === direction) {+ if (destRange.endRow === maxRow - 1) {+ shouldContinue = false;+ break;+ }++ const nextRow = destRange.endRow + 1;+ const { hasValue: nextRangeHasValue, matrix } = rangeHasValue(+ worksheet,+ nextRow,+ destRange.startColumn,+ nextRow,+ destRange.endColumn+ );++ if (currentPositionHasValue && !nextRangeHasValue && !firstMove) {+ shouldContinue = false;+ break;+ } else {+ const r = {+ startColumn: destRange.startColumn,+ endColumn: destRange.endColumn,+ startRow: 1_000_000_000,+ endRow: 0,+ };+ matrix.forValue((row, _, value) => {+ r.startRow = Math.min(r.startRow, row);+ r.endRow = Math.max(row + (value.rowSpan || 1) - 1, r.endRow);+ });+ destRange = r;++ if (!currentPositionHasValue && nextRangeHasValue) {+ shouldContinue = false;+ break;+ }++ currentPositionHasValue = nextRangeHasValue;+ firstMove = false;+ }+ }++ if (Direction.LEFT === direction) {+ if (destRange.startColumn === 0) {+ shouldContinue = false;+ break;+ }++ const destCol = destRange.startColumn - 1;+ const { hasValue: nextRangeHasValue, matrix } = rangeHasValue(+ worksheet,+ destRange.startRow,+ destCol,+ destRange.endRow,+ destCol+ );++ if (currentPositionHasValue && !nextRangeHasValue && !firstMove) {+ shouldContinue = false;+ break;+ } else {+ const r = {+ startRow: destRange.startRow,+ endRow: destRange.endRow,+ startColumn: 1_000_000_000,+ endColumn: 0,+ };+ matrix.forValue((_, col, value) => {+ r.startColumn = Math.min(col, r.startColumn);+ r.endColumn = Math.max(col + (value.colSpan || 1) - 1, r.endColumn);+ });++ destRange = r;++ if (!currentPositionHasValue && nextRangeHasValue) {+ shouldContinue = false;+ break;+ }++ currentPositionHasValue = nextRangeHasValue;+ firstMove = false;+ }+ }++ if (Direction.RIGHT === direction) {+ if (destRange.endColumn === worksheet.getMaxColumns() - 1) {+ shouldContinue = false;+ break;+ }++ const destCol = destRange.endColumn + 1;+ const { hasValue: nextRangeHasValue, matrix } = rangeHasValue(+ worksheet,+ destRange.startRow,+ destCol,+ destRange.endRow,+ destCol+ );++ if (currentPositionHasValue && !nextRangeHasValue && !firstMove) {+ shouldContinue = false;+ break;+ } else {+ const r = {+ startRow: destRange.startRow,+ endRow: destRange.endRow,+ startColumn: 1_000_000_000,+ endColumn: 0,+ };+ matrix.forValue((_, col, value) => {+ r.startColumn = Math.min(col, r.startColumn);+ r.endColumn = Math.max(col + (value.colSpan || 1) - 1, r.endColumn);+ });+ destRange = r;++ if (!currentPositionHasValue && nextRangeHasValue) {+ shouldContinue = false;+ break;+ }++ currentPositionHasValue = nextRangeHasValue;+ firstMove = false;+ }+ }}- const { startRow, startColumn, endRow, endColumn } = getLastArrayOfRange(startRange, direction);- let currentPositionHasValue = rangeHasValue(startRow, startColumn, endRow, endColumn).hasValue;+ return destRange;+}++export function expandToNextGapCell(+ startRange: ISelectionRange,+ direction: Direction,+ worksheet: Worksheet+): ISelectionRange {+ const destRange = { ...startRange };+ const maxRow = worksheet.getMaxRows();++ const { startRow, startColumn, endRow, endColumn } = getLastArrayOfRange(startRange, direction, worksheet);+ let currentPositionHasValue = rangeHasValue(worksheet, startRow, startColumn, endRow, endColumn).hasValue;let firstMove = true;let shouldContinue = true;while (shouldContinue) {- if (params.up) {+ if (Direction.UP === direction) {if (destRange.startRow === 0) {shouldContinue = false;break;@@ -107,12 +276,14 @@ export function expandToNextGapCell(const destRow = destRange.startRow - 1; // it may decrease if there are merged cellconst { hasValue: nextRangeHasValue, matrix } = rangeHasValue(+ worksheet,destRow,destRange.startColumn,destRow,destRange.endColumn);+ // case 1if (currentPositionHasValue && !nextRangeHasValue && !firstMove) {shouldContinue = false;break;@@ -126,17 +297,19 @@ export function expandToNextGapCell();});+ // case 2if (!currentPositionHasValue && nextRangeHasValue) {shouldContinue = false;break;}+ // other casescurrentPositionHasValue = nextRangeHasValue;firstMove = false;}}- if (params.down) {+ if (Direction.DOWN === direction) {if (destRange.endRow === maxRow - 1) {shouldContinue = false;break;@@ -144,6 +317,7 @@ export function expandToNextGapCell(const nextRow = destRange.endRow + 1;const { hasValue: nextRangeHasValue, matrix } = rangeHasValue(+ worksheet,nextRow,destRange.startColumn,nextRow,@@ -156,14 +330,8 @@ export function expandToNextGapCell(} else {matrix.forValue((row, col, value) => {destRange.startColumn = Math.min(col, destRange.startColumn);- destRange.endRow = Math.max(- row + (value.rowSpan !== undefined ? value.rowSpan - 1 : 0),- destRange.endRow- );- destRange.endColumn = Math.max(- col + (value.rowSpan === undefined ? 0 : value.rowSpan - 1),- destRange.endColumn- );+ destRange.endRow = Math.max(row + (value.rowSpan || 1) - 1, destRange.endRow);+ destRange.endColumn = Math.max(col + (value.colSpan || 1) - 1, destRange.endColumn);});if (!currentPositionHasValue && nextRangeHasValue) {@@ -176,7 +344,7 @@ export function expandToNextGapCell(}}- if (params.left) {+ if (Direction.LEFT === direction) {if (destRange.startColumn === 0) {shouldContinue = false;break;@@ -184,6 +352,7 @@ export function expandToNextGapCell(const destCol = destRange.startColumn - 1;const { hasValue: nextRangeHasValue, matrix } = rangeHasValue(+ worksheet,destRange.startRow,destCol,destRange.endRow,@@ -213,7 +382,7 @@ export function expandToNextGapCell(}}- if (params.right) {+ if (Direction.RIGHT === direction) {if (destRange.endColumn === worksheet.getMaxColumns() - 1) {shouldContinue = false;break;@@ -221,6 +390,7 @@ export function expandToNextGapCell(const destCol = destRange.endColumn + 1;const { hasValue: nextRangeHasValue, matrix } = rangeHasValue(+ worksheet,destRange.startRow,destCol,destRange.endRow,@@ -257,8 +427,132 @@ export function expandToNextGapCell(return destRange;}-// NOTE@wzhudev: Worksheet or Workbook used in commands layer / service layer / controller layer me should be-// changed to SheerViewModel or BookViewModel in the future.+/**+ * Adjust the range to align merged cell's borders.+ */+export function alignToMergedCellsBorders(startRange: ISelectionRange, worksheet: Worksheet, shouldRecursive = true) {+ const coveredMergedCells = worksheet.getMatrixWithMergedCells(...selectionToArray(startRange));+ const exceededMergedCells: ISelectionRange[] = [];++ coveredMergedCells.forValue((row, col, value) => {+ if (value.colSpan !== undefined && value.rowSpan !== undefined) {+ const mergedCellRange = {+ startRow: row,+ startColumn: col,+ endRow: row + value.rowSpan! - 1,+ endColumn: col + value.colSpan! - 1,+ };++ if (!Rectangle.contains(startRange, mergedCellRange)) {+ exceededMergedCells.push(mergedCellRange);+ }+ }+ });++ if (exceededMergedCells.length === 0) {+ return startRange;+ }++ const union = Rectangle.union(startRange, ...exceededMergedCells);+ if (shouldRecursive) {+ return alignToMergedCellsBorders(union, worksheet, shouldRecursive);+ }+ return union;+}++export function expandToNextCell(+ startRange: ISelectionRange,+ direction: Direction,+ worksheet: Worksheet+): ISelectionRange {+ const next = findNextRange(startRange, direction, worksheet);+ const destRange: ISelectionRange = {+ startRow: Math.min(startRange.startRow, next.startRow),+ startColumn: Math.min(startRange.startColumn, next.startColumn),+ endRow: Math.max(startRange.endRow, next.endRow),+ endColumn: Math.max(startRange.endColumn, next.endColumn),+ };++ return alignToMergedCellsBorders(Rectangle.union(startRange, destRange), worksheet);+}++/**+ * This function is considered as a reversed operation of `expandToNextGapCell` but there are slightly differences.+ * @param startRange+ * @param direction+ * @param worksheet+ */+export function shrinkToNextGapCell(+ startRange: ISelectionRange,+ anchorRange: ISelectionRange,+ direction: Direction,+ worksheet: Worksheet+): ISelectionRange {+ // use `moveToNextGapCell` reversely to get the next going to cell+ const reversedDirection = getReverseDirection(direction);+ const nextGap = findNextGapRange(+ getLastArrayOfRange(startRange, reversedDirection, worksheet),+ direction,+ worksheet+ );++ // if next exceed the startRange we should just expand anchorRange with+ if (direction === Direction.UP && nextGap.startRow <= startRange.startRow) {+ return alignToMergedCellsBorders(+ { ...anchorRange, startColumn: startRange.startColumn, endColumn: startRange.endColumn },+ worksheet,+ true+ );+ }+ if (direction === Direction.DOWN && nextGap.endRow >= startRange.endRow) {+ return alignToMergedCellsBorders(+ { ...anchorRange, startColumn: startRange.startColumn, endColumn: startRange.endColumn },+ worksheet,+ true+ );+ }+ if (direction === Direction.LEFT && nextGap.startColumn <= startRange.startColumn) {+ return alignToMergedCellsBorders(+ { ...anchorRange, startRow: startRange.startRow, endRow: startRange.endRow },+ worksheet,+ true+ );+ }+ if (direction === Direction.RIGHT && nextGap.endColumn >= startRange.endColumn) {+ return alignToMergedCellsBorders(+ { ...anchorRange, startRow: startRange.startRow, endRow: startRange.endRow },+ worksheet,+ true+ );+ }+ return Rectangle.union(anchorRange, nextGap);+}++/**+ * This function is considered as a reversed operation of `expandToNextCell` but there are some slightly differences.+ * @param startRange+ * @param direction+ * @param worksheet+ */+export function shrinkToNextCell(+ startRange: ISelectionRange,+ anchorRange: ISelectionRange,+ direction: Direction,+ worksheet: Worksheet+): ISelectionRange {+ // use `moveToNextCell` reversely to get the next going to cell+ const reversedDirection = getReverseDirection(direction);+ const next = findNextRange(getLastArrayOfRange(startRange, reversedDirection, worksheet), direction, worksheet);++ const destRange: ISelectionRange = {+ startRow: Math.min(anchorRange.startRow, next.startRow),+ startColumn: Math.min(anchorRange.startColumn, next.startColumn),+ endRow: Math.max(anchorRange.endRow, next.endRow),+ endColumn: Math.max(anchorRange.endColumn, next.endColumn),+ };++ return destRange;+}export function expandToContinuousRange(startRange: ISelectionRange,@@ -374,37 +668,70 @@ export function expandToWholeSheet(worksheet: Worksheet): ISelectionRange {};}-function getLastArrayOfRange(startRange: ISelectionRange, direction: Direction): ISelectionRange {+function getLastArrayOfRange(startRange: ISelectionRange, direction: Direction, worksheet: Worksheet): ISelectionRange {+ let destRange: ISelectionRange;switch (direction) {case Direction.UP:- return {+ destRange = {startRow: startRange.startRow,startColumn: startRange.startColumn,endRow: startRange.startRow,endColumn: startRange.endColumn,};++ break;case Direction.DOWN:- return {+ destRange = {startRow: startRange.endRow,startColumn: startRange.startColumn,endRow: startRange.endRow,endColumn: startRange.endColumn,};+ break;case Direction.LEFT:- return {+ destRange = {startRow: startRange.startRow,startColumn: startRange.startColumn,endRow: startRange.endRow,endColumn: startRange.startColumn,};+ break;case Direction.RIGHT:- return {+ destRange = {startRow: startRange.startRow,startColumn: startRange.endColumn,endRow: startRange.endRow,endColumn: startRange.endColumn,};+ break;default:throw new Error('Invalid direction');}++ return alignToMergedCellsBorders(destRange, worksheet, false);+}++function rangeHasValue(+ worksheet: Worksheet,+ row: number,+ col: number,+ rowEnd: number,+ colEnd: number+): {+ hasValue: boolean;+ matrix: ObjectMatrix<ICellData & { rowSpan?: number; colSpan?: number }>;+} {+ let hasValue = false;++ const matrix = worksheet.getMatrixWithMergedCells(row, col, rowEnd, colEnd).forValue((_, __, value) => {+ if (value.v) {+ hasValue = true;+ return false; // stop looping+ }+ });++ return {+ hasValue,+ matrix,+ };}diff --git a/packages/core/src/Shared/Rectangle.ts b/packages/core/src/Shared/Rectangle.tsindex cf3c00f0a8..c3cf51069e 100644--- a/packages/core/src/Shared/Rectangle.ts+++ b/packages/core/src/Shared/Rectangle.ts@@ -1,52 +1,10 @@import { ISelectionRange } from '../Types/Interfaces/ISelectionRange';-import { Tools } from './Tools';import { Nullable } from './Types';-// TODO: it seems that this wrapper is not necessary. Only static methods are good.-/**- * A square area containing four position information: startRow, startColumn, endRow, and endColumn+ * This class provides a set of methods to calculate `ISelectionRange`.*/-export class Rectangle implements ISelectionRange {- startRow: number;-- startColumn: number;-- endRow: number;-- endColumn: number;-- constructor();- constructor(rectangle: ISelectionRange);- constructor(startRow: number, startColumn: number, endRow: number, endColumn: number);- constructor(...argument: any[]) {- if (Tools.hasLength(argument, 0)) {- this.startRow = 0;- this.startColumn = 0;- this.endRow = 0;- this.endColumn = 0;- return;- }- if (Tools.hasLength(argument, 1)) {- const rectangle = argument[0];- this.startRow = rectangle.startRow;- this.startColumn = rectangle.startColumn;- this.endRow = rectangle.endRow;- this.endColumn = rectangle.endColumn;- return;- }- if (Tools.hasLength(argument, 4)) {- const startRow = argument[0];- const startColumn = argument[1];- const endRow = argument[2];- const endColumn = argument[3];- this.startRow = startRow;- this.startColumn = startColumn;- this.endRow = endRow;- this.endColumn = endColumn;- }- }-+export class Rectangle {static equals(src: ISelectionRange, target: ISelectionRange): boolean {return (src.endRow === target.endRow &&@@ -138,30 +96,80 @@ export class Rectangle implements ISelectionRange {};}- intersects(rectangle: Rectangle): boolean {- return Rectangle.intersects(this, rectangle);+ static subtract(src: ISelectionRange, target: ISelectionRange): Nullable<ISelectionRange[]> {+ const intersected = Rectangle.getIntersects(src, target);+ if (!intersected) {+ return [src];+ }++ const result: ISelectionRange[] = [];+ const { startRow, endRow, startColumn, endColumn } = intersected;+ const { startRow: srcStartRow, endRow: srcEndRow, startColumn: srcStartColumn, endColumn: srcEndColumn } = src;++ // subtract could result in eight pieces and these eight pieces and be merged to at most four pieces}- union(rectangle: Rectangle) {- const { startRow, startColumn, endRow, endColumn } = this;- return new Rectangle(- rectangle.startRow < this.startRow ? rectangle.startRow : startRow,- rectangle.startColumn < startColumn ? rectangle.startColumn : startColumn,- rectangle.endRow > endRow ? rectangle.endRow : endRow,- rectangle.endColumn > endColumn ? rectangle.endColumn : endColumn+ static contains(src: ISelectionRange, target: ISelectionRange): boolean {+ return (+ src.startRow <= target.startRow &&+ src.endRow >= target.endRow &&+ src.startColumn <= target.startColumn &&+ src.endColumn >= target.endColumn);}- getData() {- return {- startRow: this.startRow,- startColumn: this.startColumn,- endRow: this.endRow,- endColumn: this.endColumn,- };+ static realContain(src: ISelectionRange, target: ISelectionRange): boolean {+ return (+ Rectangle.contains(src, target) &&+ (src.startRow < target.startRow ||+ src.endRow > target.endRow ||+ src.startColumn < target.startColumn ||+ src.endColumn > target.endColumn)+ );}- equals(rectangle: Rectangle) {- return Rectangle.equals(this, rectangle);+ static union(...ranges: ISelectionRange[]): ISelectionRange {+ return ranges.reduce(+ (acc, current) => ({+ startRow: Math.min(acc.startRow, current.startRow),+ startColumn: Math.min(acc.startColumn, current.startColumn),+ endRow: Math.max(acc.endRow, current.endRow),+ endColumn: Math.max(acc.endColumn, current.endColumn),+ }),+ ranges[0]+ );}++ // /**+ // * @deprecated use static methods+ // * @param rectangle+ // * @returns+ // */+ // intersects(rectangle: Rectangle): boolean {+ // return Rectangle.intersects(this, rectangle);+ // }++ // /**+ // * @deprecated use static methods+ // * @param rectangle+ // * @returns+ // */+ // union(rectangle: Rectangle) {+ // const { startRow, startColumn, endRow, endColumn } = this;+ // return new Rectangle(+ // rectangle.startRow < this.startRow ? rectangle.startRow : startRow,+ // rectangle.startColumn < startColumn ? rectangle.startColumn : startColumn,+ // rectangle.endRow > endRow ? rectangle.endRow : endRow,+ // rectangle.endColumn > endColumn ? rectangle.endColumn : endColumn+ // );+ // }++ // getData() {+ // return {+ // startRow: this.startRow,+ // startColumn: this.startColumn,+ // endRow: this.endRow,+ // endColumn: this.endColumn,+ // };+ // }}diff --git a/packages/core/src/Sheets/Domain/Worksheet.ts b/packages/core/src/Sheets/Domain/Worksheet.tsindex 0c26934ed0..299be68a48 100644--- a/packages/core/src/Sheets/Domain/Worksheet.ts+++ b/packages/core/src/Sheets/Domain/Worksheet.ts@@ -130,12 +130,10 @@ export class Worksheet {getMergedCells(row: number, col: number): Nullable<ISelectionRange[]> {const _rectangleList = this._snapshot.mergeData;const rectList = [];- const target = new Rectangle(row, col, row, col);for (let i = 0; i < _rectangleList.length; i++) {- const rectangle = _rectangleList[i];- if (target!.intersects(new Rectangle(rectangle))) {- // return rectangle;- rectList.push(rectangle);+ const range = _rectangleList[i];+ if (Rectangle.intersects({ startRow: row, startColumn: col, endRow: row, endColumn: col }, range)) {+ rectList.push(range);}}@@ -155,11 +153,9 @@ export class Worksheet {const matrix = this.getCellMatrix();// get all merged cells- const mergedCellsInRange = this._snapshot.mergeData.filter((rect) => {- const rectRange = new Rectangle(rect);- const targetRange = new Rectangle(row, col, endRow, endCol);- return rectRange.intersects(targetRange);- });+ const mergedCellsInRange = this._snapshot.mergeData.filter((rect) =>+ Rectangle.intersects({ startRow: row, startColumn: col, endRow, endColumn: endCol }, rect)+ );const ret = new ObjectMatrix<ICellData & { rowSpan?: number; colSpan?: number }>();diff --git a/packages/core/src/Types/Enum/Direction.ts b/packages/core/src/Types/Enum/Direction.tsindex 6acf2f6ea5..6bd96e32d3 100644--- a/packages/core/src/Types/Enum/Direction.ts+++ b/packages/core/src/Types/Enum/Direction.ts@@ -1,9 +1,19 @@-/**- * Direction: Top/Bottom/Left/Right- */export enum Direction {- LEFT,- RIGHT,UP,+ RIGHT,DOWN,+ LEFT,+}++export function getReverseDirection(direction: Direction): Direction {+ switch (direction) {+ case Direction.LEFT:+ return Direction.RIGHT;+ case Direction.RIGHT:+ return Direction.LEFT;+ case Direction.UP:+ return Direction.DOWN;+ case Direction.DOWN:+ return Direction.UP;+ }}diff --git a/packages/core/src/Types/Interfaces/ISelectionRange.ts b/packages/core/src/Types/Interfaces/ISelectionRange.tsindex dfdd4f11bc..eb974e5c08 100644--- a/packages/core/src/Types/Interfaces/ISelectionRange.ts+++ b/packages/core/src/Types/Interfaces/ISelectionRange.ts@@ -37,6 +37,15 @@ export interface ISelectionRange {endColumn: number;}+/**+ * Transform an `ISelectionRange` object to an array.+ * @param range+ * @returns [rowStart, colStart, rowEnd, colEnd]+ */+export function selectionToArray(range: ISelectionRange): [number, number, number, number] {+ return [range.startRow, range.startColumn, range.endRow, range.endColumn];+}+/*** Range data of grid*/diff --git a/packages/ui-plugin-sheets/src/controller/shortcuts/selection.shortcut.ts b/packages/ui-plugin-sheets/src/controller/shortcuts/selection.shortcut.tsindex c484ed1186..3c6504fb61 100644--- a/packages/ui-plugin-sheets/src/controller/shortcuts/selection.shortcut.ts+++ b/packages/ui-plugin-sheets/src/controller/shortcuts/selection.shortcut.ts@@ -64,7 +64,7 @@ export const MoveSelectionEndDownShortcutItem: IShortcutItem<IChangeSelectionCompreconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET),staticParameters: {direction: Direction.DOWN,- toNextGap: true,+ jumpOver: true,},};@@ -74,7 +74,7 @@ export const MoveSelectionEndUpShortcutItem: IShortcutItem<IChangeSelectionCommapreconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET),staticParameters: {direction: Direction.UP,- toNextGap: true,+ jumpOver: true,},};@@ -84,7 +84,7 @@ export const MoveSelectionEndLeftShortcutItem: IShortcutItem<IChangeSelectionCompreconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET),staticParameters: {direction: Direction.LEFT,- toNextGap: true,+ jumpOver: true,},};@@ -94,12 +94,10 @@ export const MoveSelectionEndRightShortcutItem: IShortcutItem<IChangeSelectionCopreconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET),staticParameters: {direction: Direction.RIGHT,- toNextGap: true,+ jumpOver: true,},};-// continuous selection by cell-export const ExpandSelectionDownShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {id: ExpandSelectionCommand.id,binding: KeyCode.ARROW_DOWN | MetaKeys.SHIFT,@@ -139,46 +137,42 @@ export const ExpandSelectionRightShortcutItem: IShortcutItem<IExpandSelectionCom// continuous selection to continuous endexport const ExpandSelectionEndDownShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {- id: ChangeSelectionCommand.id,+ id: ExpandSelectionCommand.id,binding: KeyCode.ARROW_DOWN | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,preconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET),staticParameters: {direction: Direction.DOWN,- toNextGap: true,- expand: true,+ jumpOver: true,},};export const ExpandSelectionEndUpShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {- id: ChangeSelectionCommand.id,+ id: ExpandSelectionCommand.id,binding: KeyCode.ARROW_UP | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,preconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET),staticParameters: {direction: Direction.UP,- toNextGap: true,- expand: true,+ jumpOver: true,},};export const ExpandSelectionEndLeftShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {- id: ChangeSelectionCommand.id,+ id: ExpandSelectionCommand.id,binding: KeyCode.ARROW_LEFT | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,preconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET),staticParameters: {direction: Direction.LEFT,- toNextGap: true,- expand: true,+ jumpOver: true,},};export const ExpandSelectionEndRightShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {- id: ChangeSelectionCommand.id,+ id: ExpandSelectionCommand.id,binding: KeyCode.ARROW_RIGHT | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,preconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET),staticParameters: {direction: Direction.RIGHT,- toNextGap: true,- expand: true,+ jumpOver: true,},};