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
fix(selection): fix multiple selection use tab not right issue (#4288)
VicKun2a010766baef
diff --git a/packages/sheets-ui/src/commands/commands/set-selection.command.ts b/packages/sheets-ui/src/commands/commands/set-selection.command.tsindex 0b14d8457f..96063e78a3 100644--- a/packages/sheets-ui/src/commands/commands/set-selection.command.ts+++ b/packages/sheets-ui/src/commands/commands/set-selection.command.ts@@ -14,10 +14,11 @@* limitations under the License.*/-import type { Direction, ICommand, IRange } from '@univerjs/core';+import type { ICommand, IRange } from '@univerjs/core';import type {- ISetSelectionsOperationParams } from '@univerjs/sheets';-import { CommandType, ICommandService, IUniverInstanceService, RANGE_TYPE, Rectangle, Tools } from '@univerjs/core';+ ISetSelectionsOperationParams,+} from '@univerjs/sheets';+import { CommandType, Direction, ICommandService, IUniverInstanceService, RANGE_TYPE, Rectangle, Tools } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import {@@ -140,6 +141,7 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTabid: 'sheet.command.move-selection-enter-tab',type: CommandType.COMMAND,+ // eslint-disable-next-line max-lines-per-function, complexityhandler: async (accessor, params) => {if (!params) {return false;@@ -149,11 +151,20 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTabif (!target) return false;const { workbook, worksheet } = target;+ const selectionsService = getSelectionsService(accessor);+ const { direction, keycode } = params;+ const isReverse = direction === Direction.LEFT || direction === Direction.UP;- const selection = getSelectionsService(accessor).getCurrentLastSelection();+ const selections = selectionsService.getCurrentSelections().concat();+ const currentSelectionIndex = selections.findIndex((s) => s.primary);+ const selection = selections[currentSelectionIndex];if (!selection) {return false;}+ // for shift tab or shift enter, the direction should be reversed. so we need find the previous selection.+ const delta = isReverse ? -1 : 1;+ const nextSelection = currentSelectionIndex + delta !== selections.length ? selections[currentSelectionIndex + delta] : selections[0];+ const nextSelectionIndex = selections.findIndex((s) => s === nextSelection);const unitId = workbook.getUnitId();const sheetId = worksheet.getSheetId();@@ -161,8 +172,8 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTabreturn false;}- const { direction, keycode } = params;- const { range, primary } = selection;+ const { range } = selection;+ const primary = selection.primary!;let startRange = getStartRange(range, primary, direction);const shortcutExperienceService = accessor.get(ShortcutExperienceService);@@ -173,7 +184,12 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTab});let resultRange;+const { startRow, endRow, startColumn, endColumn } = range;++ // for the last cell in the selection, the next cell should be the next selection's start cell.+ const isLastCell = isReverse ? primary.startRow === startRow && primary.startColumn === startColumn : primary.endRow === endRow && primary.endColumn === endColumn;+ // not single cell should be handled by the move-selection active cellif (!Rectangle.equals(range, primary)) {// Handle the situation of moving the active cell within the selection area.shortcutExperienceService.remove({@@ -184,38 +200,42 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTabconst newPrimary = Tools.deepClone(primary);- const next = findNextRange(- {- startRow: newPrimary.startRow,- startColumn: newPrimary.startColumn,- endRow: newPrimary.endRow,- endColumn: newPrimary.endColumn,- },- direction,- worksheet,- {- startRow,- endRow,- startColumn,- endColumn,- }- );-- const destRange = getCellAtRowCol(next.startRow, next.startColumn, worksheet);+ const next = isLastCell+ ? nextSelection.range :+ findNextRange(+ {+ startRow: newPrimary.startRow,+ startColumn: newPrimary.startColumn,+ endRow: newPrimary.endRow,+ endColumn: newPrimary.endColumn,+ },+ direction,+ worksheet,+ {+ startRow,+ endRow,+ startColumn,+ endColumn,+ }+ );++ const useLeftTopAsDest = isLastCell && isReverse;+ const destRange = useLeftTopAsDest ? getCellAtRowCol(next.endRow, next.endColumn, worksheet) : getCellAtRowCol(next.startRow, next.startColumn, worksheet);resultRange = {- range: Rectangle.clone(range),+ range: isLastCell ? nextSelection.range : Rectangle.clone(range),primary: {startRow: destRange.startRow,startColumn: destRange.startColumn,endRow: destRange.endRow,endColumn: destRange.endColumn,- actualRow: next.startRow,- actualColumn: next.startColumn,+ actualRow: useLeftTopAsDest ? destRange.startRow : next.startRow,+ actualColumn: useLeftTopAsDest ? destRange.startColumn : next.startColumn,isMerged: destRange.isMerged,isMergedMainCell:destRange.startRow === next.startRow && destRange.startColumn === next.startColumn,},+ style: isLastCell ? nextSelection.style : selection.style,};} else {// Handle the regular situation of moving the selection area.@@ -267,11 +287,19 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTab};}+ if (isLastCell) {+ selections[currentSelectionIndex].primary = null;+ selections[nextSelectionIndex] = resultRange;+ selectionsService.setSelections(unitId, sheetId, [], SelectionMoveType.MOVE_END);+ } else {+ selections[currentSelectionIndex] = resultRange;+ }+const rs = accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {unitId,subUnitId: sheetId,type: SelectionMoveType.MOVE_END,- selections: [resultRange],+ selections,});const renderManagerService = accessor.get(IRenderManagerService);const selectionService = renderManagerService.getRenderById(unitId)?.with(ISheetSelectionRenderService);diff --git a/packages/sheets/src/facade/f-range.ts b/packages/sheets/src/facade/f-range.tsindex 79ddc4d12d..82769b77e5 100644--- a/packages/sheets/src/facade/f-range.ts+++ b/packages/sheets/src/facade/f-range.ts@@ -17,9 +17,10 @@import type { CellValue, ICellData, IColorStyle, IObjectMatrixPrimitiveType, IRange, IStyleData, ITextDecoration, Nullable, Workbook, Worksheet } from '@univerjs/core';import type { ISetHorizontalTextAlignCommandParams, ISetStyleCommandParams, ISetTextWrapCommandParams, ISetVerticalTextAlignCommandParams, IStyleTypeValue } from '@univerjs/sheets';import type { FHorizontalAlignment, FVerticalAlignment } from './utils';-import { BooleanNumber, Dimension, FBase, ICommandService, Inject, Injector, Rectangle, WrapStrategy } from '@univerjs/core';+import { BooleanNumber, Dimension, FBase, ICommandService, Inject, Injector, Rectangle, Tools, WrapStrategy } from '@univerjs/core';import { FormulaDataModel } from '@univerjs/engine-formula';import { addMergeCellsUtil, getAddMergeMutationRangeByType, RemoveWorksheetMergeCommand, SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand } from '@univerjs/sheets';+import { FWorkbook } from './f-workbook';import { covertCellValue, covertCellValues, transformCoreHorizontalAlignment, transformCoreVerticalAlignment, transformFacadeHorizontalAlignment, transformFacadeVerticalAlignment } from './utils';export type FontLine = 'none' | 'underline' | 'line-through';@@ -586,7 +587,7 @@ export class FRange extends FBase {}/**- * Unmerge cells in the range+ * Break all horizontally- or vertically-merged cells contained within the range list into individual cells again.* @returns This range, for chaining*/breakApart(): FRange {@@ -598,7 +599,18 @@ export class FRange extends FBase {/*** Iterate cells in this range. Merged cells will be respected.- * @param callback+ * @param callback the callback function to be called for each cell in the range+ * @param {number} callback.row the row number of the cell+ * @param {number} callback.col the column number of the cell+ * @param {ICellData} callback.cell the cell data+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorksheet = fWorkbook.getActiveSheet();+ * const fRange = fWorksheet.getRange('A1:B2');+ * fRange.forEach((row, col, cell) => {+ * console.log(row, col, cell);+ * });+ * ```*/forEach(callback: (row: number, col: number, cell: ICellData) => void): void {// Iterate each cell in this range.@@ -609,4 +621,67 @@ export class FRange extends FBase {callback(row, col, value);});}++ /**+ * Returns a string description of the range, in A1 notation.+ * @returns {string} The A1 notation of the range.+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorksheet = fWorkbook.getActiveSheet();+ * const fRange = fWorksheet.getRange('A1:B2');+ * console.log(fRange.getA1Notation()); // A1:B2+ * ```+ */+ getA1Notation(): string {+ const { startRow, endRow, startColumn, endColumn } = this._range;+ let start;+ let end;+ if (startColumn < endColumn) {+ start = Tools.numToWord(startColumn + 1) + (startRow + 1);+ end = Tools.numToWord(endColumn + 1) + (endRow + 1);+ } else {+ start = Tools.numToWord(endColumn + 1) + (endRow + 1);+ end = Tools.numToWord(startColumn + 1) + (startRow + 1);+ }++ if (start === end) return `${start}`;+ return `${start}:${end}`;+ }++ /**+ * Sets the specified range as the active range, with the top left cell in the range as the current cell.+ * @returns {FRange} This range, for chaining.+ * @example+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorksheet = fWorkbook.getActiveSheet();+ * const fRange = fWorksheet.getRange('A1:B2');+ * fRange.activate(); // the active cell will be A1+ * ```+ */+ activate(): FRange {+ const fWorkbook = this._injector.createInstance(FWorkbook, this._workbook);+ fWorkbook.setActiveRange(this);+ return this;+ }++ /**+ * Sets the specified cell as the current cell.+ * If the specified cell is present in an existing range, then that range becomes the active range with the cell as the current cell.+ * If the specified cell is not part of an existing range, then a new range is created with the cell as the active range and the current cell.+ * @returns {FRange} This range, for chaining.+ * @description If the range is not a single cell, an error will be thrown.+ */+ activateAsCurrentCell(): FRange {+ const mergeInfo = this._worksheet.getMergedCell(this._range.startRow, this._range.startColumn);+ // the range is a merge cell or single cell+ const valid = (mergeInfo && Rectangle.equals(mergeInfo, this._range)) ||+ (!mergeInfo && this._range.startRow === this._range.endRow && this._range.startColumn === this._range.endColumn);++ if (valid) {+ return this.activate();+ } else {+ throw new Error('The range is not a single cell');+ }+ }}diff --git a/packages/sheets/src/facade/f-selection.ts b/packages/sheets/src/facade/f-selection.tsindex 4b081ddf15..0d8fc74ae5 100644--- a/packages/sheets/src/facade/f-selection.ts+++ b/packages/sheets/src/facade/f-selection.ts@@ -14,11 +14,14 @@* limitations under the License.*/-import type { ISelectionCell, Nullable, Workbook, Worksheet } from '@univerjs/core';-import type { ISelectionWithStyle } from '@univerjs/sheets';-import { Inject, Injector } from '@univerjs/core';+import type { Direction, ISelectionCell, Nullable, Workbook, Worksheet } from '@univerjs/core';+import type { ISelectionWithStyle, ISetSelectionsOperationParams } from '@univerjs/sheets';+import { ICommandService, Inject, Injector, Rectangle } from '@univerjs/core';+import { getNextPrimaryCell, getPrimaryForRange, SetSelectionsOperation } from '@univerjs/sheets';import { FRange } from './f-range';+import { FWorkbook } from './f-workbook';+import { FWorksheet } from './f-worksheet';/*** @description Represents the active selection in the sheet.@@ -76,5 +79,104 @@ export class FSelection {return current.primary;}++ /**+ * Returns the active sheet in the spreadsheet.+ * @returns {FWorksheet} The active sheet in the spreadsheet.+ * @example+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorksheet = fWorkbook.getActiveSheet();+ * const fSelection = fWorksheet.getSelection();+ * const activeSheet = fSelection.getActiveSheet();+ * console.log(activeSheet.equalTo(fWorksheet)); // true+ * ```+ */+ getActiveSheet(): FWorksheet {+ const fWorkbook = this._injector.createInstance(FWorkbook, this._workbook);+ return this._injector.createInstance(FWorksheet, fWorkbook, this._workbook, this._worksheet);+ }++ /**+ * Update the primary cell in the selection. if the primary cell not exists in selections, add it to the selections and clear the old selections.+ * @param {FRange} cell The new primary cell to update.+ * @returns {FSelection} The new selection after updating the primary cell.Because the selection is immutable, the return value is a new selection.+ * @example+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorksheet = fWorkbook.getActiveSheet();+ * const fSelection = fWorksheet.getSelection();+ * const cell = fWorksheet.getCell('A1');+ * const newSelection = fSelection.updatePrimaryCell(cell);+ * console.log(newSelection.getActiveRange().getA1Notation()); // A1+ * ```+ */+ async updatePrimaryCell(cell: FRange): Promise<FSelection> {+ const commandService = this._injector.get(ICommandService);+ let newSelections = [];+ let hasSetPrimary = false;+ for (const { range, style } of this._selections) {+ if (Rectangle.contains(range, cell.getRange())) {+ newSelections.push({+ range,+ primary: getPrimaryForRange(cell.getRange(), this._worksheet),+ style,+ });+ hasSetPrimary = true;+ } else {+ newSelections.push({+ range,+ primary: null,+ style,+ });+ }+ }++ if (!hasSetPrimary) {+ newSelections = [+ {+ range: cell.getRange(),+ primary: getPrimaryForRange(cell.getRange(), this._worksheet),+ },+ ];+ }++ const setSelectionOperationParams: ISetSelectionsOperationParams = {+ unitId: this._workbook.getUnitId(),+ subUnitId: this._worksheet.getSheetId(),+ selections: newSelections,+ };++ await commandService.syncExecuteCommand(SetSelectionsOperation.id, setSelectionOperationParams);+ return new FSelection(this._workbook, this._worksheet, newSelections, this._injector);+ }++ /**+ *Get the next primary cell in the specified direction. If the primary cell not exists in selections, return null.+ * @param {Direction} direction The direction to move the primary cell.The enum value is maybe one of the following: UP(0),RIGHT(1), DOWN(2), LEFT(3).+ * @returns {FRange | null} The next primary cell in the specified direction.+ * @example+ * ```ts+ * // import { Direction } from '@univerjs/core';+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorksheet = fWorkbook.getActiveSheet();+ * // make sure the active cell is A1 and selection is A1:C3+ * const fSelection = fWorksheet.getSelection();+ * const nextCell = fSelection.getNextDataRange(Direction.RIGHT);+ * console.log(nextCell?.getA1Notation()); // B1+ * ```+ */+ getNextDataRange(direction: Direction): FRange | null {+ const active = this._selections.find((selection) => !!selection.primary);+ if (!active) {+ return null;+ }++ const range = getNextPrimaryCell(this._selections.concat(), direction, this._worksheet);+ if (range) {+ return this._injector.createInstance(FRange, this._workbook, this._worksheet, range);+ }+ return null;+ }}diff --git a/packages/sheets/src/facade/f-worksheet.ts b/packages/sheets/src/facade/f-worksheet.tsindex a9e37a6219..01a3a2428e 100644--- a/packages/sheets/src/facade/f-worksheet.ts+++ b/packages/sheets/src/facade/f-worksheet.ts@@ -1105,6 +1105,16 @@ export class FWorksheet extends FBase {/*** Returns true if the sheet's gridlines are hidden; otherwise returns false. Gridlines are visible by default.+ * @returns {boolean} True if the sheet's gridlines are hidden; otherwise false.+ * @example+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorkSheet = fWorkbook.getActiveSheet();+ * // check if the gridlines are hidden+ * if (fWorkSheet.hasHiddenGridLines()) {+ * console.log('Gridlines are hidden');+ * }+ * ```*/hasHiddenGridLines(): boolean {return this._worksheet.getConfig().showGridlines === BooleanNumber.FALSE;@@ -1180,6 +1190,14 @@ export class FWorksheet extends FBase {/*** Get the tab color of the sheet.* @returns {string} The tab color of the sheet or undefined.+ * The default color is css style property 'unset'.+ * @example+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorkSheet = fWorkbook.getActiveSheet();+ * // get the tab color of the sheet+ * console.log(fWorkSheet.getTabColor());+ * ```*/getTabColor(): string | undefined {return this._worksheet.getTabColor() as string | undefined;@@ -1189,6 +1207,17 @@ export class FWorksheet extends FBase {* Subscribe to the cell data change event.* @param callback - The callback function to be executed when the cell data changes.* @returns - A disposable object to unsubscribe from the event.+ * @example+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorkSheet = fWorkbook.getActiveSheet();+ * // subscribe to the cell data change event+ * const disposable = fWorkSheet.onCellDataChange((cellValue) => {+ * console.log(cellValue.toArray());+ * });+ * // unsubscribe from the event+ * disposable.dispose();+ * ```*/onCellDataChange(callback: (cellValue: ObjectMatrix<Nullable<ICellData>>) => void): IDisposable {const commandService = this._injector.get(ICommandService);@@ -1210,6 +1239,17 @@ export class FWorksheet extends FBase {* Subscribe to the cell data change event.* @param callback - The callback function to be executed before the cell data changes.* @returns - A disposable object to unsubscribe from the event.+ * @example+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorkSheet = fWorkbook.getActiveSheet();+ * // subscribe to the cell data change event+ * const disposable = fWorkSheet.onBeforeCellDataChange((cellValue) => {+ * console.log(cellValue.toArray());+ * });+ * // unsubscribe from the event+ * disposable.dispose();+ * ```*/onBeforeCellDataChange(callback: (cellValue: ObjectMatrix<Nullable<ICellData>>) => void): IDisposable {const commandService = this._injector.get(ICommandService);@@ -1225,6 +1265,13 @@ export class FWorksheet extends FBase {/*** Hides this sheet. Has no effect if the sheet is already hidden. If this method is called on the only visible sheet, it throws an exception.+ * @example+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorkSheet = fWorkbook.getActiveSheet();+ * // hide the active sheet+ * fWorkSheet.hideSheet();+ * ``*/hideSheet(): void {const commandService = this._injector.get(ICommandService);@@ -1243,6 +1290,14 @@ export class FWorksheet extends FBase {/*** Shows this sheet. Has no effect if the sheet is already visible.+ * @returns {Promise<boolean>} True if the command was successful, false otherwise.+ * @example+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorkSheets = fWorkbook.getSheets();+ * // show the last sheet+ * fWorkSheets[fWorkSheets.length - 1].showSheet();+ * ```*/showSheet(): Promise<boolean> {const commandService = this._injector.get(ICommandService);@@ -1411,8 +1466,17 @@ export class FWorksheet extends FBase {/*** Returns a Range corresponding to the dimensions in which data is present.- * This is functionally equivalent to creating a Range bounded by A1 and (Sheet.getLastColumns(), Sheet.getLastRows()).+ * This is functionally equivalent to creating a Range bounded by A1 and (Sheet.getLastColumns(), Sheet.getLastRows()).* @returns {FRange} The range of the data in the sheet.+ * @example+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorkSheet = fWorkbook.getActiveSheet();+ * // the sheet is a empty sheet+ * const cellRange = fWorkSheet.getRange(200, 10, 1, 1);+ * cellRange.setValue('Hello World');+ * console.log(fWorkSheet.getDataRange().getA1Notation()); // A1:J200+ * ```*/getDataRange(): FRange {const lastRow = this.getLastRows();@@ -1449,4 +1513,23 @@ export class FWorksheet extends FBase {getLastRows(): number {return this._worksheet.getLastRowWithContent();}++ /**+ * Judge whether provided FWorksheet is equal to current.+ * @param {FWorksheet} other the FWorksheet to compare with.+ * @returns {boolean} true if the FWorksheet is equal to the current FWorksheet, false otherwise.+ * @example+ * ```ts+ * const fWorkbook = univerAPI.getActiveWorkbook();+ * const fWorkSheet = fWorkbook.getActiveSheet();+ * const fWorkSheet2 = fWorkbook.getSheetByName('Sheet1');+ * console.log(fWorkSheet.equals(fWorkSheet2)); // true, if the active sheet is 'Sheet1'+ * ```+ */+ equalTo(other: FWorksheet): boolean {+ if (other instanceof FWorksheet) {+ return this._worksheet.getSheetId() === other.getSheetId() && this._workbook.getUnitId() === other.getWorkbook().getUnitId();+ }+ return false;+ }}diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex ec3435d23e..1551a6e922 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -97,6 +97,7 @@ export { AddMergeRedoSelectionsOperationFactory, AddMergeUndoSelectionsOperationexport type { FormatType } from './services/numfmt/type';export { expandToContinuousRange } from './basics/expand-range';+export { getNextPrimaryCell } from './services/selections/move-active-cell-util';export { ExclusiveRangeService, IExclusiveRangeService } from './services/exclusive-range/exclusive-range-service';diff --git a/packages/sheets/src/services/__tests__/move-active-cell.spec.ts b/packages/sheets/src/services/__tests__/move-active-cell.spec.tsnew file mode 100644index 0000000000..5d722c99ef--- /dev/null+++ b/packages/sheets/src/services/__tests__/move-active-cell.spec.ts@@ -0,0 +1,236 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ISelectionWithStyle } from '../../basics';+import { Direction, type Worksheet } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { getNextPrimaryCell } from '../selections/move-active-cell-util';+import { createTestBase } from './util';++describe('Test move active cell', () => {+ let sheet: Worksheet;+ let selections: ISelectionWithStyle[];+ beforeEach(() => {+ const testBed = createTestBase(undefined);+ sheet = testBed.sheet.getActiveSheet()!;+ selections = [+ {+ range: {+ startRow: 0,+ startColumn: 0,+ endRow: 3,+ endColumn: 2,+ rangeType: 0,+ unitId: 'workbook-01',+ sheetId: 'cEJnka85APUJkzGG8SB4w',+ },+ primary: null,+ style: {+ strokeWidth: 1,+ stroke: '#274fee',+ fill: 'rgba(39,79,238,0.07)',+ widgets: {},+ widgetSize: 6,+ widgetStrokeWidth: 1,+ widgetStroke: '#ffffff',+ autofillSize: 6,+ autofillStrokeWidth: 1,+ autofillStroke: '#ffffff',+ rowHeaderFill: 'rgba(39,79,238,0.07)',+ rowHeaderStroke: '#274fee',+ rowHeaderStrokeWidth: 1,+ columnHeaderFill: 'rgba(39,79,238,0.07)',+ columnHeaderStroke: '#274fee',+ columnHeaderStrokeWidth: 1,+ expandCornerSize: 40,+ },+ },+ {+ range: {+ startRow: 4,+ startColumn: 3,+ endRow: 7,+ endColumn: 5,+ rangeType: 0,+ unitId: 'workbook-01',+ sheetId: 'cEJnka85APUJkzGG8SB4w',+ },+ primary: {+ actualRow: 4,+ actualColumn: 3,+ isMerged: false,+ isMergedMainCell: false,+ startRow: 4,+ startColumn: 3,+ endRow: 4,+ endColumn: 3,+ },+ style: {+ strokeWidth: 1,+ stroke: '#274fee',+ fill: 'rgba(39,79,238,0.07)',+ widgets: {},+ widgetSize: 6,+ widgetStrokeWidth: 1,+ widgetStroke: '#ffffff',+ autofillSize: 6,+ autofillStrokeWidth: 1,+ autofillStroke: '#ffffff',+ rowHeaderFill: 'rgba(39,79,238,0.07)',+ rowHeaderStroke: '#274fee',+ rowHeaderStrokeWidth: 1,+ columnHeaderFill: 'rgba(39,79,238,0.07)',+ columnHeaderStroke: '#274fee',+ columnHeaderStrokeWidth: 1,+ expandCornerSize: 40,+ },+ },+ ];+ });+ it('move up', () => {+ const rs = getNextPrimaryCell(selections, Direction.UP, sheet);+ expect(rs).toEqual({+ startRow: 3,+ startColumn: 2,+ endRow: 3,+ endColumn: 2,+ });+ });+ it('move right', () => {+ const rs = getNextPrimaryCell(selections, Direction.RIGHT, sheet);+ expect(rs).toEqual({+ startRow: 4,+ startColumn: 4,+ endRow: 4,+ endColumn: 4,+ });+ });+ it('move down', () => {+ const rs = getNextPrimaryCell(selections, Direction.DOWN, sheet);+ expect(rs).toEqual({+ startRow: 5,+ startColumn: 3,+ endRow: 5,+ endColumn: 3,+ });+ });+ it('move left', () => {+ const rs = getNextPrimaryCell(selections, Direction.LEFT, sheet);+ expect(rs).toEqual({+ startRow: 3,+ startColumn: 2,+ endRow: 3,+ endColumn: 2,+ });+ });+});++describe('Test move active cell with merged cell', () => {+ let sheet: Worksheet;+ let selections: ISelectionWithStyle[];+ beforeEach(() => {+ const testBed = createTestBase(undefined);+ sheet = testBed.sheet.getActiveSheet()!;+ sheet.setMergeData([{+ startRow: 1,+ startColumn: 1,+ endRow: 2,+ endColumn: 2,+ rangeType: 0,+ unitId: 'workbook-01',+ sheetId: 'QzJ-nUESkG_1_4KWI_EUz',+ }]);+ selections = [+ {+ range: {+ startRow: 0,+ startColumn: 0,+ endRow: 3,+ endColumn: 3,+ rangeType: 0,+ unitId: 'workbook-01',+ sheetId: 'QzJ-nUESkG_1_4KWI_EUz',+ },+ primary: {+ actualRow: 1,+ actualColumn: 3,+ isMerged: false,+ isMergedMainCell: true,+ startRow: 1,+ startColumn: 3,+ endRow: 1,+ endColumn: 3,+ },+ style: {+ strokeWidth: 1,+ stroke: '#274fee',+ fill: 'rgba(39,79,238,0.07)',+ widgets: {},+ widgetSize: 6,+ widgetStrokeWidth: 1,+ widgetStroke: '#ffffff',+ autofillSize: 6,+ autofillStrokeWidth: 1,+ autofillStroke: '#ffffff',+ rowHeaderFill: 'rgba(39,79,238,0.07)',+ rowHeaderStroke: '#274fee',+ rowHeaderStrokeWidth: 1,+ columnHeaderFill: 'rgba(39,79,238,0.07)',+ columnHeaderStroke: '#274fee',+ columnHeaderStrokeWidth: 1,+ expandCornerSize: 40,+ },+ },+ ];+ });+ it('move up', () => {+ const rs = getNextPrimaryCell(selections, Direction.UP, sheet);+ expect(rs).toEqual({+ startRow: 0,+ startColumn: 3,+ endRow: 0,+ endColumn: 3,+ });+ });+ it('last cell move right', () => {+ const rs = getNextPrimaryCell(selections, Direction.RIGHT, sheet);+ expect(rs).toEqual({+ startRow: 2,+ startColumn: 0,+ endRow: 2,+ endColumn: 0,+ });+ });+ it('move down', () => {+ const rs = getNextPrimaryCell(selections, Direction.DOWN, sheet);+ expect(rs).toEqual({+ startRow: 2,+ startColumn: 3,+ endRow: 2,+ endColumn: 3,+ });+ });+ it('move left', () => {+ const rs = getNextPrimaryCell(selections, Direction.LEFT, sheet);+ // return the merged cell in B2:C3+ expect(rs).toEqual({+ startRow: 1,+ startColumn: 1,+ endRow: 2,+ endColumn: 2,+ });+ });+});diff --git a/packages/sheets/src/services/selections/move-active-cell-util.ts b/packages/sheets/src/services/selections/move-active-cell-util.tsnew file mode 100644index 0000000000..cbe0cd3fe4--- /dev/null+++ b/packages/sheets/src/services/selections/move-active-cell-util.ts@@ -0,0 +1,212 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IRange, ISelectionCell, Worksheet } from '@univerjs/core';+import type { ISelectionWithStyle } from '../../basics';+import { Direction, Range, RANGE_TYPE, Rectangle } from '@univerjs/core';++const getPrimaryCellUp = (scopeRange: IRange, worksheet: Worksheet, currentPrimary: ISelectionCell, step: number = 1, isFindNext: boolean = true, isGoBack: boolean = true): IRange | undefined => {+ const movedRange = Range.transformRange(scopeRange, worksheet);+ const { startRow, endRow } = movedRange;+ let next = currentPrimary.startRow - step;+ let nextCellMergedInfo = worksheet.getMergedCell(next, currentPrimary.startColumn);+ let isMainCell = !nextCellMergedInfo || (nextCellMergedInfo.startRow === next && nextCellMergedInfo.startColumn === currentPrimary.startColumn);+ while (!worksheet.getRowVisible(next) || !isMainCell) {+ next--;+ nextCellMergedInfo = worksheet.getMergedCell(next, currentPrimary.startColumn);+ isMainCell = !nextCellMergedInfo || (nextCellMergedInfo.startRow === next && nextCellMergedInfo.startColumn === currentPrimary.startColumn);+ }+ if (next >= startRow) {+ return { ...currentPrimary, startRow: next, endRow: next };+ } else if (isGoBack) {+ const newPrimary = { ...currentPrimary, startRow: endRow, endRow };+ // eslint-disable-next-line ts/no-use-before-define+ return getPrimaryCellLeft(scopeRange, worksheet, newPrimary, step, isFindNext, false);+ }+};++const getPrimaryCellDown = (scopeRange: IRange, worksheet: Worksheet, currentPrimary: ISelectionCell, step: number = 1, isFindNext: boolean = true, isGoBack: boolean = true): IRange | undefined => {+ const movedRange = Range.transformRange(scopeRange, worksheet);+ const { startRow, endRow } = movedRange;+ let next = currentPrimary.endRow + step;+ let nextCellMergedInfo = worksheet.getMergedCell(next, currentPrimary.startColumn);+ let isMainCell = !nextCellMergedInfo || (nextCellMergedInfo.startRow === next && nextCellMergedInfo.startColumn === currentPrimary.startColumn);+ while (!worksheet.getRowVisible(next) || !isMainCell) {+ next++;+ nextCellMergedInfo = worksheet.getMergedCell(next, currentPrimary.startColumn);+ isMainCell = !nextCellMergedInfo || (nextCellMergedInfo.startRow === next && nextCellMergedInfo.startColumn === currentPrimary.startColumn);+ }+ if (next <= endRow) {+ return { ...currentPrimary, startRow: next, endRow: next };+ } else if (isGoBack) {+ const newPrimary = { ...currentPrimary, startRow, endRow: startRow };+ // eslint-disable-next-line ts/no-use-before-define+ return getPrimaryCellRight(scopeRange, worksheet, newPrimary, step, isFindNext, false);+ }+};++const getPrimaryCellLeft = (scopeRange: IRange, worksheet: Worksheet, currentPrimary: ISelectionCell, step: number = 1, isFindNext: boolean = true, isGoBack: boolean = true): IRange | undefined => {+ const movedRange = Range.transformRange(scopeRange, worksheet);+ const { startColumn, endColumn } = movedRange;+ let next = currentPrimary.startColumn - step;+ let nextCellMergedInfo = worksheet.getMergedCell(currentPrimary.startRow, next);+ let isMainCell = !nextCellMergedInfo || (nextCellMergedInfo.startRow === currentPrimary.startRow && nextCellMergedInfo.startColumn === next);+ while (!worksheet.getColVisible(next) || !isMainCell) {+ next--;+ nextCellMergedInfo = worksheet.getMergedCell(currentPrimary.startRow, next);+ isMainCell = !nextCellMergedInfo || (nextCellMergedInfo.startRow === currentPrimary.startRow && nextCellMergedInfo.startColumn === next);+ }+ if (next >= startColumn) {+ return { ...currentPrimary, startColumn: next, endColumn: next };+ } else if (isGoBack) {+ const newPrimary = { ...currentPrimary, startColumn: endColumn, endColumn };+ return getPrimaryCellUp(scopeRange, worksheet, newPrimary, step, isFindNext, false);+ }+};++const getPrimaryCellRight = (scopeRange: IRange, worksheet: Worksheet, currentPrimary: ISelectionCell, step: number = 1, isFindNext: boolean = true, isGoBack: boolean = true): IRange | undefined => {+ const movedRange = Range.transformRange(scopeRange, worksheet);+ const { startColumn, endColumn } = movedRange;+ let next = currentPrimary.endColumn + step;+ let nextCellMergedInfo = worksheet.getMergedCell(currentPrimary.startRow, next);+ let isMainCell = !nextCellMergedInfo || (nextCellMergedInfo.startRow === currentPrimary.startRow && nextCellMergedInfo.startColumn === next);+ while (!worksheet.getColVisible(next) || !isMainCell) {+ next++;+ nextCellMergedInfo = worksheet.getMergedCell(currentPrimary.startRow, next);+ isMainCell = !nextCellMergedInfo || (nextCellMergedInfo.startRow === currentPrimary.startRow && nextCellMergedInfo.startColumn === next);+ }+ if (next <= endColumn) {+ return { ...currentPrimary, endColumn: next, startColumn: next };+ } else if (isGoBack) {+ const newPrimary = { ...currentPrimary, startColumn, endColumn: startColumn };+ return getPrimaryCellDown(scopeRange, worksheet, newPrimary, step, isFindNext, false);+ }+};++function getCellAtRowCol(row: number, col: number, worksheet: Worksheet): ISelectionCell {+ let destRange: ISelectionCell | null = null;++ const matrix = worksheet.getMatrixWithMergedCells(row, col, row, col);+ matrix.forValue((row, col, value) => {+ destRange = {+ actualRow: row,+ actualColumn: 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),+ rangeType: RANGE_TYPE.NORMAL,+ };++ return false;+ });++ if (!destRange) {+ return {+ actualColumn: col,+ actualRow: row,+ startRow: row,+ startColumn: col,+ endRow: row,+ endColumn: col,+ isMerged: false,+ isMergedMainCell: false,+ rangeType: RANGE_TYPE.NORMAL,+ };+ }++ return destRange;+}++const getPrimaryCell = (scopeRange: IRange, worksheet: Worksheet, currentPrimary: ISelectionCell, direction: Direction, step: number = 1): IRange | undefined => {+ switch (direction) {+ case Direction.UP:+ return getPrimaryCellUp(scopeRange, worksheet, currentPrimary, step);+ case Direction.DOWN:+ return getPrimaryCellDown(scopeRange, worksheet, currentPrimary, step);+ case Direction.LEFT:+ return getPrimaryCellLeft(scopeRange, worksheet, currentPrimary, step);+ case Direction.RIGHT:+ return getPrimaryCellRight(scopeRange, worksheet, currentPrimary, step);+ }+};++/**+ * Get the next primary cell in the specified direction. If the primary cell not exists in selections, return null.+ * @param selections The current selections.+ * @param {Direction} direction The direction to move the primary cell.The enum value is maybe one of the following: UP(0),RIGHT(1), DOWN(2), LEFT(3).+ * @param {Worksheet} worksheet The worksheet instance.+ * @returns {IRange | null} The next primary cell.+ */+export const getNextPrimaryCell = (selections: ISelectionWithStyle[], direction: Direction, worksheet: Worksheet): IRange | null => {+ let activeSelection;+ let activeIndex = -1;+ let currentPrimary;+ for (let i = 0; i < selections.length; i++) {+ if (selections[i].primary) {+ activeSelection = selections[i];+ activeIndex = i;+ currentPrimary = activeSelection.primary;+ break;+ }+ }++ if (activeIndex === -1) {+ return null;+ }+ const isReverse = direction === Direction.LEFT || direction === Direction.UP;+ // for shift tab or shift enter, the direction should be reversed. so we need find the previous selection.+ const nextIndex = isReverse+ ? (activeIndex - 1 >= 0 ? activeIndex - 1 : selections.length - 1)+ : activeIndex + 1 < selections.length ? activeIndex + 1 : 0;+ const nextSelection = selections[nextIndex];++ if (!activeSelection || !currentPrimary) {+ return null;+ }+ const primary = { ...currentPrimary };+ const { startRow, startColumn, endRow, endColumn } = activeSelection.range;++ const isLastCell = isReverse ? primary.startRow === startRow && primary.startColumn === startColumn : primary.endRow === endRow && primary.endColumn === endColumn;+ const useLeftTopAsDest = isLastCell && isReverse;++ // if the current selection is a single cell, we should not move the primary cell.+ if (!Rectangle.equals(activeSelection.range, primary)) {+ const next = isLastCell ? nextSelection.range : getPrimaryCell(activeSelection.range, worksheet, primary, direction);+ if (!next) {+ return null;+ }+ const destRange = useLeftTopAsDest ? getCellAtRowCol(next.endRow, next.endColumn, worksheet) : getCellAtRowCol(next.startRow, next.startColumn, worksheet);++ return {+ startRow: destRange.startRow,+ startColumn: destRange.startColumn,+ endRow: destRange.endRow,+ endColumn: destRange.endColumn,+ };+ }++ const destRange = useLeftTopAsDest ? getCellAtRowCol(nextSelection.range.endRow, nextSelection.range.endColumn, worksheet) : getCellAtRowCol(nextSelection.range.startRow, nextSelection.range.startColumn, worksheet);+ return {+ startRow: destRange.startRow,+ startColumn: destRange.startColumn,+ endRow: destRange.endRow,+ endColumn: destRange.endColumn,+ };+};+