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(sheets): align formula keyboard selection and navigation (#7828)
wpxp123456261bf5d08cdd
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-left-and-right-arrow.spec.tsx b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-left-and-right-arrow.spec.tsxindex 3182223534..dceea03f73 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-left-and-right-arrow.spec.tsx+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-left-and-right-arrow.spec.tsx@@ -14,21 +14,211 @@* limitations under the License.*/+import type { IWorkbookData, Workbook } from '@univerjs/core';import type { Editor } from '@univerjs/docs-ui';-import { CommandService, ConfigService, ContextService, DesktopLogService, Direction, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR, FOCUSING_SHEET, FOCUSING_UNIVER_EDITOR, ICommandService, IConfigService, IContextService, ILogService, Injector } from '@univerjs/core';-import { DeleteLeftCommand, DeleteRightCommand, IEditorService, MoveCursorOperation, MoveSelectionOperation, UniverDocsUIPlugin } from '@univerjs/docs-ui';-import { IRenderManagerService } from '@univerjs/engine-render';-import { ExpandSelectionCommand, JumpOver, MoveSelectionCommand } from '@univerjs/sheets-ui';-import { IPlatformService, IShortcutService, IUIRuntimeScopeService, KeyCode, RediContext, ShortcutService, UIRuntimeScopeService } from '@univerjs/ui';+import type { MetaKeys } from '@univerjs/ui';+import {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ Direction,+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ EDITOR_ACTIVATED,+ FOCUSING_FX_BAR_EDITOR,+ FOCUSING_SHEET,+ FOCUSING_UNIVER_EDITOR,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LocaleType,+ RANGE_TYPE,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import {+ DeleteLeftCommand,+ DeleteRightCommand,+ EditorService,+ IEditorService,+ MoveCursorOperation,+ MoveSelectionOperation,+ UniverDocsUIPlugin,+} from '@univerjs/docs-ui';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import {+ IRefSelectionsService,+ REF_SELECTIONS_ENABLED,+ SetSelectionsOperation,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import { ExpandSelectionCommand, JumpOver, MoveSelectionCommand, UniverSheetsUIPlugin } from '@univerjs/sheets-ui';+import {+ ComponentManager,+ IconManager,+ IPlatformService,+ IShortcutService,+ IUIRuntimeScopeService,+ KeyCode,+ RediContext,+ ShortcutService,+ UIRuntimeScopeService,+} from '@univerjs/ui';import { act } from 'react';import { createRoot } from 'react-dom/client';import { describe, expect, it, vi } from 'vitest';-import { FormulaSelectingType } from '../use-formula-selection';import { useLeftAndRightArrow } from '../use-left-and-right-arrow';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+interface IEditorKeysProps {+ selectingType: FormulaSelectingType;+ editor: Editor;+ onMoveInEditor?: (keyCode: KeyCode, metaKey?: MetaKeys) => void;+ getRefSelectionCount?: () => number;+}++function EditorKeys({ selectingType, editor, onMoveInEditor, getRefSelectionCount }: IEditorKeysProps) {+ useLeftAndRightArrow(true, selectingType, editor, onMoveInEditor, getRefSelectionCount);+ return null;+}++describe('formula editor reference selection', () => {+ it.each([+ { keyCode: KeyCode.ARROW_UP, reverseKeyCode: KeyCode.ARROW_DOWN, row: 2, column: 3, expandedRow: 1, expandedColumn: 3 },+ { keyCode: KeyCode.ARROW_DOWN, reverseKeyCode: KeyCode.ARROW_UP, row: 4, column: 3, expandedRow: 5, expandedColumn: 3 },+ { keyCode: KeyCode.ARROW_LEFT, reverseKeyCode: KeyCode.ARROW_RIGHT, row: 3, column: 2, expandedRow: 3, expandedColumn: 1 },+ { keyCode: KeyCode.ARROW_RIGHT, reverseKeyCode: KeyCode.ARROW_LEFT, row: 3, column: 4, expandedRow: 3, expandedColumn: 5 },+ ].flatMap((keys) => [3, 6].map((selectionEnd) => ({ ...keys, selectionEnd }))))('anchors Shift+$keyCode references to the edited cell in a selection ending at $selectionEnd', async (keys) => {+ const univer = new Univer({ locale: LocaleType.EN_US });+ const injector = univer.__getInjector();+ const root = createRoot(document.createElement('div'));+ let focusedEditorId = DOCS_NORMAL_EDITOR_UNIT_ID_KEY;+ let sheetsUIPlugin: UniverSheetsUIPlugin | undefined;+ try {+ injector.add([SheetsSelectionsService]);+ injector.add([ComponentManager]);+ injector.add([IconManager]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ sheetsUIPlugin = injector.createInstance(UniverSheetsUIPlugin, {});+ sheetsUIPlugin.onStarting();+ injector.add([DocSelectionManagerService]);+ injector.add([IEditorService, { useClass: EditorService }]);+ vi.spyOn(injector.get(IEditorService), 'getFocusId').mockImplementation(() => focusedEditorId);+ injector.add([IPlatformService, { useValue: { isMac: false, isWindows: true, isLinux: false } }]);+ injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id: 'test',+ name: '',+ appVersion: '1.0.0',+ locale: LocaleType.EN_US,+ sheetOrder: ['sheet1'],+ sheets: { sheet1: { id: 'sheet1', rowCount: 10, columnCount: 10 } },+ styles: {},+ });+ injector.get(IUniverInstanceService).focusUnit(workbook.getUnitId());+ const context = injector.get(IContextService);+ const commands = injector.get(ICommandService);+ [MoveSelectionCommand, ExpandSelectionCommand, SetSelectionsOperation].forEach((command) => {+ commands.registerCommand(command);+ });+ const selections = injector.get(SheetsSelectionsService);+ const refSelections = injector.get(IRefSelectionsService);+ const shortcuts = injector.get(IShortcutService);+ const getRefSelectionCount = () => refSelections.getCurrentSelections().length;++ for (const editorId of [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY]) {+ focusedEditorId = editorId;+ context.setContextValue(REF_SELECTIONS_ENABLED, false);+ await commands.executeCommand(SetSelectionsOperation.id, {+ unitId: workbook.getUnitId(),+ subUnitId: 'sheet1',+ selections: [{+ range: { startRow: 3, endRow: keys.selectionEnd, startColumn: 3, endColumn: keys.selectionEnd, rangeType: RANGE_TYPE.NORMAL },+ primary: {+ startRow: 3,+ endRow: 3,+ startColumn: 3,+ endColumn: 3,+ actualRow: 3,+ actualColumn: 3,+ isMerged: false,+ isMergedMainCell: true,+ },+ style: null,+ }],+ });+ refSelections.clear();+ context.setContextValue(REF_SELECTIONS_ENABLED, true);+ const editor = { getEditorId: () => editorId, docSelectionRenderService: { isFocusing: true } } as unknown as Editor;+ await act(async () => root.render(+ <RediContext.Provider value={{ injector }}>+ <EditorKeys selectingType={FormulaSelectingType.NEED_ADD} editor={editor} getRefSelectionCount={getRefSelectionCount} />+ </RediContext.Provider>+ ));+ const shortcut = shortcuts.dispatch(new KeyboardEvent('keydown', { keyCode: keys.keyCode, shiftKey: true }));+ expect(shortcut).toBeDefined();+ await expect(commands.executeCommand(shortcut!.id, shortcut!.staticParameters)).resolves.toBe(true);+ expect(selections.getCurrentLastSelection()?.range).toMatchObject({+ startRow: 3,+ endRow: keys.selectionEnd,+ startColumn: 3,+ endColumn: keys.selectionEnd,+ });+ expect(refSelections.getCurrentLastSelection()?.range).toMatchObject({+ startRow: Math.min(3, keys.row),+ endRow: Math.max(3, keys.row),+ startColumn: Math.min(3, keys.column),+ endColumn: Math.max(3, keys.column),+ });+ expect(refSelections.getCurrentLastSelection()?.primary).toMatchObject({+ actualRow: 3,+ actualColumn: 3,+ });+ await expect(commands.executeCommand(shortcut!.id, shortcut!.staticParameters)).resolves.toBe(true);+ expect(refSelections.getCurrentLastSelection()?.range).toMatchObject({+ startRow: Math.min(3, keys.expandedRow),+ endRow: Math.max(3, keys.expandedRow),+ startColumn: Math.min(3, keys.expandedColumn),+ endColumn: Math.max(3, keys.expandedColumn),+ });+ expect(refSelections.getCurrentLastSelection()?.primary).toMatchObject({+ actualRow: 3,+ actualColumn: 3,+ });+ const reverseShortcut = shortcuts.dispatch(new KeyboardEvent('keydown', { keyCode: keys.reverseKeyCode, shiftKey: true }));+ expect(reverseShortcut).toBeDefined();+ await expect(commands.executeCommand(reverseShortcut!.id, reverseShortcut!.staticParameters)).resolves.toBe(true);+ await expect(commands.executeCommand(reverseShortcut!.id, reverseShortcut!.staticParameters)).resolves.toBe(true);+ expect(refSelections.getCurrentLastSelection()?.range).toMatchObject({+ startRow: 3,+ endRow: 3,+ startColumn: 3,+ endColumn: 3,+ });+ expect(selections.getCurrentLastSelection()?.range).toMatchObject({+ startRow: 3,+ endRow: keys.selectionEnd,+ startColumn: 3,+ endColumn: keys.selectionEnd,+ });+ }+ } finally {+ await act(async () => root.unmount());+ vi.restoreAllMocks();+ sheetsUIPlugin?.dispose();+ univer.dispose();+ }+ });+});+describe('formula editor text navigation', () => {it.each([{ isMac: true, keyCode: KeyCode.ARROW_LEFT, metaKey: true, direction: Direction.LEFT, granularity: 'line' },@@ -57,27 +247,24 @@ describe('formula editor text navigation', () => {[IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }],[IShortcutService, { useClass: ShortcutService }],[IRenderManagerService, { useValue: {} }],+ [IEditorService, { useValue: { getFocusId: () => DOCS_NORMAL_EDITOR_UNIT_ID_KEY } }],]);const container = document.createElement('div');const root = createRoot(container);const editor = { getEditorId: () => DOCS_NORMAL_EDITOR_UNIT_ID_KEY, docSelectionRenderService: { isFocusing: true } } as unknown as Editor;const onMoveInEditor = vi.fn();let selectingType = FormulaSelectingType.NOT_SELECT;- function EditorKeys() {- useLeftAndRightArrow(true, selectingType, editor, onMoveInEditor);- return null;- }try {const context = injector.get(IContextService);[FOCUSING_SHEET, FOCUSING_UNIVER_EDITOR, EDITOR_ACTIVATED].forEach((key) => context.setContextValue(key, true));const shortcuts = injector.get(IShortcutService);injector.createInstance(UniverDocsUIPlugin, {- override: [[IEditorService, { useValue: { getFocusId: () => DOCS_NORMAL_EDITOR_UNIT_ID_KEY } }]],+ override: [[IEditorService, null]],});const commands = injector.get(ICommandService);const executed = vi.fn();commands.onCommandExecuted(executed);- await act(async () => root.render(<RediContext.Provider value={{ injector }}><EditorKeys /></RediContext.Provider>));+ await act(async () => root.render(<RediContext.Provider value={{ injector }}><EditorKeys selectingType={selectingType} editor={editor} onMoveInEditor={onMoveInEditor} /></RediContext.Provider>));for (const shiftKey of [false, true]) {const shortcut = shortcuts.dispatch(new KeyboardEvent('keydown', { ...keys, shiftKey }));expect(shortcut).toBeDefined();@@ -115,7 +302,7 @@ describe('formula editor text navigation', () => {commands.registerCommand({ ...MoveSelectionCommand, handler: moveReference });commands.registerCommand({ ...ExpandSelectionCommand, handler: expandReference });selectingType = FormulaSelectingType.NEED_ADD;- await act(async () => root.render(<RediContext.Provider value={{ injector }}><EditorKeys /></RediContext.Provider>));+ await act(async () => root.render(<RediContext.Provider value={{ injector }}><EditorKeys selectingType={selectingType} editor={editor} onMoveInEditor={onMoveInEditor} /></RediContext.Provider>));for (const shiftKey of [false, true]) {const shortcut = shortcuts.dispatch(new KeyboardEvent('keydown', {keyCode: KeyCode.ARROW_LEFT,diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-left-and-right-arrow.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-left-and-right-arrow.tsindex 2d05cb544a..511d66a53e 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-left-and-right-arrow.ts+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-left-and-right-arrow.ts@@ -15,13 +15,22 @@*/import type { Editor } from '@univerjs/docs-ui';-import { CommandType, Direction, DisposableCollection, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, FOCUSING_FX_BAR_EDITOR, generateRandomId, ICommandService, IContextService } from '@univerjs/core';+import {+ CommandType,+ Direction,+ DisposableCollection,+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ FOCUSING_FX_BAR_EDITOR,+ generateRandomId,+ ICommandService,+ IContextService,+} from '@univerjs/core';import { IEditorService, MoveCursorOperation, MoveSelectionOperation } from '@univerjs/docs-ui';import { DeviceInputEventType } from '@univerjs/engine-render';import { ExpandSelectionCommand, JumpOver, MoveSelectionCommand } from '@univerjs/sheets-ui';import { IShortcutService, KeyCode, MetaKeys, useDependency } from '@univerjs/ui';import { useEffect, useMemo, useRef } from 'react';-import { FormulaSelectingType } from './use-formula-selection';export function shouldMoveFormulaSelectionFromCurrentSelection(selectingType: FormulaSelectingType, refSelectionCount: number): boolean {@@ -132,9 +141,10 @@ export const useLeftAndRightArrow = (direction = Direction.RIGHT;}if (shouldMoveSelectionRef.current) {+ const refSelectionCount = getRefSelectionCountRef.current?.() ?? 0;const fromCurrentSelection = shouldMoveFormulaSelectionFromCurrentSelection(shouldMoveSelectionRef.current,- getRefSelectionCountRef.current?.() ?? 0+ refSelectionCount);if (metaKey === MetaKeys.CTRL_COMMAND) {return commandService.executeCommand(MoveSelectionCommand.id, {@@ -147,12 +157,14 @@ export const useLeftAndRightArrow = (return commandService.executeCommand(ExpandSelectionCommand.id, {direction,extra: 'formula-editor',+ fromCurrentSelection: refSelectionCount === 0,});} else if (metaKey === (MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT)) {return commandService.executeCommand(ExpandSelectionCommand.id, {direction,jumpOver: JumpOver.moveGap,extra: 'formula-editor',+ fromCurrentSelection: refSelectionCount === 0,});} else {return commandService.executeCommand(MoveSelectionCommand.id, {diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-selection.command.spec.tssimilarity index 82%rename from packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.tsrename to packages/sheets-ui/src/commands/commands/__tests__/set-selection.command.spec.tsindex d3f88d67bd..fcc8da199b 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-selection.command.spec.ts@@ -21,9 +21,20 @@ import type {IMoveSelectionEnterAndTabCommandParams,ISelectAllCommandParams,} from '../set-selection.command';-import { Direction, ICommandService, IUniverInstanceService, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';+import {+ BooleanNumber,+ Direction,+ ICommandService,+ IConfigService,+ IContextService,+ IUniverInstanceService,+ RANGE_TYPE,+ UniverInstanceType,+} from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import {+ IRefSelectionsService,+ REF_SELECTIONS_ENABLED,SetColHiddenCommand,SetColHiddenMutation,SetColVisibleMutation,@@ -37,13 +48,21 @@ import {} from '@univerjs/sheets';import { KeyCode } from '@univerjs/ui';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../../config/config';import { SelectAllService } from '../../../services/select-all/select-all.service';import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';-import { ExpandSelectionCommand, JumpOver, MoveSelectionCommand, MoveSelectionEnterAndTabCommand, SelectAllCommand } from '../set-selection.command';+import {+ ExpandSelectionCommand,+ JumpOver,+ MoveSelectionCommand,+ MoveSelectionEnterAndTabCommand,+ SelectAllCommand,+} from '../set-selection.command';import {createSelectionCommandTestBed,SELECTION_WITH_EMPTY_CELLS_DATA,SELECTION_WITH_MERGED_CELLS_DATA,+ SIMPLE_SELECTION_WORKBOOK_DATA,} from './create-selection-command-test-bed';describe('Test commands used for change selections', () => {@@ -262,6 +281,173 @@ describe('Test commands used for change selections', () => {});});+ describe('Sheet boundary navigation', () => {+ beforeEach(() => {+ prepareSelectionsTestBed();+ commandService.registerCommand(MoveSelectionEnterAndTabCommand);+ });++ const boundaries = [+ { direction: Direction.UP, keycode: KeyCode.ENTER, row: 0, column: 4, wrapRow: 19, wrapColumn: 3 },+ { direction: Direction.DOWN, keycode: KeyCode.ENTER, row: 19, column: 4, wrapRow: 0, wrapColumn: 5 },+ { direction: Direction.LEFT, keycode: KeyCode.TAB, row: 4, column: 0, wrapRow: 3, wrapColumn: 19 },+ { direction: Direction.RIGHT, keycode: KeyCode.TAB, row: 4, column: 19, wrapRow: 5, wrapColumn: 0 },+ ];+ const cases = boundaries.flatMap((boundary) => [undefined, false, true].map((allowWrap) => ({+ ...boundary,+ allowWrap,+ })));++ it.each(cases.flatMap((testCase) => [false, true].map((referenceMode) => ({ ...testCase, referenceMode }))))(+ 'handles arrow $direction at the sheet edge with wrapping=$allowWrap and referenceMode=$referenceMode',+ async ({ direction, row, column, wrapRow, wrapColumn, allowWrap, referenceMode }) => {+ get(IConfigService).setConfig(SHEETS_UI_PLUGIN_CONFIG_KEY, {+ allowArrowKeyWrapOnSheetBoundary: allowWrap,+ });+ select(row, column, row, column, row, column, false, false);+ const normalSelections = selectionManagerService.getCurrentSelections();+ const refSelections = get(IRefSelectionsService);+ if (referenceMode) {+ refSelections.setSelections(normalSelections.concat());+ get(IContextService).setContextValue(REF_SELECTIONS_ENABLED, true);+ }++ await expect(commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {+ direction,+ })).resolves.toBe(allowWrap !== false);++ const selections = referenceMode ? refSelections : selectionManagerService;+ const expectedRow = allowWrap === false ? row : wrapRow;+ const expectedColumn = allowWrap === false ? column : wrapColumn;+ expect(selections.getCurrentLastSelection()?.range).toMatchObject({+ startRow: expectedRow,+ endRow: expectedRow,+ startColumn: expectedColumn,+ endColumn: expectedColumn,+ });+ if (referenceMode) {+ expect(selectionManagerService.getCurrentSelections()).toEqual(normalSelections);+ }+ }+ );++ it.each(cases)(+ 'stops single-cell Enter/Tab in direction $direction regardless of wrapping=$allowWrap',+ async ({ direction, keycode, row, column, allowWrap }) => {+ get(IConfigService).setConfig(SHEETS_UI_PLUGIN_CONFIG_KEY, {+ allowArrowKeyWrapOnSheetBoundary: allowWrap,+ });+ select(row, column, row, column, row, column, false, false);++ await expect(commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(+ MoveSelectionEnterAndTabCommand.id,+ { direction, keycode }+ )).resolves.toBe(false);++ expectSelectionToBe(row, column, row, column);+ }+ );++ it.each([+ { direction: Direction.DOWN, keycode: KeyCode.ENTER, cells: [[1, 0], [0, 1], [1, 1], [0, 0]] },+ { direction: Direction.RIGHT, keycode: KeyCode.TAB, cells: [[0, 1], [1, 0], [1, 1], [0, 0]] },+ { direction: Direction.UP, keycode: KeyCode.ENTER, cells: [[0, 1], [1, 0], [0, 0], [1, 1]] },+ { direction: Direction.LEFT, keycode: KeyCode.TAB, cells: [[1, 0], [0, 1], [0, 0], [1, 1]] },+ ].flatMap((navigation) => [false, true].map((allowWrap) => ({ ...navigation, allowWrap }))))(+ 'cycles Enter/Tab inside a selected range in direction $direction with wrapping=$allowWrap',+ async ({ direction, keycode, cells, allowWrap }) => {+ get(IConfigService).setConfig(SHEETS_UI_PLUGIN_CONFIG_KEY, {+ allowArrowKeyWrapOnSheetBoundary: allowWrap,+ });+ const origin = direction === Direction.UP || direction === Direction.LEFT ? 1 : 0;+ select(origin, origin, origin, origin, origin, origin, false, false);+ const range = { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1, rangeType: RANGE_TYPE.NORMAL };+ selectionManagerService.setSelections([{+ ...selectionManagerService.getCurrentLastSelection()!,+ range,+ }]);++ for (const [row, column] of cells) {+ await expect(commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(+ MoveSelectionEnterAndTabCommand.id,+ { direction, keycode }+ )).resolves.toBe(true);+ expect(selectionManagerService.getCurrentLastSelection()?.range).toEqual(range);+ expect(selectionManagerService.getCurrentLastSelection()?.primary).toMatchObject({+ actualRow: row,+ actualColumn: column,+ });+ }+ }+ );+ });++ describe('Merged and hidden worksheet boundaries', () => {+ it.each([+ { direction: Direction.UP, keycode: KeyCode.ENTER, row: 0, column: 4 },+ { direction: Direction.DOWN, keycode: KeyCode.ENTER, row: 18, column: 4 },+ { direction: Direction.LEFT, keycode: KeyCode.TAB, row: 4, column: 0 },+ { direction: Direction.RIGHT, keycode: KeyCode.TAB, row: 4, column: 18 },+ ])('keeps an edge merged cell selected in direction $direction', async ({ direction, keycode, row, column }) => {+ const mergedRange = { startRow: row, endRow: row + 1, startColumn: column, endColumn: column + 1 };+ prepareSelectionsTestBed({+ ...SIMPLE_SELECTION_WORKBOOK_DATA,+ sheets: {+ sheet1: { ...SIMPLE_SELECTION_WORKBOOK_DATA.sheets.sheet1, mergeData: [mergedRange] },+ },+ });+ commandService.registerCommand(MoveSelectionEnterAndTabCommand);+ get(IConfigService).setConfig(SHEETS_UI_PLUGIN_CONFIG_KEY, { allowArrowKeyWrapOnSheetBoundary: false });+ select(row, column, row + 1, column + 1, row, column, true, true);++ await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, { direction });+ expectSelectionToBe(row, column, row + 1, column + 1);++ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(+ MoveSelectionEnterAndTabCommand.id,+ { direction, keycode }+ );+ expectSelectionToBe(row, column, row + 1, column + 1);+ expect(selectionManagerService.getCurrentLastSelection()?.primary).toMatchObject({+ actualRow: row,+ actualColumn: column,+ });+ });++ it.each([+ { direction: Direction.UP, keycode: KeyCode.ENTER, row: 1, column: 4 },+ { direction: Direction.DOWN, keycode: KeyCode.ENTER, row: 18, column: 4 },+ { direction: Direction.LEFT, keycode: KeyCode.TAB, row: 4, column: 1 },+ { direction: Direction.RIGHT, keycode: KeyCode.TAB, row: 4, column: 18 },+ ])('stops at the last visible cell in direction $direction', async ({ direction, keycode, row, column }) => {+ prepareSelectionsTestBed({+ ...SIMPLE_SELECTION_WORKBOOK_DATA,+ sheets: {+ sheet1: {+ ...SIMPLE_SELECTION_WORKBOOK_DATA.sheets.sheet1,+ rowData: { 0: { hd: BooleanNumber.TRUE }, 19: { hd: BooleanNumber.TRUE } },+ columnData: { 0: { hd: BooleanNumber.TRUE }, 19: { hd: BooleanNumber.TRUE } },+ },+ },+ });+ commandService.registerCommand(MoveSelectionEnterAndTabCommand);+ get(IConfigService).setConfig(SHEETS_UI_PLUGIN_CONFIG_KEY, { allowArrowKeyWrapOnSheetBoundary: false });+ select(row, column, row, column, row, column, false, false);++ await expect(commandService.executeCommand<IMoveSelectionCommandParams>(+ MoveSelectionCommand.id,+ { direction }+ )).resolves.toBe(false);+ expectSelectionToBe(row, column, row, column);++ await expect(commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(+ MoveSelectionEnterAndTabCommand.id,+ { direction, keycode }+ )).resolves.toBe(false);+ expectSelectionToBe(row, column, row, column);+ });+ });+describe('Move cell to/through merged cells', () => {beforeEach(() => prepareSelectionsTestBed(SELECTION_WITH_MERGED_CELLS_DATA));diff --git a/packages/sheets-ui/src/commands/commands/set-selection.command.ts b/packages/sheets-ui/src/commands/commands/set-selection.command.tsindex f681b82952..13ae5df6da 100644--- a/packages/sheets-ui/src/commands/commands/set-selection.command.ts+++ b/packages/sheets-ui/src/commands/commands/set-selection.command.ts@@ -15,11 +15,19 @@*/import type { ICommand, IMutationInfo, IRange } from '@univerjs/core';-import type {- ISetSelectionsOperationParams,-} from '@univerjs/sheets';-import { CommandType, Direction, ICommandService, IUniverInstanceService, RANGE_TYPE, Rectangle, sequenceExecute, Tools } from '@univerjs/core';-+import type { ISetSelectionsOperationParams } from '@univerjs/sheets';+import type { IUniverSheetsUIConfig } from '../../config/config';+import {+ CommandType,+ Direction,+ ICommandService,+ IConfigService,+ IUniverInstanceService,+ RANGE_TYPE,+ Rectangle,+ sequenceExecute,+ Tools,+} from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import {expandToContinuousRange,@@ -31,6 +39,7 @@ import {SheetInterceptorService,} from '@univerjs/sheets';import { KeyCode } from '@univerjs/ui';+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';import { SelectAllService } from '../../services/select-all/select-all.service';import { ISheetSelectionRenderService } from '../../services/selection/base-selection-render.service';import { ShortcutExperienceService } from '../../services/shortcut-experience.service';@@ -76,14 +85,15 @@ export interface IMoveSelectionEnterAndTabCommandParams {export const MoveSelectionCommand: ICommand<IMoveSelectionCommandParams> = {id: 'sheet.command.move-selection',type: CommandType.COMMAND,- // eslint-disable-next-line max-lines-per-functionhandler: (accessor, params) => {if (!params) {return false;}const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));- if (!target) return false;+ if (!target) {+ return false;+ }const { workbook, worksheet } = target;const selection = getSelectionsService(accessor, params.fromCurrentSelection).getCurrentLastSelection();@@ -116,12 +126,14 @@ export const MoveSelectionCommand: ICommand<IMoveSelectionCommandParams> = {}const startRange = getStartRange(range, primary, direction);+ const config = accessor.get(IConfigService).getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);+ const allowWrap = config?.allowArrowKeyWrapOnSheetBoundary ?? true;// the start range is from the primary selection rangeconst next =jumpOver === JumpOver.moveGap? findNextGapRange(startRange, direction, worksheet)- : findNextRange(startRange, direction, worksheet);+ : findNextRange(startRange, direction, worksheet, undefined, true, 1, allowWrap);const destRange = getCellAtRowCol(next.startRow, next.startColumn, worksheet);if (Rectangle.equals(destRange, startRange)) {@@ -171,14 +183,15 @@ export const MoveSelectionCommand: ICommand<IMoveSelectionCommandParams> = {export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTabCommandParams> = {id: 'sheet.command.move-selection-enter-tab',type: CommandType.COMMAND,- // eslint-disable-next-line max-lines-per-function, complexityhandler: (accessor, params) => {if (!params) {return false;}const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));- if (!target) return false;+ if (!target) {+ return false;+ }const { workbook, worksheet } = target;const selectionsService = getSelectionsService(accessor, params.fromCurrentSelection);@@ -293,13 +306,7 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTab});}- /**- * The start range is from the primary selection range.- * If the edited cell is the last row/column of the worksheet, and the submitted operation is Enter/Tab to move down/right, the next selected cell should still be the current cell (not move to the first row/column of the worksheet).- */- const isLastRowCell = keycode === KeyCode.ENTER && direction === Direction.DOWN && startRange.endRow === worksheet.getMaxRows() - 1;- const isLastColumnCell = keycode === KeyCode.TAB && direction === Direction.RIGHT && startRange.endColumn === worksheet.getMaxColumns() - 1;- const next = (isLastRowCell || isLastColumnCell) ? startRange : findNextRange(startRange, direction, worksheet);+ const next = findNextRange(startRange, direction, worksheet, undefined, true, 1, false);const destRange = getCellAtRowCol(next.startRow, next.startColumn, worksheet);if (Rectangle.equals(destRange, startRange)) {@@ -351,6 +358,8 @@ export interface IExpandSelectionCommandParams {jumpOver?: JumpOver;nextStep?: number;extra?: string;+ /** Use the normal selection's primary cell to start a formula reference. */+ fromCurrentSelection?: boolean;}// Though the command's name is "expand-selection", it actually does not expand but shrink the selection.@@ -359,20 +368,37 @@ export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {id: 'sheet.command.expand-selection',type: CommandType.COMMAND,handler: (accessor, params) => {- if (!params) return false;+ if (!params) {+ return false;+ }const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));- if (!target) return false;+ if (!target) {+ return false;+ }const { worksheet, unitId, subUnitId } = target;- const selection = getSelectionsService(accessor).getCurrentLastSelection();- if (!selection) return false;+ const selectionsService = getSelectionsService(accessor, params.fromCurrentSelection);+ const selection = selectionsService.getCurrentLastSelection();+ if (!selection) {+ return false;+ }const { jumpOver, direction, extra } = params;let { range: startRange, primary } = selection;if (extra === 'formula-editor') {+ if (params.fromCurrentSelection && primary) {+ startRange = {+ startRow: primary.startRow,+ endRow: primary.endRow,+ startColumn: primary.startColumn,+ endColumn: primary.endColumn,+ rangeType: RANGE_TYPE.NORMAL,+ };+ }+// When in formula editor, if the current cell is a merged cell, expand the selection to the merged cell range for calculation.if (startRange.startRow === startRange.endRow && startRange.startColumn === startRange.endColumn) {const mergedCell = worksheet.getMergedCell(startRange.startRow, startRange.startColumn);@@ -386,7 +412,7 @@ export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {// When in formula editor, try to use the last primary cell in ref selections as the primary cell for calculation.if (!primary) {- const lastSelectionPrimary = getSelectionsService(accessor).getCurrentLastSelectionPrimaryCell();+ const lastSelectionPrimary = selectionsService.getCurrentLastSelectionPrimaryCell();if (lastSelectionPrimary && Rectangle.contains(startRange, lastSelectionPrimary)) {primary = lastSelectionPrimary;}@@ -394,11 +420,9 @@ export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {}const isShrink = checkIfShrink({ range: startRange, primary }, direction, worksheet);- const destRange = !isShrink- ? jumpOver === JumpOver.moveGap- ? expandToNextGapRange(startRange, direction, worksheet)- : expandToNextCell(startRange, direction, worksheet)- : jumpOver === JumpOver.moveGap+ let destRange: IRange;+ if (isShrink) {+ destRange = jumpOver === JumpOver.moveGap? shrinkToNextGapRange(startRange,{ ...Rectangle.clone(primary), rangeType: RANGE_TYPE.NORMAL },@@ -406,7 +430,12 @@ export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {worksheet): shrinkToNextCell(startRange, direction, worksheet);- destRange.rangeType = selection.range.rangeType;+ } else {+ destRange = jumpOver === JumpOver.moveGap+ ? expandToNextGapRange(startRange, direction, worksheet)+ : expandToNextCell(startRange, direction, worksheet);+ }+ destRange.rangeType = startRange.rangeType;if (Rectangle.equals(destRange, startRange)) {return false;diff --git a/packages/sheets-ui/src/config/config.ts b/packages/sheets-ui/src/config/config.tsindex a1bb96495e..7bcd7981e2 100644--- a/packages/sheets-ui/src/config/config.ts+++ b/packages/sheets-ui/src/config/config.ts@@ -28,6 +28,13 @@ export interface IUniverSheetsUIConfig {disableAutoFocus?: true;override?: DependencyOverride;+ /**+ * Whether arrow keys may wrap to another row or column at worksheet boundaries.+ * Does not affect Enter/Tab cycling within selected ranges.+ * @default true+ */+ allowArrowKeyWrapOnSheetBoundary?: boolean;+/*** The maximum count of rows triggering auto height. This is used to avoid performance issue.* @default 1000@@ -141,6 +148,7 @@ export interface IUniverSheetsUIConfig {}export const defaultPluginConfig: IUniverSheetsUIConfig = {+ allowArrowKeyWrapOnSheetBoundary: true,formulaBar: true,protectedRangeShadow: true,maxAutoHeightCount: 1000,diff --git a/presets/packages/preset-sheets-core/src/preset.ts b/presets/packages/preset-sheets-core/src/preset.tsindex 5b8c2c21b9..8b25704e18 100644--- a/presets/packages/preset-sheets-core/src/preset.ts+++ b/presets/packages/preset-sheets-core/src/preset.ts@@ -141,6 +141,7 @@ export function UniverSheetsCorePreset(config: Partial<IUniverSheetsCorePresetCo[UniverSheetsUIPlugin, {formulaBar,footer,+ allowArrowKeyWrapOnSheetBoundary: sheets?.allowArrowKeyWrapOnSheetBoundary,maxAutoHeightCount: sheets?.maxAutoHeightCount,clipboardConfig: sheets?.clipboardConfig,scrollConfig: sheets?.scrollConfig,diff --git a/presets/packages/preset-sheets-core/src/types.ts b/presets/packages/preset-sheets-core/src/types.tsindex 32127ea701..de6f5d7198 100644--- a/presets/packages/preset-sheets-core/src/types.ts+++ b/presets/packages/preset-sheets-core/src/types.ts@@ -37,5 +37,15 @@ export interface IUniverDocsPresetConfig extendsexport interface IUniverSheetsPresetConfig extendsPick<IUniverSheetsConfig, 'isRowStylePrecedeColumnStyle' | 'autoHeightForMergedCells' | 'freezeSync'>,- Pick<IUniverSheetsUIConfig, 'maxAutoHeightCount' | 'clipboardConfig' | 'scrollConfig' | 'protectedRangeShadow' | 'protectedRangeUserSelector' | 'disableForceStringAlert' | 'disableForceStringMark'> {+ Pick<+ IUniverSheetsUIConfig,+ 'maxAutoHeightCount'+ | 'clipboardConfig'+ | 'scrollConfig'+ | 'protectedRangeShadow'+ | 'protectedRangeUserSelector'+ | 'disableForceStringAlert'+ | 'disableForceStringMark'+ | 'allowArrowKeyWrapOnSheetBoundary'+ > {}