Skip to content

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.

fix(sheets): restore cell editor keyboard shortcuts (#7790)

白熱1dd554db2ea4
diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts
index 59d977b490..4ee023278d 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts
@@ -21,13 +21,18 @@ import {
HorizontalAlign,
ICommandService,
IUniverInstanceService,
+ RANGE_DIRECTION,
+ RedoCommand,
+ UndoCommand,
Univer,
UniverInstanceType,
} from '@univerjs/core';
import {
+ DeleteTextCommand,
DocLayoutExecutorService,
DocSelectionManagerService,
DocSkeletonManagerService,
+ DocStateChangeManagerService,
DocStateEmitService,
RichTextEditingMutation,
UpdateTextCommand,
@@ -38,7 +43,11 @@ import {
RenderManagerService,
} from '@univerjs/engine-render';
import { describe, expect, it } from 'vitest';
+
+import { DocMoveCursorController } from '../../../controllers/doc-move-cursor.controller';
import { EditorService, IEditorService } from '../../../services/editor/editor-manager.service';
+import { MoveSelectionOperation } from '../../operations/doc-cursor.operation';
+import { CutContentCommand } from '../clipboard.inner.command';
import { DeleteLeftCommand, DeleteRightCommand, MergeTwoParagraphCommand } from '../doc-delete.command';
describe('empty editor deletion', () => {
@@ -134,3 +143,73 @@ describe('MergeTwoParagraphCommand segment selection', () => {
}
});
});
+
+describe('boundary deletion', () => {
+ it.each([
+ { command: DeleteLeftCommand, granularity: 'word', start: 16, end: 16, expected: 'alpha beta \rdelta epsilon zeta\r\n' },
+ { command: DeleteLeftCommand, granularity: 'line', start: 16, end: 16, expected: '\rdelta epsilon zeta\r\n' },
+ { command: DeleteRightCommand, granularity: 'word', start: 6, end: 6, expected: 'alpha gamma\rdelta epsilon zeta\r\n' },
+ { command: DeleteRightCommand, granularity: 'line', start: 6, end: 6, expected: 'alpha \rdelta epsilon zeta\r\n' },
+ { command: DeleteLeftCommand, granularity: 'line', start: 0, end: 0, expected: 'alpha beta gamma\rdelta epsilon zeta\r\n' },
+ { command: DeleteRightCommand, granularity: 'line', start: 16, end: 16, expected: 'alpha beta gamma\rdelta epsilon zeta\r\n' },
+ { command: DeleteLeftCommand, granularity: 'word', start: 2, end: 8, expected: 'alta gamma\rdelta epsilon zeta\r\n' },
+ ])('$command.id at $start:$end deletes by $granularity', async ({ command, granularity, start, end, expected }) => {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ let skeletonManager: DocSkeletonManagerService | undefined;
+ injector.add([IRenderManagerService, { useValue: {
+ getRenderUnitById: () => ({
+ components: new Map(),
+ with: (token: unknown) => token === DocSkeletonManagerService ? skeletonManager : undefined,
+ }),
+ } as unknown as IRenderManagerService }]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([DocStateEmitService]);
+ injector.add([DocStateChangeManagerService]);
+ injector.add([DocLayoutExecutorService]);
+ injector.add([DocMoveCursorController]);
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'boundary-editor',
+ documentStyle: { pageSize: { width: 600, height: 400 } },
+ body: {
+ dataStream: 'alpha beta gamma\rdelta epsilon zeta\r\n',
+ paragraphs: [{ startIndex: 16, paragraphId: 'first' }, { startIndex: 35, paragraphId: 'second' }],
+ },
+ });
+ try {
+ injector.get(IUniverInstanceService).focusUnit(model.getUnitId());
+ skeletonManager = injector.createInstance(DocSkeletonManagerService, { unit: model, unitId: model.getUnitId(), type: UniverInstanceType.UNIVER_DOC });
+ const commands = injector.get(ICommandService);
+ [command, MoveSelectionOperation, CutContentCommand, DeleteTextCommand, MergeTwoParagraphCommand, RichTextEditingMutation].forEach((entry) => commands.registerCommand(entry));
+ injector.get(DocMoveCursorController);
+ injector.get(DocStateChangeManagerService);
+ const selections = injector.get(DocSelectionManagerService);
+ selections.__TEST_ONLY_setCurrentSelection({ unitId: model.getUnitId(), subUnitId: model.getUnitId() });
+ // The headless render boundary records ranges produced by the real cursor controller.
+ const refresh = selections.refreshSelection$.subscribe((value) => {
+ if (!value) return;
+ selections.replaceSelectionInfoWithoutRefresh({ textRanges: value.docRanges.map((range) => ({
+ startOffset: Math.min(range.startOffset!, range.endOffset!),
+ endOffset: Math.max(range.startOffset!, range.endOffset!),
+ collapsed: range.startOffset === range.endOffset,
+ direction: range.startOffset! <= range.endOffset! ? RANGE_DIRECTION.FORWARD : RANGE_DIRECTION.BACKWARD,
+ isActive: true,
+ })), rectRanges: [], segmentId: '', segmentPage: -1, isEditing: true, style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE });
+ });
+ selections.__TEST_ONLY_add([{ startOffset: start, endOffset: end, collapsed: start === end, isActive: true }]);
+ const before = model.getBody()!.dataStream;
+ await commands.executeCommand(command.id, { granularity });
+ expect(model.getBody()!.dataStream).toBe(expected);
+ if (expected !== before) {
+ await commands.executeCommand(UndoCommand.id);
+ expect(model.getBody()!.dataStream).toBe(before);
+ await commands.executeCommand(RedoCommand.id);
+ expect(model.getBody()!.dataStream).toBe(expected);
+ }
+ refresh.unsubscribe();
+ } finally {
+ skeletonManager?.dispose();
+ univer.dispose();
+ }
+ });
+});
diff --git a/packages/docs-ui/src/commands/commands/doc-delete.command.ts b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
index 18bf000205..9c6f7a1203 100644
--- a/packages/docs-ui/src/commands/commands/doc-delete.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
@@ -40,6 +40,7 @@ import {
CommandType,
DataStreamTreeTokenType,
DeleteDirection,
+ Direction,
getBlockRangeInterval,
getParagraphContentStartOffset,
getRichTextEditPath,
@@ -64,10 +65,12 @@ import {
UpdateTextCommand,
} from '@univerjs/docs';
import { getParagraphByGlyph, hasListGlyph, isFirstGlyph, isIndentByGlyph } from '@univerjs/engine-render';
+
import { DocAutoFormatService } from '../../services/doc-auto-format.service';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
import { IEditorService } from '../../services/editor/editor-manager.service';
import { isHorizontalLineParagraph } from '../../utils/horizontal-line';
+import { MoveSelectionOperation } from '../operations/doc-cursor.operation';
import { getCommandSkeleton } from '../util';
import { CutContentCommand } from './clipboard.inner.command';
import { captureTextFormat } from './format-painter.command';
@@ -169,7 +172,6 @@ interface IMergeTwoParagraphParams {
export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
id: 'doc.command.merge-two-paragraph',
type: CommandType.COMMAND,
- // eslint-disable-next-line max-lines-per-function
handler: async (accessor, params: IMergeTwoParagraphParams) => {
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -292,7 +294,6 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
export const RemoveHorizontalLineCommand: ICommand = {
id: 'doc.command.remove-horizontal-line',
type: CommandType.COMMAND,
- // eslint-disable-next-line max-lines-per-function
handler: async (accessor) => {
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -441,13 +442,30 @@ export function isDeleteOffsetInsideBlockRange(body: IDocumentBody, offset: numb
}) ?? false;
}
+export interface IDeleteBoundaryParams {
+ granularity?: 'word' | 'line';
+}
+
+function selectDeleteBoundary(accessor: IAccessor, direction: Direction, granularity: 'word' | 'line'): boolean {
+ const selections = accessor.get(DocSelectionManagerService);
+ if (selections.getActiveTextRange()?.collapsed && !selections.getRectRanges()?.length) {
+ accessor.get(ICommandService).syncExecuteCommand(MoveSelectionOperation.id, { direction, granularity });
+ return selections.getActiveTextRange()?.collapsed === false;
+ }
+
+ return true;
+}
+
// Handle BACKSPACE key.
-export const DeleteLeftCommand: ICommand = {
+export const DeleteLeftCommand: ICommand<IDeleteBoundaryParams> = {
id: 'doc.command.delete-left',
type: CommandType.COMMAND,
- // eslint-disable-next-line max-lines-per-function, complexity
- handler: async (accessor) => {
+ handler: async (accessor, params) => {
+ if (params?.granularity && !selectDeleteBoundary(accessor, Direction.LEFT, params.granularity)) {
+ return true;
+ }
+
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
@@ -682,12 +700,15 @@ export const DeleteLeftCommand: ICommand = {
};
// handle Delete key
-export const DeleteRightCommand: ICommand = {
+export const DeleteRightCommand: ICommand<IDeleteBoundaryParams> = {
id: 'doc.command.delete-right',
type: CommandType.COMMAND,
- // eslint-disable-next-line max-lines-per-function, complexity
- handler: async (accessor) => {
+ handler: async (accessor, params) => {
+ if (params?.granularity && !selectDeleteBoundary(accessor, Direction.RIGHT, params.granularity)) {
+ return true;
+ }
+
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 35d9ecd7d1..d5fe8378e6 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -37,6 +37,7 @@ import {
} from '@univerjs/docs';
import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
import { IShortcutService } from '@univerjs/ui';
+
import pkg from '../package.json';
import { AfterSpaceCommand, EnterCommand, TabCommand } from './commands/commands/auto-format.command';
import { BreakLineCommand } from './commands/commands/break-line.command';
@@ -213,7 +214,11 @@ import {
BreakLineShortcut,
CloseHeaderFooterShortcut,
DeleteLeftShortcut,
+ DeleteLineEndShortcut,
+ DeleteLineStartShortcut,
DeleteRightShortcut,
+ DeleteWordLeftShortcut,
+ DeleteWordRightShortcut,
SoftBreakLineShortcut,
} from './shortcuts/core-editing.shortcut';
import {
@@ -311,7 +316,6 @@ export class UniverDocsUIPlugin extends Plugin {
]);
}
- // eslint-disable-next-line max-lines-per-function
private _initCommand() {
[
DeleteLeftCommand,
@@ -441,6 +445,10 @@ export class UniverDocsUIPlugin extends Plugin {
MoveSelectionWordRightShortcut,
SelectAllShortcut,
DeleteLeftShortcut,
+ DeleteWordLeftShortcut,
+ DeleteWordRightShortcut,
+ DeleteLineStartShortcut,
+ DeleteLineEndShortcut,
DeleteRightShortcut,
CloseHeaderFooterShortcut,
BreakLineShortcut,
diff --git a/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts b/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts
index a578a72a12..dc59af4629 100644
--- a/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts
+++ b/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts
@@ -16,11 +16,12 @@
import type { IShortcutItem } from '@univerjs/ui';
import { KeyCode, MetaKeys } from '@univerjs/ui';
+
import { EnterCommand } from '../commands/commands/auto-format.command';
import { BreakLineCommand } from '../commands/commands/break-line.command';
import { DeleteLeftCommand, DeleteRightCommand } from '../commands/commands/doc-delete.command';
import { CloseHeaderFooterCommand } from '../commands/commands/doc-header-footer.command';
-import { whenDocAndEditorFocused, whenDocAndEditorFocusedWithBreakLine } from './utils';
+import { whenDocAndEditorFocused, whenDocAndEditorFocusedWithBreakLine, whenTextEditorFocused } from './utils';
export const BreakLineShortcut: IShortcutItem = {
id: EnterCommand.id,
@@ -52,14 +53,32 @@ export const CloseHeaderFooterShortcut: IShortcutItem = {
binding: KeyCode.ESC,
};
-// export const TabShortcut: IShortcutItem = {
-// id: DocTabCommand.id,
-// preconditions: whenDocAndEditorFocused,
-// binding: KeyCode.TAB,
-// };
+export const DeleteWordLeftShortcut: IShortcutItem = {
+ id: DeleteLeftCommand.id,
+ preconditions: whenTextEditorFocused,
+ binding: KeyCode.BACKSPACE | MetaKeys.CTRL_COMMAND,
+ mac: KeyCode.BACKSPACE | MetaKeys.ALT,
+ staticParameters: { granularity: 'word' },
+};
+
+export const DeleteWordRightShortcut: IShortcutItem = {
+ id: DeleteRightCommand.id,
+ preconditions: whenTextEditorFocused,
+ mac: KeyCode.DELETE | MetaKeys.ALT,
+ staticParameters: { granularity: 'word' },
+};
-// export const ShiftTabShortcut: IShortcutItem = {
-// id: DocShiftTabCommand.id,
-// preconditions: whenDocAndEditorFocused,
-// binding: KeyCode.TAB | MetaKeys.SHIFT,
-// };
+export const DeleteLineStartShortcut: IShortcutItem = {
+ id: DeleteLeftCommand.id,
+ preconditions: whenTextEditorFocused,
+ mac: KeyCode.BACKSPACE | MetaKeys.CTRL_COMMAND,
+ staticParameters: { granularity: 'line' },
+};
+
+export const DeleteLineEndShortcut: IShortcutItem = {
+ id: DeleteRightCommand.id,
+ preconditions: whenTextEditorFocused,
+ binding: KeyCode.DELETE | MetaKeys.CTRL_COMMAND,
+ mac: KeyCode.DELETE | MetaKeys.MAC_CTRL,
+ staticParameters: { granularity: 'line' },
+};
diff --git a/packages/docs-ui/src/shortcuts/cursor.shortcut.ts b/packages/docs-ui/src/shortcuts/cursor.shortcut.ts
index 98e84bceb5..3e309fb1c9 100644
--- a/packages/docs-ui/src/shortcuts/cursor.shortcut.ts
+++ b/packages/docs-ui/src/shortcuts/cursor.shortcut.ts
@@ -17,9 +17,10 @@
import type { IShortcutItem } from '@univerjs/ui';
import { Direction, EDITOR_ACTIVATED, FOCUSING_DOC, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';
import { KeyCode, MetaKeys } from '@univerjs/ui';
+
import { DocSelectAllCommand } from '../commands/commands/doc-select-all.command';
import { MoveCursorOperation, MoveSelectionOperation } from '../commands/operations/doc-cursor.operation';
-import { whenDocAndEditorFocused } from './utils';
+import { whenDocAndEditorFocused, whenTextEditorFocused } from './utils';
function moveCursorShortcut(
direction: Direction,
@@ -35,7 +36,7 @@ function moveCursorShortcut(
mac,
win,
linux,
- preconditions: whenDocAndEditorFocused,
+ preconditions: whenTextEditorFocused,
staticParameters: {
direction,
granularity,
@@ -57,7 +58,7 @@ function moveSelectionShortcut(
mac,
win,
linux,
- preconditions: whenDocAndEditorFocused,
+ preconditions: whenTextEditorFocused,
staticParameters: {
direction,
granularity,
diff --git a/packages/docs-ui/src/shortcuts/utils.ts b/packages/docs-ui/src/shortcuts/utils.ts
index c924ff0756..95aa33d91b 100644
--- a/packages/docs-ui/src/shortcuts/utils.ts
+++ b/packages/docs-ui/src/shortcuts/utils.ts
@@ -15,7 +15,15 @@
*/
import type { IContextService } from '@univerjs/core';
-import { FOCUSING_COMMON_DRAWINGS, FOCUSING_DOC, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';
+import { EDITOR_ACTIVATED, FOCUSING_COMMON_DRAWINGS, FOCUSING_DOC, FOCUSING_FX_BAR_EDITOR, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';
+
+export function whenTextEditorFocused(contextService: IContextService): boolean {
+ return contextService.getContextValue(FOCUSING_UNIVER_EDITOR)
+ && !contextService.getContextValue(FOCUSING_COMMON_DRAWINGS)
+ && (contextService.getContextValue(FOCUSING_DOC)
+ || contextService.getContextValue(EDITOR_ACTIVATED)
+ || contextService.getContextValue(FOCUSING_FX_BAR_EDITOR));
+}
export function whenDocAndEditorFocused(contextService: IContextService): boolean {
return contextService.getContextValue(FOCUSING_DOC)
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.tsx
new file mode 100644
index 0000000000..3182223534
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-left-and-right-arrow.spec.tsx
@@ -0,0 +1,138 @@
+/**
+ * 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 { 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 { 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;
+
+describe('formula editor text navigation', () => {
+ it.each([
+ { isMac: true, keyCode: KeyCode.ARROW_LEFT, metaKey: true, direction: Direction.LEFT, granularity: 'line' },
+ { isMac: true, keyCode: KeyCode.ARROW_RIGHT, metaKey: true, direction: Direction.RIGHT, granularity: 'line' },
+ { isMac: true, keyCode: KeyCode.ARROW_DOWN, metaKey: true, direction: Direction.DOWN, granularity: 'document' },
+ { isMac: true, keyCode: KeyCode.ARROW_UP, metaKey: true, direction: Direction.UP, granularity: 'document' },
+ { isMac: true, keyCode: KeyCode.ARROW_LEFT, altKey: true, direction: Direction.LEFT, granularity: 'word' },
+ { isMac: true, keyCode: KeyCode.ARROW_RIGHT, altKey: true, direction: Direction.RIGHT, granularity: 'word' },
+ { isMac: true, keyCode: KeyCode.ARROW_UP, altKey: true, direction: Direction.UP, granularity: 'paragraph' },
+ { isMac: true, keyCode: KeyCode.ARROW_DOWN, altKey: true, direction: Direction.DOWN, granularity: 'paragraph' },
+ { isMac: false, keyCode: KeyCode.END, direction: Direction.RIGHT, granularity: 'line' },
+ { isMac: false, keyCode: KeyCode.HOME, direction: Direction.LEFT, granularity: 'line' },
+ { isMac: false, keyCode: KeyCode.ARROW_RIGHT, ctrlKey: true, direction: Direction.RIGHT, granularity: 'word' },
+ { isMac: false, keyCode: KeyCode.ARROW_UP, ctrlKey: true, direction: Direction.UP, granularity: 'paragraph' },
+ { isMac: false, keyCode: KeyCode.ARROW_DOWN, ctrlKey: true, direction: Direction.DOWN, granularity: 'paragraph' },
+ { isMac: false, keyCode: KeyCode.END, ctrlKey: true, direction: Direction.DOWN, granularity: 'document' },
+ { isMac: false, keyCode: KeyCode.ARROW_LEFT, ctrlKey: true, direction: Direction.LEFT, granularity: 'word' },
+ { isMac: false, keyCode: KeyCode.HOME, ctrlKey: true, direction: Direction.UP, granularity: 'document' },
+ ])('keeps the text movement for $keyCode on mac=$isMac', async (keys) => {
+ const injector = new Injector([
+ [ICommandService, { useClass: CommandService }],
+ [IConfigService, { useClass: ConfigService }],
+ [IContextService, { useClass: ContextService }],
+ [ILogService, { useClass: DesktopLogService }],
+ [IPlatformService, { useValue: { isMac: keys.isMac, isWindows: !keys.isMac, isLinux: false } }],
+ [IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }],
+ [IShortcutService, { useClass: ShortcutService }],
+ [IRenderManagerService, { useValue: {} }],
+ ]);
+ 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 } }]],
+ });
+ const commands = injector.get(ICommandService);
+ const executed = vi.fn();
+ commands.onCommandExecuted(executed);
+ await act(async () => root.render(<RediContext.Provider value={{ injector }}><EditorKeys /></RediContext.Provider>));
+ for (const shiftKey of [false, true]) {
+ const shortcut = shortcuts.dispatch(new KeyboardEvent('keydown', { ...keys, shiftKey }));
+ expect(shortcut).toBeDefined();
+ await commands.executeCommand(shortcut!.id, shortcut!.staticParameters);
+ expect(executed).toHaveBeenCalledWith(expect.objectContaining({
+ id: shiftKey ? MoveSelectionOperation.id : MoveCursorOperation.id,
+ params: { direction: keys.direction, granularity: keys.granularity },
+ }), expect.anything());
+ expect(onMoveInEditor).not.toHaveBeenCalled();
+ executed.mockClear();
+ }
+ context.setContextValue(EDITOR_ACTIVATED, false);
+ expect(shortcuts.dispatch(new KeyboardEvent('keydown', keys))).toBeUndefined();
+ context.setContextValue(FOCUSING_FX_BAR_EDITOR, true);
+ expect(shortcuts.dispatch(new KeyboardEvent('keydown', keys))?.id).toBe(MoveCursorOperation.id);
+ context.setContextValue(FOCUSING_UNIVER_EDITOR, false);
+ expect(shortcuts.dispatch(new KeyboardEvent('keydown', keys))).toBeUndefined();
+ context.setContextValue(FOCUSING_UNIVER_EDITOR, true);
+ for (const [event, id, granularity] of keys.isMac
+ ? [
+ [{ keyCode: KeyCode.BACKSPACE, altKey: true }, DeleteLeftCommand.id, 'word'],
+ [{ keyCode: KeyCode.BACKSPACE, metaKey: true }, DeleteLeftCommand.id, 'line'],
+ [{ keyCode: KeyCode.DELETE, altKey: true }, DeleteRightCommand.id, 'word'],
+ [{ keyCode: KeyCode.DELETE, ctrlKey: true }, DeleteRightCommand.id, 'line'],
+ ] as const
+ : [
+ [{ keyCode: KeyCode.BACKSPACE, ctrlKey: true }, DeleteLeftCommand.id, 'word'],
+ [{ keyCode: KeyCode.DELETE, ctrlKey: true }, DeleteRightCommand.id, 'line'],
+ ] as const) {
+ expect(shortcuts.dispatch(new KeyboardEvent('keydown', event))).toMatchObject({ id, staticParameters: { granularity } });
+ }
+ // The same key must still select worksheet references after entering formula point mode.
+ const moveReference = vi.fn(() => true);
+ const expandReference = vi.fn(() => true);
+ 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>));
+ for (const shiftKey of [false, true]) {
+ const shortcut = shortcuts.dispatch(new KeyboardEvent('keydown', {
+ keyCode: KeyCode.ARROW_LEFT,
+ metaKey: keys.isMac,
+ ctrlKey: !keys.isMac,
+ shiftKey,
+ }));
+ await commands.executeCommand(shortcut!.id, shortcut!.staticParameters);
+ expect(shiftKey ? expandReference : moveReference).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ direction: Direction.LEFT,
+ jumpOver: JumpOver.moveGap,
+ extra: 'formula-editor',
+ }), expect.anything());
+ }
+ } finally {
+ await act(async () => root.unmount());
+ injector.dispose();
+ }
+ });
+});
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.ts
index 5353da90e6..2d05cb544a 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
@@ -21,6 +21,7 @@ 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 {
@@ -77,7 +78,6 @@ export const useLeftAndRightArrow = (
const getRefSelectionCountRef = useRef(getRefSelectionCount);
getRefSelectionCountRef.current = getRefSelectionCount;
- // eslint-disable-next-line max-lines-per-function
useEffect(() => {
if (!editor || !isNeed) {
return;
@@ -110,11 +110,11 @@ export const useLeftAndRightArrow = (
}
if (metaKey === MetaKeys.SHIFT) {
- commandService.executeCommand(MoveSelectionOperation.id, {
+ return commandService.syncExecuteCommand(MoveSelectionOperation.id, {
direction,
});
} else {
- commandService.executeCommand(MoveCursorOperation.id, {
+ return commandService.syncExecuteCommand(MoveCursorOperation.id, {
direction,
});
}
@@ -137,32 +137,32 @@ export const useLeftAndRightArrow = (
getRefSelectionCountRef.current?.() ?? 0
);
if (metaKey === MetaKeys.CTRL_COMMAND) {
- commandService.executeCommand(MoveSelectionCommand.id, {
+ return commandService.executeCommand(MoveSelectionCommand.id, {
direction,
jumpOver: JumpOver.moveGap,
extra: 'formula-editor',
fromCurrentSelection,
});
} else if (metaKey === MetaKeys.SHIFT) {
- commandService.executeCommand(ExpandSelectionCommand.id, {
+ return commandService.executeCommand(ExpandSelectionCommand.id, {
direction,
extra: 'formula-editor',
});
} else if (metaKey === (MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT)) {
- commandService.executeCommand(ExpandSelectionCommand.id, {
+ return commandService.executeCommand(ExpandSelectionCommand.id, {
direction,
jumpOver: JumpOver.moveGap,
extra: 'formula-editor',
});
} else {
- commandService.executeCommand(MoveSelectionCommand.id, {
+ return commandService.executeCommand(MoveSelectionCommand.id, {
direction,
extra: 'formula-editor',
fromCurrentSelection,
});
}
} else {
- handleMoveInEditor(keycode, metaKey);
+ return handleMoveInEditor(keycode, metaKey);
}
};
@@ -171,7 +171,7 @@ export const useLeftAndRightArrow = (
type: CommandType.OPERATION,
handler(_event, params) {
const { keyCode, metaKey } = params as { eventType: DeviceInputEventType; keyCode: KeyCode; metaKey?: MetaKeys };
- handleKeycode(keyCode, metaKey);
+ return handleKeycode(keyCode, metaKey);
},
}));
@@ -198,7 +198,9 @@ export const useLeftAndRightArrow = (
return {
id: operationId,
binding: metaKey ? keyCode | metaKey : keyCode,
- preconditions: shouldHandleShortcut,
+ // Text navigation uses the shared editor shortcuts; point mode owns reference movement.
+ preconditions: () => shouldHandleShortcut() &&
+ (!(metaKey && (metaKey & MetaKeys.CTRL_COMMAND)) || Boolean(shouldMoveSelectionRef.current)),
priority: 900,
staticParameters: {
eventType: DeviceInputEventType.Keyboard,
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.ts
index d381f11712..66601ee3c6 100644
--- a/packages/sheets-ui/src/controllers/shortcuts/__tests__/editor.shortcut.spec.ts
+++ b/packages/sheets-ui/src/controllers/shortcuts/__tests__/editor.shortcut.spec.ts
@@ -14,57 +14,16 @@
* limitations under the License.
*/
-import {
- ContextService,
- Direction,
- EDITOR_ACTIVATED,
- FOCUSING_EDITOR_INPUT_FORMULA,
- FOCUSING_SHEET,
- FOCUSING_UNIVER_EDITOR,
- IContextService,
- Injector,
-} from '@univerjs/core';
-import { MoveCursorOperation, MoveSelectionOperation } from '@univerjs/docs-ui';
import { DeviceInputEventType } from '@univerjs/engine-render';
import { KeyCode, MetaKeys } from '@univerjs/ui';
import { describe, expect, it } from 'vitest';
+
import {
EditorCursorShiftEnterShortcut,
EditorCursorShiftTabShortcut,
- generateArrowSelectionShortCutItem,
} from '../editor.shortcut';
describe('editor shortcuts', () => {
- it.each([false, true])('moves to line boundaries with selection extension=%s only in an active Sheet text editor', (extend) => {
- const injector = new Injector();
- injector.add([IContextService, { useClass: ContextService }]);
- const context = injector.get(IContextService);
- context.setContextValue(FOCUSING_SHEET, true);
- context.setContextValue(FOCUSING_UNIVER_EDITOR, true);
- context.setContextValue(EDITOR_ACTIVATED, true);
- const shortcuts = generateArrowSelectionShortCutItem();
- const shift = extend ? MetaKeys.SHIFT : 0;
- for (const [key, arrow, direction] of [
- [KeyCode.HOME, KeyCode.ARROW_LEFT, Direction.LEFT],
- [KeyCode.END, KeyCode.ARROW_RIGHT, Direction.RIGHT],
- ]) {
- const shortcut = shortcuts.find((item) => item.binding === (key | shift));
- expect(shortcut).toBeDefined();
- expect(shortcut).toMatchObject({
- id: extend ? MoveSelectionOperation.id : MoveCursorOperation.id,
- mac: arrow | MetaKeys.CTRL_COMMAND | shift,
- staticParameters: { direction, granularity: 'line' },
- });
- expect(shortcut!.preconditions!(context)).toBe(true);
- context.setContextValue(EDITOR_ACTIVATED, false);
- expect(shortcut!.preconditions!(context)).toBe(false);
- context.setContextValue(EDITOR_ACTIVATED, true);
- context.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);
- expect(shortcut!.preconditions!(context)).toBe(false);
- context.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
- }
- injector.dispose();
- });
it.each([
['Shift+Enter', EditorCursorShiftEnterShortcut, KeyCode.ENTER],
['Shift+Tab', EditorCursorShiftTabShortcut, KeyCode.TAB],
diff --git a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts
index 629b1323e9..89c744df5e 100644
--- a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts
+++ b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts
@@ -15,16 +15,14 @@
*/
import type { IShortcutItem } from '@univerjs/ui';
-import { Direction } from '@univerjs/core';
import {
BreakLineCommand,
DeleteLeftCommand,
DeleteRightCommand,
- MoveCursorOperation,
- MoveSelectionOperation,
} from '@univerjs/docs-ui';
import { DeviceInputEventType } from '@univerjs/engine-render';
import { KeyCode, MetaKeys } from '@univerjs/ui';
+
import { RepeatLastActionCommand } from '../../commands/commands/repeat-last-action.command';
import {
SetCellEditVisibleArrowOperation,
@@ -77,23 +75,6 @@ export function generateArrowSelectionShortCutItem() {
});
}
- // Sheet editors own focus, so Doc-only line navigation shortcuts do not apply here.
- for (const [binding, macArrow, direction] of [
- [KeyCode.HOME, KeyCode.ARROW_LEFT, Direction.LEFT],
- [KeyCode.END, KeyCode.ARROW_RIGHT, Direction.RIGHT],
- ]) {
- for (const extend of [false, true]) {
- const shift = extend ? MetaKeys.SHIFT : 0;
- shortcutList.push({
- id: extend ? MoveSelectionOperation.id : MoveCursorOperation.id,
- binding: binding | shift,
- mac: macArrow | MetaKeys.CTRL_COMMAND | shift,
- preconditions: whenEditorDidNotInputFormulaActivated,
- staticParameters: { direction, granularity: 'line' },
- });
- }
- }
-
return shortcutList;
}