Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat: support editor-scoped undo redo (#7107)
Univer881f54cb5ea4
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.tsindex 5cad55c8ec..4fe96fd33d 100644--- a/packages/docs-ui/src/index.ts+++ b/packages/docs-ui/src/index.ts@@ -182,6 +182,10 @@ export { getAnchorBounding, getLineBounding, TEXT_RANGE_LAYER_INDEX, TextRange }export { whenDocAndEditorFocused } from './shortcuts/utils';export { DOC_VERTICAL_PADDING } from './types/const/padding';export {+ createEditorUndoRedoKeyboardConfig,+ executeEditorUndoRedoCommand,+ type ICreateEditorUndoRedoKeyboardConfigOptions,+ type IExecuteEditorUndoRedoCommandOptions,type IKeyboardEventConfig,useEditor,useEditorClickOutside,diff --git a/packages/docs-ui/src/views/RichTextEditor.tsx b/packages/docs-ui/src/views/RichTextEditor.tsxindex e4d366cb9e..808a3504d4 100644--- a/packages/docs-ui/src/views/RichTextEditor.tsx+++ b/packages/docs-ui/src/views/RichTextEditor.tsx@@ -18,14 +18,14 @@ import type { IDocumentData } from '@univerjs/core';import type { CSSProperties, ReactNode, RefObject } from 'react';import type { Editor } from '../services/editor/editor';import type { IKeyboardEventConfig } from './rich-text-editor/hooks';-import { BuildTextUtils, createInternalEditorID, generateRandomId, getPlainText } from '@univerjs/core';+import { BuildTextUtils, createInternalEditorID, generateRandomId, getPlainText, ICommandService, IUniverInstanceService } from '@univerjs/core';import { borderClassName, clsx } from '@univerjs/design';import { DocSkeletonManagerService } from '@univerjs/docs';import { IRenderManagerService } from '@univerjs/engine-render';import { useDependency, useEvent, useObservable } from '@univerjs/ui';import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { IEditorService } from '../services/editor/editor-manager.service';-import { useEditorClickOutside, useIsFocusing, useKeyboardEvent, useResize } from './rich-text-editor/hooks';+import { createEditorUndoRedoKeyboardConfig, useEditorClickOutside, useIsFocusing, useKeyboardEvent, useResize } from './rich-text-editor/hooks';import { useEditor } from './rich-text-editor/hooks/use-editor';import { useLeftAndRightArrow } from './rich-text-editor/hooks/use-left-and-right-arrow';import { useOnChange } from './rich-text-editor/hooks/use-on-change';@@ -73,6 +73,8 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {noStyle,} = props;const editorService = useDependency(IEditorService);+ const commandService = useDependency(ICommandService);+ const univerInstanceService = useDependency(IUniverInstanceService);const onFocusChange = useEvent(_onFocusChange);const onClickOutside = useEvent(_onClickOutside);const [height, setHeight] = useState(defaultHeight);@@ -132,8 +134,16 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {useEditorClickOutside(editorId, sheetEmbeddingRef, onClickOutside);+ const resolvedKeyboardEventConfig = useMemo(() => createEditorUndoRedoKeyboardConfig({+ commandService,+ univerInstanceService,+ editorUnitId: editorId,+ keyCodes: keyboardEventConfig?.keyCodes,+ handler: keyboardEventConfig?.handler,+ }), [commandService, editorId, keyboardEventConfig, univerInstanceService]);+useLeftAndRightArrow(isFocusing && moveCursor, false, editor);- useKeyboardEvent(isFocusing, keyboardEventConfig, editor);+ useKeyboardEvent(isFocusing, resolvedKeyboardEventConfig, editor);useOnChange(editor, onChange);return (diff --git a/packages/docs-ui/src/views/rich-text-editor/hooks/__tests__/editor-undo-redo-keyboard.spec.ts b/packages/docs-ui/src/views/rich-text-editor/hooks/__tests__/editor-undo-redo-keyboard.spec.tsnew file mode 100644index 0000000000..680af66120--- /dev/null+++ b/packages/docs-ui/src/views/rich-text-editor/hooks/__tests__/editor-undo-redo-keyboard.spec.ts@@ -0,0 +1,140 @@+/**+ * 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 { ICommandService, IUniverInstanceService } from '@univerjs/core';+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, RedoCommand, UndoCommand } from '@univerjs/core';+import { KeyCode, MetaKeys } from '@univerjs/ui';+import { describe, expect, it, vi } from 'vitest';+import { createEditorUndoRedoKeyboardConfig, executeEditorUndoRedoCommand } from '../editor-undo-redo-keyboard';++function createCommandService() {+ const executeCommand = vi.fn(async () => true) as unknown as ICommandService['executeCommand'] & ReturnType<typeof vi.fn>;++ return {+ executeCommand,+ } satisfies Pick<ICommandService, 'executeCommand'> & {+ executeCommand: ReturnType<typeof vi.fn>;+ };+}++function createUniverInstanceService(focusedUnitId: string | null = null) {+ let currentFocusedUnitId = focusedUnitId;+ const focusUnit = vi.fn((unitId: string) => {+ currentFocusedUnitId = unitId;+ });++ return {+ focusUnit,+ getFocusedUnit: vi.fn(() => currentFocusedUnitId == null+ ? undefined+ : { getUnitId: () => currentFocusedUnitId }),+ } as unknown as Pick<IUniverInstanceService, 'focusUnit' | 'getFocusedUnit'> & {+ focusUnit: ReturnType<typeof vi.fn>;+ };+}++async function waitForCommandFinally() {+ await Promise.resolve();+ await Promise.resolve();+}++describe('editor undo redo keyboard helper', () => {+ it('focuses a standalone editor before executing undo and restores the previous focus', async () => {+ const commandService = createCommandService();+ const univerInstanceService = createUniverInstanceService('host-doc');++ executeEditorUndoRedoCommand({+ commandId: UndoCommand.id,+ commandService,+ editorUnitId: 'comment-editor',+ univerInstanceService,+ });++ expect(univerInstanceService.focusUnit).toHaveBeenNthCalledWith(1, 'comment-editor');+ expect(commandService.executeCommand).toHaveBeenCalledWith(UndoCommand.id);++ await waitForCommandFinally();++ expect(univerInstanceService.focusUnit).toHaveBeenNthCalledWith(2, 'host-doc');+ });++ it('keeps sheet editor undo redo on the existing sheet context', async () => {+ for (const editorUnitId of [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY]) {+ const commandService = createCommandService();+ const univerInstanceService = createUniverInstanceService('sheet-unit');++ executeEditorUndoRedoCommand({+ commandId: RedoCommand.id,+ commandService,+ editorUnitId,+ univerInstanceService,+ });++ await waitForCommandFinally();++ expect(univerInstanceService.focusUnit).not.toHaveBeenCalled();+ expect(commandService.executeCommand).toHaveBeenCalledWith(RedoCommand.id);+ }+ });++ it('does not restore focus when no previous unit was focused', async () => {+ const commandService = createCommandService();+ const univerInstanceService = createUniverInstanceService();++ executeEditorUndoRedoCommand({+ commandId: UndoCommand.id,+ commandService,+ editorUnitId: 'shape-editor',+ univerInstanceService,+ });++ await waitForCommandFinally();++ expect(univerInstanceService.focusUnit).toHaveBeenCalledTimes(1);+ expect(univerInstanceService.focusUnit).toHaveBeenCalledWith('shape-editor');+ });++ it('registers undo redo shortcuts and delegates unmatched keys', () => {+ const commandService = createCommandService();+ const univerInstanceService = createUniverInstanceService('host-doc');+ const handler = vi.fn();++ const config = createEditorUndoRedoKeyboardConfig({+ commandService,+ editorUnitId: 'comment-editor',+ univerInstanceService,+ keyCodes: [{ keyCode: KeyCode.B, metaKey: MetaKeys.CTRL_COMMAND }],+ handler,+ });++ expect(config.keyCodes).toEqual([+ { keyCode: KeyCode.Z, metaKey: MetaKeys.CTRL_COMMAND },+ { keyCode: KeyCode.Y, metaKey: MetaKeys.CTRL_COMMAND },+ { keyCode: KeyCode.Z, metaKey: MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT },+ { keyCode: KeyCode.B, metaKey: MetaKeys.CTRL_COMMAND },+ ]);++ config.handler(KeyCode.Z, MetaKeys.CTRL_COMMAND);+ config.handler(KeyCode.Y, MetaKeys.CTRL_COMMAND);+ config.handler(KeyCode.Z, MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT);+ config.handler(KeyCode.B);++ expect(commandService.executeCommand).toHaveBeenNthCalledWith(1, UndoCommand.id);+ expect(commandService.executeCommand).toHaveBeenNthCalledWith(2, RedoCommand.id);+ expect(commandService.executeCommand).toHaveBeenNthCalledWith(3, RedoCommand.id);+ expect(handler).toHaveBeenCalledWith(KeyCode.B, undefined);+ });+});diff --git a/packages/docs-ui/src/views/rich-text-editor/hooks/editor-undo-redo-keyboard.ts b/packages/docs-ui/src/views/rich-text-editor/hooks/editor-undo-redo-keyboard.tsnew file mode 100644index 0000000000..5ef9be2949--- /dev/null+++ b/packages/docs-ui/src/views/rich-text-editor/hooks/editor-undo-redo-keyboard.ts@@ -0,0 +1,85 @@+/**+ * 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 { ICommandService, IUniverInstanceService } from '@univerjs/core';+import type { IKeyboardEventConfig } from './use-keyboard-event';+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, RedoCommand, UndoCommand } from '@univerjs/core';+import { KeyCode, MetaKeys } from '@univerjs/ui';++export interface IExecuteEditorUndoRedoCommandOptions {+ commandId: string;+ commandService: Pick<ICommandService, 'executeCommand'>;+ editorUnitId: string;+ univerInstanceService: Pick<IUniverInstanceService, 'focusUnit' | 'getFocusedUnit'>;+}++export interface ICreateEditorUndoRedoKeyboardConfigOptions {+ commandService: Pick<ICommandService, 'executeCommand'>;+ univerInstanceService: Pick<IUniverInstanceService, 'focusUnit' | 'getFocusedUnit'>;+ editorUnitId: string;+ keyCodes?: IKeyboardEventConfig['keyCodes'];+ handler?: IKeyboardEventConfig['handler'];+}++export function executeEditorUndoRedoCommand(options: IExecuteEditorUndoRedoCommandOptions): void {+ const { commandId, commandService, editorUnitId, univerInstanceService } = options;+ const shouldUseSheetEditorContext =+ editorUnitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY ||+ editorUnitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;+ const previousFocusedUnitId = univerInstanceService.getFocusedUnit()?.getUnitId() ?? null;+ const shouldRestoreFocus = !shouldUseSheetEditorContext && previousFocusedUnitId !== null && previousFocusedUnitId !== editorUnitId;++ if (!shouldUseSheetEditorContext && previousFocusedUnitId !== editorUnitId) {+ univerInstanceService.focusUnit(editorUnitId);+ }++ void commandService.executeCommand(commandId).finally(() => {+ if (shouldRestoreFocus) {+ univerInstanceService.focusUnit(previousFocusedUnitId);+ }+ });+}++export function createEditorUndoRedoKeyboardConfig(options: ICreateEditorUndoRedoKeyboardConfigOptions): IKeyboardEventConfig {+ const { commandService, editorUnitId, handler, keyCodes = [], univerInstanceService } = options;+ const ctrlCommand = MetaKeys.CTRL_COMMAND;+ const ctrlCommandShift = MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT;++ return {+ keyCodes: [+ { keyCode: KeyCode.Z, metaKey: ctrlCommand },+ { keyCode: KeyCode.Y, metaKey: ctrlCommand },+ { keyCode: KeyCode.Z, metaKey: ctrlCommandShift },+ ...keyCodes,+ ],+ handler: (keyCode, metaKey) => {+ const normalizedMetaKey = metaKey ?? 0;+ const shortcut = `${keyCode}:${normalizedMetaKey}`;++ switch (shortcut) {+ case `${KeyCode.Z}:${ctrlCommand}`:+ executeEditorUndoRedoCommand({ commandId: UndoCommand.id, commandService, editorUnitId, univerInstanceService });+ return;+ case `${KeyCode.Y}:${ctrlCommand}`:+ case `${KeyCode.Z}:${ctrlCommandShift}`:+ executeEditorUndoRedoCommand({ commandId: RedoCommand.id, commandService, editorUnitId, univerInstanceService });+ return;+ }++ handler?.(keyCode, metaKey);+ },+ };+}diff --git a/packages/docs-ui/src/views/rich-text-editor/hooks/index.ts b/packages/docs-ui/src/views/rich-text-editor/hooks/index.tsindex 42b0fce653..27d9385831 100644--- a/packages/docs-ui/src/views/rich-text-editor/hooks/index.ts+++ b/packages/docs-ui/src/views/rich-text-editor/hooks/index.ts@@ -14,6 +14,7 @@* limitations under the License.*/+export { createEditorUndoRedoKeyboardConfig, executeEditorUndoRedoCommand, type ICreateEditorUndoRedoKeyboardConfigOptions, type IExecuteEditorUndoRedoCommandOptions } from './editor-undo-redo-keyboard';export { useEditor } from './use-editor';export { useEditorClickOutside } from './use-editor-click-outside';export { useIsFocusing } from './use-is-focusing';diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsxindex e79f6bde43..084ab49464 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx@@ -27,6 +27,7 @@ import {DocumentFlavor,generateRandomId,HorizontalAlign,+ ICommandService,IConfigService,IUniverInstanceService,noop,@@ -34,7 +35,7 @@ import {VerticalAlign,} from '@univerjs/core';import { clsx } from '@univerjs/design';-import { DocBackScrollRenderController, DocSelectionRenderService, IEditorService, useKeyboardEvent, useResize } from '@univerjs/docs-ui';+import { createEditorUndoRedoKeyboardConfig, DocBackScrollRenderController, DocSelectionRenderService, IEditorService, useKeyboardEvent, useResize } from '@univerjs/docs-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { EMBEDDING_FORMULA_EDITOR } from '@univerjs/sheets-ui';import { useDependency, useEvent, useObservable, useUpdateEffect } from '@univerjs/ui';@@ -124,6 +125,7 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF} = props;const editorService = useDependency(IEditorService);+ const commandService = useDependency(ICommandService);const sheetEmbeddingRef = useRef<HTMLDivElement>(null);const onChange = useEvent(propOnChange);useImperativeHandle(ref, () => ({@@ -230,7 +232,15 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFonFormulaSelectingChange(isSelecting, docSelectionRenderService?.isFocusing ?? true);}, [onFormulaSelectingChange, isSelecting]);- useKeyboardEvent(isFocus, keyboardEventConfig, editor);+ const resolvedKeyboardEventConfig = useMemo(() => createEditorUndoRedoKeyboardConfig({+ commandService,+ univerInstanceService,+ editorUnitId: editorId,+ keyCodes: keyboardEventConfig?.keyCodes,+ handler: keyboardEventConfig?.handler,+ }), [commandService, editorId, keyboardEventConfig, univerInstanceService]);++ useKeyboardEvent(isFocus, resolvedKeyboardEventConfig, editor);useLayoutEffect(() => {let dispose: IDisposable;