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 keyboard shortcut behavior (#7610)
wpxp123456be27f8551194
diff --git a/packages/sheets-formula-ui/src/controllers/shortcuts/__tests__/formula-shortcuts.spec.ts b/packages/sheets-formula-ui/src/controllers/shortcuts/__tests__/formula-shortcuts.spec.tsindex 15b9af0cbc..b54d02759c 100644--- a/packages/sheets-formula-ui/src/controllers/shortcuts/__tests__/formula-shortcuts.spec.ts+++ b/packages/sheets-formula-ui/src/controllers/shortcuts/__tests__/formula-shortcuts.spec.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { QuickSumCommand } from '@univerjs/sheets-formula';+import type { IInsertFunctionOperationParams } from '../../../commands/operations/insert-function.operation';import { KeyCode, MetaKeys } from '@univerjs/ui';import { describe, expect, it, vi } from 'vitest';import { ReferenceAbsoluteOperation } from '../../../commands/operations/reference-absolute.operation';@@ -44,10 +44,12 @@ describe('formula shortcuts', () => {expect(whenSheetEditorActivatedMock).toHaveBeenCalledWith(contextService);});- it('binds quick sum to platform shortcuts while the sheet editor is focused', async () => {+ it('binds quick sum to SUM insertion while the sheet editor is focused', async () => {+ const { InsertFunctionOperation } = await import('../../../commands/operations/insert-function.operation');const { QuickSumShortcut } = await import('../quick-sum.shortcut');- expect(QuickSumShortcut.id).toBe(QuickSumCommand.id);+ expect(QuickSumShortcut.id).toBe(InsertFunctionOperation.id);+ expect(QuickSumShortcut.staticParameters).toEqual({ value: 'SUM' } satisfies IInsertFunctionOperationParams);expect(QuickSumShortcut.binding).toBe(MetaKeys.ALT | KeyCode.EQUAL);expect(QuickSumShortcut.mac).toBe(MetaKeys.CTRL_COMMAND | MetaKeys.ALT | KeyCode.EQUAL);expect(QuickSumShortcut.preconditions).toBe(whenSheetEditorFocusedMock);diff --git a/packages/sheets-formula-ui/src/controllers/shortcuts/quick-sum.shortcut.ts b/packages/sheets-formula-ui/src/controllers/shortcuts/quick-sum.shortcut.tsindex 0113c6a035..74bb1a14cc 100644--- a/packages/sheets-formula-ui/src/controllers/shortcuts/quick-sum.shortcut.ts+++ b/packages/sheets-formula-ui/src/controllers/shortcuts/quick-sum.shortcut.ts@@ -15,15 +15,17 @@*/import type { IShortcutItem } from '@univerjs/ui';-import { QuickSumCommand } from '@univerjs/sheets-formula';+import type { IInsertFunctionOperationParams } from '../../commands/operations/insert-function.operation';import { whenSheetEditorFocused } from '@univerjs/sheets-ui';import { KeyCode, MetaKeys } from '@univerjs/ui';+import { InsertFunctionOperation } from '../../commands/operations/insert-function.operation';-export const QuickSumShortcut: IShortcutItem = {- id: QuickSumCommand.id,+export const QuickSumShortcut: IShortcutItem<IInsertFunctionOperationParams> = {+ id: InsertFunctionOperation.id,binding: MetaKeys.ALT | KeyCode.EQUAL,preconditions: whenSheetEditorFocused,mac: MetaKeys.CTRL_COMMAND | MetaKeys.ALT | KeyCode.EQUAL,+ staticParameters: { value: 'SUM' },description: 'sheets-formula-ui.shortcut.quick-sum',group: '4_sheet-edit',groupTitle: 'sheets-ui.shortcut.sheet-edit',diff --git a/packages/sheets-formula/src/commands/commands/__tests__/quick-sum.command.spec.ts b/packages/sheets-formula/src/commands/commands/__tests__/quick-sum.command.spec.tsdeleted file mode 100644index dd760fc392..0000000000--- a/packages/sheets-formula/src/commands/commands/__tests__/quick-sum.command.spec.ts+++ /dev/null@@ -1,172 +0,0 @@-/**- * Copyright 2023-present DreamNum Co., Ltd.- *- * 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 { IAccessor, IWorkbookData } from '@univerjs/core';-import { CellValueType, ICommandService, IUniverInstanceService, LocaleType } from '@univerjs/core';-import { SetRangeValuesCommand, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';-import { afterEach, describe, expect, it, vi } from 'vitest';-import { createFacadeTestBed } from '../../../facade/__tests__/create-test-bed';-import { QuickSumCommand } from '../quick-sum.command';--function createWorkbookData(): IWorkbookData {- return {- id: 'test',- appVersion: '3.0.0-alpha',- locale: LocaleType.EN_US,- name: 'test',- sheetOrder: ['sheet1'],- sheets: {- sheet1: {- id: 'sheet1',- name: 'Sheet1',- rowCount: 20,- columnCount: 20,- cellData: {- 0: {- 0: { v: 1, t: CellValueType.NUMBER },- 1: { v: 2, t: CellValueType.NUMBER },- 2: {},- },- 1: {- 0: { v: 3, t: CellValueType.NUMBER },- 1: { v: 4, t: CellValueType.NUMBER },- 2: {},- },- 2: {- 0: {},- 1: {},- 2: {},- },- },- },- },- styles: {},- };-}--describe('QuickSumCommand', () => {- afterEach(() => {- vi.restoreAllMocks();- });-- it('returns false when there is no active selection', async () => {- const testBed = createFacadeTestBed(createWorkbookData());-- const executeCommand = vi.fn();- const accessor = {- get(token: unknown) {- if (token === SheetsSelectionsService) {- return { getCurrentLastSelection: vi.fn(() => null) };- }- if (token === IUniverInstanceService) {- return testBed.injector.get(IUniverInstanceService);- }- if (token === ICommandService) {- return { executeCommand };- }-- throw new Error(`Unknown token: ${String(token)}`);- },- } as unknown as IAccessor;-- await expect(QuickSumCommand.handler?.(accessor)).resolves.toBe(false);- expect(executeCommand).not.toHaveBeenCalled();-- testBed.univer.dispose();- });-- it('writes row and column sum formulas, then resets selection to the computed range', async () => {- const testBed = createFacadeTestBed(createWorkbookData());- const executeCommand = vi.fn(async () => true);- const accessor = {- get(token: unknown) {- if (token === SheetsSelectionsService) {- return {- getCurrentLastSelection: vi.fn(() => ({- range: {- startRow: 0,- startColumn: 0,- endRow: 2,- endColumn: 2,- },- primary: {- startRow: 9,- startColumn: 9,- endRow: 9,- endColumn: 9,- },- })),- };- }- if (token === IUniverInstanceService) {- return testBed.injector.get(IUniverInstanceService);- }- if (token === ICommandService) {- return { executeCommand };- }-- throw new Error(`Unknown token: ${String(token)}`);- },- } as unknown as IAccessor;-- await expect(QuickSumCommand.handler?.(accessor)).resolves.toBe(true);-- expect(executeCommand).toHaveBeenNthCalledWith(1, SetRangeValuesCommand.id, {- range: {- startRow: 0,- startColumn: 0,- endRow: 2,- endColumn: 2,- },- value: {- 0: {- 2: { f: '=SUM(A1:B1)' },- },- 1: {- 2: { f: '=SUM(A2:B2)' },- },- 2: {- 0: { f: '=SUM(A1:A2)' },- 1: { f: '=SUM(B1:B2)' },- 2: { f: '=SUM(A3:B3)' },- },- },- }, undefined);- expect(executeCommand).toHaveBeenNthCalledWith(2, SetSelectionsOperation.id, {- unitId: 'test',- subUnitId: 'sheet1',- selections: [{- range: {- startRow: 0,- startColumn: 0,- endRow: 2,- endColumn: 2,- },- primary: {- startRow: 0,- endRow: 0,- startColumn: 0,- endColumn: 0,- actualRow: 0,- actualColumn: 0,- },- style: null,- }],- }, undefined);-- testBed.univer.dispose();- });-});diff --git a/packages/sheets-formula/src/commands/commands/quick-sum.command.ts b/packages/sheets-formula/src/commands/commands/quick-sum.command.tsdeleted file mode 100644index 1c9cdf940d..0000000000--- a/packages/sheets-formula/src/commands/commands/quick-sum.command.ts+++ /dev/null@@ -1,119 +0,0 @@-/**- * Copyright 2023-present DreamNum Co., Ltd.- *- * 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 { IAccessor, ICellData, ICommand } from '@univerjs/core';-import type { ISetRangeValuesCommandParams, ISetSelectionsOperationParams } from '@univerjs/sheets';-import { CommandType, ICommandService, IUniverInstanceService, ObjectMatrix, Rectangle, sequenceExecuteAsync } from '@univerjs/core';-import { serializeRange } from '@univerjs/engine-formula';-import { alignToMergedCellsBorders, expandToContinuousRange, findFirstNonEmptyCell, getSheetCommandTarget, SetRangeValuesCommand, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';--/**- * Tries to insert =SUM formulas in selection regions.- */-export const QuickSumCommand: ICommand = {- id: 'sheets-formula.command.quick-sum',- type: CommandType.COMMAND,- handler: async (accessor: IAccessor) => {- const selectionsService = accessor.get(SheetsSelectionsService);- const currentSelection = selectionsService.getCurrentLastSelection();- if (!currentSelection) return false;-- const univerInstanceService = accessor.get(IUniverInstanceService);- const target = getSheetCommandTarget(univerInstanceService);- if (!target) return false;-- const range = currentSelection.range;- const { worksheet } = target;- let firstCell = findFirstNonEmptyCell(range, worksheet);- if (!firstCell) return false;-- firstCell = alignToMergedCellsBorders(firstCell, worksheet);- const targetRange = expandToContinuousRange({- startRow: firstCell.startRow,- startColumn: firstCell.startColumn,- endRow: range.endRow,- endColumn: range.endColumn,- }, { left: true, right: true, up: true, down: true }, worksheet);-- const setValueMatrix = new ObjectMatrix<ICellData>();-- const lastRow = alignToMergedCellsBorders({- startRow: targetRange.endRow,- endRow: targetRange.endRow,- startColumn: targetRange.startColumn,- endColumn: targetRange.endColumn,- }, worksheet);- if (!Rectangle.equals(lastRow, targetRange)) {- for (const cell of worksheet.iterateByColumn(lastRow)) {- if (!cell.value || !worksheet.cellHasValue(cell.value)) {- setValueMatrix.setValue(cell.row, cell.col, {- f: `=SUM(${serializeRange({- startColumn: cell.col,- endColumn: cell.col,- startRow: targetRange.startRow,- endRow: cell.row - 1,- })})`,- });- }- }- }-- const lastColumn = alignToMergedCellsBorders({- startRow: targetRange.startRow,- startColumn: targetRange.endColumn,- endRow: targetRange.endRow,- endColumn: targetRange.endColumn,- }, worksheet);- if (!Rectangle.equals(lastColumn, targetRange)) {- for (const cell of worksheet.iterateByRow(lastColumn)) {- if (!cell.value || !worksheet.cellHasValue(cell.value)) {- setValueMatrix.setValue(cell.row, cell.col, {- f: `=SUM(${serializeRange({- startColumn: targetRange.startColumn,- endColumn: cell.col - 1,- startRow: cell.row,- endRow: cell.row,- })})`,- });- }- }- }-- const commandService = accessor.get(ICommandService);-- return (await sequenceExecuteAsync([- {- id: SetRangeValuesCommand.id,- params: {- range: targetRange,- value: setValueMatrix.getMatrix(),- } as ISetRangeValuesCommandParams,- },- {- id: SetSelectionsOperation.id,- params: {- unitId: target.unitId,- subUnitId: target.subUnitId,- selections: [{- range: targetRange,- primary: Rectangle.contains(targetRange, currentSelection.primary) ? currentSelection.primary : { ...firstCell, actualRow: firstCell.startRow, actualColumn: firstCell.startColumn },- style: null,- }],- } as ISetSelectionsOperationParams,- },- ], commandService)).result;- },-};diff --git a/packages/sheets-formula/src/controllers/__tests__/formula.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula.controller.spec.tsindex c65274b029..d370cf0750 100644--- a/packages/sheets-formula/src/controllers/__tests__/formula.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/formula.controller.spec.ts@@ -15,28 +15,21 @@*/import { ICommandService } from '@univerjs/core';-import { afterEach, describe, expect, it } from 'vitest';+import { describe, expect, it } from 'vitest';import { InsertFunctionCommand } from '../../commands/commands/insert-function.command';-import { QuickSumCommand } from '../../commands/commands/quick-sum.command';import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';import { FormulaController } from '../formula.controller';describe('FormulaController', () => {- afterEach(() => {- // each test disposes its own univer instance- });-- it('registers formula-related commands through the real command service', () => {+ it('registers InsertFunctionCommand through the real command service', () => {const testBed = createFacadeTestBed(undefined, [[FormulaController]]);const commandService = testBed.injector.get(ICommandService);expect(commandService.hasCommand(InsertFunctionCommand.id)).toBe(false);- expect(commandService.hasCommand(QuickSumCommand.id)).toBe(false);testBed.injector.get(FormulaController);expect(commandService.hasCommand(InsertFunctionCommand.id)).toBe(true);- expect(commandService.hasCommand(QuickSumCommand.id)).toBe(true);testBed.univer.dispose();});diff --git a/packages/sheets-formula/src/controllers/formula.controller.ts b/packages/sheets-formula/src/controllers/formula.controller.tsindex fcb540e321..9e66a1b94a 100644--- a/packages/sheets-formula/src/controllers/formula.controller.ts+++ b/packages/sheets-formula/src/controllers/formula.controller.ts@@ -16,7 +16,6 @@import { Disposable, ICommandService } from '@univerjs/core';import { InsertFunctionCommand } from '../commands/commands/insert-function.command';-import { QuickSumCommand } from '../commands/commands/quick-sum.command';export class FormulaController extends Disposable {constructor(@@ -24,9 +23,6 @@ export class FormulaController extends Disposable {) {super();- [- InsertFunctionCommand,- QuickSumCommand,- ].forEach((c) => this._commandService.registerCommand(c));+ this._commandService.registerCommand(InsertFunctionCommand);}}diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.tsindex a79102863b..142b345c33 100644--- a/packages/sheets-formula/src/index.ts+++ b/packages/sheets-formula/src/index.ts@@ -16,7 +16,6 @@export { InsertFunctionCommand } from './commands/commands/insert-function.command';export type { IInsertFunction, IInsertFunctionCommandParams } from './commands/commands/insert-function.command';-export { QuickSumCommand } from './commands/commands/quick-sum.command';export { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from './config/config';export type { IUniverSheetsFormulaBaseConfig, IUniverSheetsFormulaRemoteConfig } from './config/config';export { FormulaAutoFillController } from './controllers/formula-auto-fill.controller';diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.tsindex 8484068f46..4bc35ed6dc 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts@@ -34,7 +34,6 @@ import {SetRangeValuesCommand,SetRangeValuesMutation,SetSelectionsOperation,- SetStyleCommand,} from '@univerjs/sheets';import { BehaviorSubject } from 'rxjs';import { beforeEach, describe, expect, it } from 'vitest';@@ -351,49 +350,6 @@ describe('Test format painter rules in controller', () => {});describe('format painter to single cell', () => {- it('marks generated set range values mutations as style updates', async () => {- expect(await commandService.executeCommand(SetSelectionsOperation.id, {- unitId: 'workbook-01',- subUnitId: 'sheet-0011',-- selections: [- {- range: {- startRow: 0,- endRow: 0,- startColumn: 0,- endColumn: 0,- },- },- ],- })).toBeTruthy();-- expect(await commandService.executeCommand(SetOnceFormatPainterCommand.id)).toBeTruthy();-- const setRangeValuesParams: Array<{ trigger?: string }> = [];- const disposable = commandService.onCommandExecuted((command) => {- if (command.id === SetRangeValuesMutation.id) {- setRangeValuesParams.push(command.params as { trigger?: string });- }- });-- expect(await commandService.executeCommand(ApplyFormatPainterCommand.id, {- range: {- startRow: 5,- endRow: 5,- startColumn: 0,- endColumn: 0,- },- unitId: 'workbook-01',- subUnitId: 'sheet-0011',- })).toBeTruthy();-- disposable.dispose();-- expect(setRangeValuesParams.length).toBeGreaterThan(0);- expect(setRangeValuesParams.every((params) => params.trigger === SetStyleCommand.id)).toBe(true);- });-it('will copy whole original styles', async () => {expect(await commandService.executeCommand(SetSelectionsOperation.id, {unitId: 'workbook-01',diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.tsindex c60031d318..42e3bc235e 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts@@ -709,6 +709,44 @@ describe('Test commands used for change selections', () => {commandService.registerCommand(MoveSelectionEnterAndTabCommand);});+ it('should move a single-cell selection left for Shift+Tab', async () => {+ select(1, 1, 1, 1, 1, 1, false, false);++ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {+ direction: Direction.LEFT,+ keycode: KeyCode.TAB,+ });++ expectSelectionToBe(1, 0, 1, 0);+ });++ it('should move down from the current cell after Shift+Tab', async () => {+ select(2, 2, 2, 2, 2, 2, false, false);++ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {+ direction: Direction.LEFT,+ keycode: KeyCode.TAB,+ });+ expectSelectionToBe(2, 1, 2, 1);++ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {+ direction: Direction.DOWN,+ keycode: KeyCode.ENTER,+ });+ expectSelectionToBe(3, 1, 3, 1);+ });++ it('should move a single-cell selection up for Shift+Enter', async () => {+ select(1, 1, 1, 1, 1, 1, false, false);++ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {+ direction: Direction.UP,+ keycode: KeyCode.ENTER,+ });++ expectSelectionToBe(0, 1, 0, 1);+ });+it('should move active cell inside multi-selections and wrap to the next selection', async () => {const refreshSelectionMoveEnd = vi.fn();const renderManagerService = get(IRenderManagerService);diff --git a/packages/sheets-ui/src/commands/commands/set-selection.command.ts b/packages/sheets-ui/src/commands/commands/set-selection.command.tsindex 288b09ba54..c9a13f73f0 100644--- a/packages/sheets-ui/src/commands/commands/set-selection.command.ts+++ b/packages/sheets-ui/src/commands/commands/set-selection.command.ts@@ -192,8 +192,8 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTab}// 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 nextSelectionIndex = (currentSelectionIndex + delta + selections.length) % selections.length;+ const nextSelection = selections[nextSelectionIndex];const unitId = workbook.getUnitId();const sheetId = worksheet.getSheetId();@@ -269,7 +269,7 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTab} else {// Handle the regular situation of moving the selection area.if (keycode === KeyCode.TAB) {- if (shortcutExperienceParam == null) {+ if (direction === Direction.RIGHT && shortcutExperienceParam == null) {shortcutExperienceService.addOrUpdate({unitId,sheetId,diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.tsindex b30bbb1688..a1bdb45417 100644--- a/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts+++ b/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts@@ -16,6 +16,7 @@import type { IDocumentBody } from '@univerjs/core';import {+ Direction,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,DOCS_NORMAL_EDITOR_UNIT_ID_KEY,EDITOR_ACTIVATED,@@ -331,6 +332,27 @@ describe('EditingRenderController business methods', () => {}));});+ it.each([+ ['Enter', KeyCode.ENTER, Direction.UP],+ ['Tab', KeyCode.TAB, Direction.LEFT],+ ])('moves the sheet selection in reverse after finishing edit with Shift+%s', async (_name, keycode, direction) => {+ const { controller } = createController();+ controller._editorBridgeService.getEditorDirty.mockReturnValue(false);++ await controller._handleEditorInvisible({+ visible: false,+ eventType: DeviceInputEventType.Keyboard,+ unitId: 'unit-1',+ keycode,+ isShift: true,+ });++ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionEnterAndTabCommand.id, {+ keycode,+ direction,+ });+ });+it('moves the cursor inside the editor and resets editor state on exit', () => {const { controller, formulaBarEditor } = createController();diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.tsindex b9d24b3301..de63510b51 100644--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts@@ -689,7 +689,7 @@ export class EditingRenderController extends Disposable {const editCellState = this._editorBridgeService.getEditCellState();const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);const snapshot = Tools.deepClone(documentDataModel?.getSnapshot());- const { keycode } = param;+ const { keycode, isShift } = param;const shouldSubmitEmptyCellImageEdit = this._submitEmptyCellImageEdit;this._submitEmptyCellImageEdit = false;this._cursorChange = CursorChange.InitialState;@@ -740,7 +740,7 @@ export class EditingRenderController extends Disposable {// moveSelection need to put behind of SetRangeValuesCommand, fix https://github.com/dream-num/univer/issues/1155if (keycode !== undefined) {- this._moveSelection(keycode, currentUnitId, worksheetId);+ this._moveSelection(keycode, currentUnitId, worksheetId, isShift);}}@@ -888,7 +888,7 @@ export class EditingRenderController extends Disposable {this._docStateChangeManagerService.clearHistory(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);}- private _moveSelection(keycode: KeyCode | undefined, currentUnitId: string, worksheetId: string) {+ private _moveSelection(keycode: KeyCode | undefined, currentUnitId: string, worksheetId: string, isShift = false) {if (keycode == null || !MOVE_SELECTION_KEYCODE_LIST.includes(keycode)) {this._refreshCurrentSelections(worksheetId);return;@@ -898,10 +898,10 @@ export class EditingRenderController extends Disposable {switch (keycode) {case KeyCode.ENTER:- direction = Direction.DOWN;+ direction = isShift ? Direction.UP : Direction.DOWN;break;case KeyCode.TAB:- direction = Direction.RIGHT;+ direction = isShift ? Direction.LEFT : Direction.RIGHT;break;case KeyCode.ARROW_DOWN:direction = Direction.DOWN;diff --git a/packages/sheets-ui/src/controllers/shortcuts/__tests__/editor.shortcut.spec.ts b/packages/sheets-ui/src/controllers/shortcuts/__tests__/editor.shortcut.spec.tsnew file mode 100644index 0000000000..9cac6dd433--- /dev/null+++ b/packages/sheets-ui/src/controllers/shortcuts/__tests__/editor.shortcut.spec.ts@@ -0,0 +1,37 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { DeviceInputEventType } from '@univerjs/engine-render';+import { KeyCode, MetaKeys } from '@univerjs/ui';+import { describe, expect, it } from 'vitest';+import { EditorCursorShiftEnterShortcut, EditorCursorShiftTabShortcut } from '../editor.shortcut';++describe('editor shortcuts', () => {+ it.each([+ ['Shift+Enter', EditorCursorShiftEnterShortcut, KeyCode.ENTER],+ ['Shift+Tab', EditorCursorShiftTabShortcut, KeyCode.TAB],+ ])('closes the editor with the reverse %s binding', (_name, shortcut, keycode) => {+ expect(shortcut).toMatchObject({+ binding: keycode | MetaKeys.SHIFT,+ staticParameters: {+ visible: false,+ eventType: DeviceInputEventType.Keyboard,+ keycode,+ isShift: true,+ },+ });+ });+});diff --git a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.tsindex 1f8638bf56..d2ecbfc684 100644--- a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts+++ b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts@@ -110,6 +110,18 @@ export const EditorCursorEnterShortcut: IShortcutItem = {},};+export const EditorCursorShiftEnterShortcut: IShortcutItem = {+ id: SetCellEditVisibleOperation.id,+ binding: KeyCode.ENTER | MetaKeys.SHIFT,+ preconditions: (contextService) => whenEditorDidNotInputFormulaActivated(contextService),+ staticParameters: {+ visible: false,+ eventType: DeviceInputEventType.Keyboard,+ keycode: KeyCode.ENTER,+ isShift: true,+ },+};+export const EditorCursorTabShortcut: IShortcutItem = {id: SetCellEditVisibleOperation.id,binding: KeyCode.TAB,@@ -121,6 +133,18 @@ export const EditorCursorTabShortcut: IShortcutItem = {},};+export const EditorCursorShiftTabShortcut: IShortcutItem = {+ id: SetCellEditVisibleOperation.id,+ binding: KeyCode.TAB | MetaKeys.SHIFT,+ preconditions: (contextService) => whenEditorDidNotInputFormulaActivated(contextService),+ staticParameters: {+ visible: false,+ eventType: DeviceInputEventType.Keyboard,+ keycode: KeyCode.TAB,+ isShift: true,+ },+};+export const EditorCursorEscShortcut: IShortcutItem = {id: SetCellEditVisibleOperation.id,binding: KeyCode.ESC,diff --git a/packages/sheets-ui/src/controllers/ui.controller.ts b/packages/sheets-ui/src/controllers/ui.controller.tsindex 9dfd68c828..de685ddd8a 100644--- a/packages/sheets-ui/src/controllers/ui.controller.ts+++ b/packages/sheets-ui/src/controllers/ui.controller.ts@@ -105,6 +105,8 @@ import {EditorCursorCtrlEnterShortcut,EditorCursorEnterShortcut,EditorCursorEscShortcut,+ EditorCursorShiftEnterShortcut,+ EditorCursorShiftTabShortcut,EditorCursorTabShortcut,EditorDeleteLeftShortcut,EditorDeleteLeftShortcutInActive,@@ -313,9 +315,11 @@ export class SheetUIController extends Disposable {ShiftDeleteSelectionValueShortcutItem,...generateArrowSelectionShortCutItem(),EditorCursorEnterShortcut,+ EditorCursorShiftEnterShortcut,RepeatLastActionShortcut,StartEditWithF2Shortcut,EditorCursorTabShortcut,+ EditorCursorShiftTabShortcut,EditorBreakLineShortcut,EditorDeleteLeftShortcut,EditorDeleteRightShortcut,diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.tsindex e3e953ec79..0395eba8a3 100644--- a/packages/sheets-ui/src/services/editor-bridge.service.ts+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts@@ -55,6 +55,7 @@ export interface IEditorBridgeServiceVisibleParam {eventType: DeviceInputEventType;unitId: string;keycode?: KeyCode;+ isShift?: boolean;initialValue?: string;}diff --git a/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx b/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsxindex fdb89b9804..9876e70607 100644--- a/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx+++ b/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx@@ -20,7 +20,7 @@ import { borderClassName, clsx, DropdownMenu } from '@univerjs/design';import { convertTransformToOffsetX, convertTransformToOffsetY, IRenderManagerService } from '@univerjs/engine-render';import { AutofillDoubleIcon, MoreDownIcon } from '@univerjs/icons';import { AUTO_FILL_APPLY_TYPE, IAutoFillService, RefillCommand } from '@univerjs/sheets';-import { useDependency, useObservable } from '@univerjs/ui';+import { ILayoutService, useDependency, useObservable } from '@univerjs/ui';import { useEffect, useMemo, useReducer, useState } from 'react';import { map } from 'rxjs';import { SetScrollOperation } from '../../commands/operations/scroll.operation';@@ -46,6 +46,7 @@ export function AutoFillPopupMenu() {const univerInstanceService = useDependency(IUniverInstanceService);const renderManagerService = useDependency(IRenderManagerService);const autoFillService = useDependency(IAutoFillService);+ const layoutService = useDependency(ILayoutService);const localeService = useDependency(LocaleService);const menu = useObservable(() => autoFillService.menu$.pipe(map((items) => items.map((item) => ({@@ -153,7 +154,6 @@ export function AutoFillPopupMenu() {const handleClick = (item: IAutoFillPopupMenuItem) => {commandService.executeCommand(RefillCommand.id, { type: item.value });- setVisible(false);};const showMore = visible || isHovered;@@ -170,6 +170,10 @@ export function AutoFillPopupMenu() {><DropdownMenualign="start"+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ layoutService.focus();+ }}items={availableMenu.map((item) => ({type: 'radio',value: selected,diff --git a/packages/sheets-ui/src/views/auto-fill-popup-menu/__tests__/AutoFillPopupMenu.spec.tsx b/packages/sheets-ui/src/views/auto-fill-popup-menu/__tests__/AutoFillPopupMenu.spec.tsxindex 19859b7c92..9b8cb2b370 100644--- a/packages/sheets-ui/src/views/auto-fill-popup-menu/__tests__/AutoFillPopupMenu.spec.tsx+++ b/packages/sheets-ui/src/views/auto-fill-popup-menu/__tests__/AutoFillPopupMenu.spec.tsx@@ -27,7 +27,7 @@ import {} from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import { AUTO_FILL_APPLY_TYPE, IAutoFillService, RefillCommand } from '@univerjs/sheets';-import { RediContext } from '@univerjs/ui';+import { ILayoutService, RediContext } from '@univerjs/ui';import { act } from 'react';import { createRoot } from 'react-dom/client';import { BehaviorSubject } from 'rxjs';@@ -119,6 +119,16 @@ class TestRenderManagerService {}}+class TestLayoutService {+ focusCount = 0;+ menuOpenWhenFocused = false;++ focus(): void {+ this.focusCount += 1;+ this.menuOpenWhenFocused = document.querySelector('[role="menu"][data-state="open"]') !== null;+ }+}+function createWorkbookData(): IWorkbookData {return {id: UNIT_ID,@@ -143,6 +153,7 @@ function createAutoFillPopupTestBed() {injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);injector.add([IAutoFillService, { useClass: TestAutoFillService as never }]);+ injector.add([ILayoutService, { useClass: TestLayoutService as never }]);const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());injector.get(IUniverInstanceService).focusUnit(UNIT_ID);@@ -173,7 +184,7 @@ async function clickElement(element: HTMLElement): Promise<void> {await act(async () => {element.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));element.dispatchEvent(new MouseEvent('click', { bubbles: true }));- await Promise.resolve();+ await new Promise((resolve) => setTimeout(resolve, 0));});}@@ -232,6 +243,30 @@ describe('AutoFillPopupMenu', () => {expect(autoFillService.refillTypes).toEqual([AUTO_FILL_APPLY_TYPE.COPY]);});+ it('restores focus after selecting an auto fill option', async () => {+ currentBed = createAutoFillPopupTestBed();+ const autoFillService = currentBed.injector.get(IAutoFillService) as unknown as TestAutoFillService;+ const layoutService = currentBed.injector.get(ILayoutService) as unknown as TestLayoutService;+ const rendered = renderWithDependencies(<AutoFillPopupMenu />, currentBed.injector);+ root = rendered.root;+ container = rendered.container;++ act(() => {+ autoFillService.setShowMenu(true);+ });++ const trigger = rendered.container.querySelector('[data-slot="dropdown-menu-trigger"]');+ if (!(trigger instanceof HTMLElement)) {+ throw new TypeError('Auto fill menu trigger not found');+ }++ await clickElement(trigger);+ await clickElement(getByText('sheets.autoFill.copy'));++ await expect.poll(() => layoutService.focusCount).toBe(1);+ expect(layoutService.menuOpenWhenFocused).toBe(false);+ });+it('keeps the overlay origin on the physical left edge in rtl', () => {currentBed = createAutoFillPopupTestBed();currentBed.injector.get(LocaleService).setDirection('rtl');