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(ui): preserve comment undo focus and dark hover styles (#7957)

wpxp123456f04bb0621aff
diff --git a/packages/docs-ui/src/views/RichTextEditor.tsx b/packages/docs-ui/src/views/RichTextEditor.tsx
index 148e4a08b6..6874bfb445 100644
--- a/packages/docs-ui/src/views/RichTextEditor.tsx
+++ b/packages/docs-ui/src/views/RichTextEditor.tsx
@@ -16,9 +16,6 @@
import type { IDocumentData } from '@univerjs/core';
import type { CSSProperties, ReactNode, RefObject } from 'react';
-import type { Editor, IEditorCanvasStyle } from '../services/editor/editor';
-import type { IEditorRuntimeConfig } from '../services/editor/editor-runtime-config';
-import type { IKeyboardEventConfig } from './rich-text-editor/hooks/use-keyboard-event';
import {
BuildTextUtils,
createInternalEditorID,
@@ -26,6 +23,7 @@ import {
getPlainText,
HorizontalAlign,
ICommandService,
+ IContextService,
IUniverInstanceService,
LocaleService,
RichTextBuilder,
@@ -37,6 +35,9 @@ import { IRenderManagerService } from '@univerjs/engine-render';
import { useDependency, useEvent, useObservable } from '@univerjs/ui';
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { map, merge, startWith } from 'rxjs';
+import type { Editor, IEditorCanvasStyle } from '../services/editor/editor';
+import type { IEditorRuntimeConfig } from '../services/editor/editor-runtime-config';
+import type { IKeyboardEventConfig } from './rich-text-editor/hooks/use-keyboard-event';
import { DocSelectionRenderService } from '../services/selection/doc-selection-render.service';
import { createEditorUndoRedoKeyboardConfig } from './rich-text-editor/hooks/editor-undo-redo-keyboard';
import { useEditor } from './rich-text-editor/hooks/use-editor';
@@ -123,6 +124,7 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {
} = props;
const commandService = useDependency(ICommandService);
+ const contextService = useDependency(IContextService);
const univerInstanceService = useDependency(IUniverInstanceService);
const localeService = useDependency(LocaleService);
const onFocusChange = useEvent(_onFocusChange);
@@ -226,11 +228,13 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {
const resolvedKeyboardEventConfig = useMemo(() => createEditorUndoRedoKeyboardConfig({
commandService,
+ contextService,
univerInstanceService,
editorUnitId: editorId,
+ preserveHostFocus,
keyCodes: keyboardEventConfig?.keyCodes,
handler: keyboardEventConfig?.handler,
- }), [commandService, editorId, keyboardEventConfig, univerInstanceService]);
+ }), [commandService, contextService, editorId, keyboardEventConfig, preserveHostFocus, univerInstanceService]);
useLeftAndRightArrow(isFocusing && moveCursor, false, editor);
// Undo can restore a non-collapsed selection without blurring the editor.
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.ts
index a0010488f2..06c329b76e 100644
--- 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.ts
@@ -14,15 +14,25 @@
* limitations under the License.
*/
-import type { ICommandService, IUniverInstanceService } from '@univerjs/core';
+import type { DocumentDataModel, IDocumentData, Nullable } from '@univerjs/core';
import {
+ CommandType,
+ DOCS_COMMENT_EDITOR_UNIT_ID_KEY,
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ FOCUSING_SHEET,
+ ICommandService,
+ IContextService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ LogLevel,
RedoCommand,
UndoCommand,
+ Univer,
+ UniverInstanceType,
} from '@univerjs/core';
-import { KeyCode, MetaKeys } from '@univerjs/ui';
-import { describe, expect, it, vi } from 'vitest';
+import { DISABLE_AUTO_FOCUS_KEY, KeyCode, MetaKeys } from '@univerjs/ui';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { createEditorUndoRedoKeyboardConfig, executeEditorUndoRedoCommand } from '../editor-undo-redo-keyboard';
function createCommandService() {
@@ -165,3 +175,167 @@ describe('editor undo redo keyboard helper', () => {
expect(handler).toHaveBeenCalledWith(KeyCode.B, undefined);
});
});
+
+describe('host-preserving editor undo redo', () => {
+ const editorUnitId = `${DOCS_COMMENT_EDITOR_UNIT_ID_KEY}_test`;
+ const setEditorTextMutationId = 'test.mutation.set-editor-text';
+ let univer: Univer;
+ let container: HTMLDivElement;
+
+ function createTestBed() {
+ univer = new Univer({ logLevel: LogLevel.SILENT });
+ const injector = univer.__getInjector();
+ const commandService = injector.get(ICommandService);
+ const contextService = injector.get(IContextService);
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ const undoRedoService = injector.get(IUndoRedoService);
+ const workbook = univer.createUnit(UniverInstanceType.UNIVER_SHEET, { id: 'host-sheet' });
+ const editor = univer.createUnit<Partial<IDocumentData>, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: editorUnitId,
+ body: { dataStream: 'reply\r\n' },
+ });
+ commandService.registerCommand({
+ id: setEditorTextMutationId,
+ type: CommandType.MUTATION,
+ handler: (accessor, params?: { dataStream: string }) => {
+ if (!params) {
+ return false;
+ }
+
+ const documentModel = accessor.get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>(editorUnitId, UniverInstanceType.UNIVER_DOC)!;
+ documentModel.reset({ ...documentModel.getSnapshot(), body: { dataStream: params.dataStream } });
+ return true;
+ },
+ });
+ undoRedoService.pushUndoRedo({
+ unitID: editorUnitId,
+ undoMutations: [{ id: setEditorTextMutationId, params: { dataStream: '\r\n' } }],
+ redoMutations: [{ id: setEditorTextMutationId, params: { dataStream: 'reply\r\n' } }],
+ });
+ undoRedoService.pushUndoRedo({ unitID: workbook.getUnitId(), undoMutations: [], redoMutations: [] });
+ univerInstanceService.focusUnit(workbook.getUnitId());
+
+ container = document.createElement('div');
+ const commentInput = document.createElement('textarea');
+ const cellInput = document.createElement('textarea');
+ container.append(commentInput, cellInput);
+ document.body.append(container);
+ // Model the sheet's native input focus response to the real host context notification.
+ const focusSubscription = contextService.subscribeContextValue$(FOCUSING_SHEET).subscribe((focusing) => {
+ if (focusing && !contextService.getContextValue(DISABLE_AUTO_FOCUS_KEY)) {
+ cellInput.focus();
+ }
+ });
+ univer.onDispose(() => focusSubscription.unsubscribe());
+ commentInput.focus();
+
+ return { commandService, contextService, univerInstanceService, undoRedoService, workbook, editor, commentInput, cellInput };
+ }
+
+ afterEach(() => {
+ univer?.dispose();
+ container?.remove();
+ });
+
+ it.each([
+ { keyCode: KeyCode.Z, metaKey: MetaKeys.CTRL_COMMAND, redo: false },
+ { keyCode: KeyCode.Y, metaKey: MetaKeys.CTRL_COMMAND, redo: true },
+ { keyCode: KeyCode.Z, metaKey: MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT, redo: true },
+ ])('keeps comment input focus for shortcut $keyCode:$metaKey', async ({ keyCode, metaKey, redo }) => {
+ const { commandService, contextService, univerInstanceService, undoRedoService, workbook, editor, commentInput } = createTestBed();
+ if (redo) {
+ univerInstanceService.focusUnit(editorUnitId);
+ commandService.syncExecuteCommand(UndoCommand.id);
+ univerInstanceService.focusUnit(workbook.getUnitId());
+ commentInput.focus();
+ }
+
+ const config = createEditorUndoRedoKeyboardConfig({
+ commandService,
+ contextService,
+ editorUnitId,
+ preserveHostFocus: true,
+ univerInstanceService,
+ });
+ config.handler(keyCode, metaKey);
+
+ await vi.waitFor(() => {
+ expect(univerInstanceService.getFocusedUnit()).toBe(workbook);
+ });
+
+ expect(editor.getBody()?.dataStream).toBe(redo ? 'reply\r\n' : '\r\n');
+ expect(document.activeElement).toBe(commentInput);
+ expect(contextService.getContextValue(DISABLE_AUTO_FOCUS_KEY)).toBe(false);
+ expect(undoRedoService.getUndoRedoStatus(workbook.getUnitId())).toEqual({ undos: 1, redos: 0 });
+ expect(undoRedoService.getUndoRedoStatus(editorUnitId)).toEqual(redo ? { undos: 1, redos: 0 } : { undos: 0, redos: 1 });
+ });
+
+ it('preserves an existing disable-auto-focus setting when undo history is empty', async () => {
+ const { commandService, contextService, univerInstanceService, undoRedoService, workbook, commentInput } = createTestBed();
+ contextService.setContextValue(DISABLE_AUTO_FOCUS_KEY, true);
+ undoRedoService.clearUndoRedo(editorUnitId);
+
+ executeEditorUndoRedoCommand({
+ commandId: UndoCommand.id,
+ commandService,
+ contextService,
+ editorUnitId,
+ preserveHostFocus: true,
+ univerInstanceService,
+ });
+
+ await vi.waitFor(() => {
+ expect(univerInstanceService.getFocusedUnit()).toBe(workbook);
+ });
+
+ expect(document.activeElement).toBe(commentInput);
+ expect(contextService.getContextValue(DISABLE_AUTO_FOCUS_KEY)).toBe(true);
+ });
+
+ it.each([false, true])('does not override a focus change during undo (preserveHostFocus=%s)', async (preserveHostFocus) => {
+ const { commandService, contextService, univerInstanceService, editor } = createTestBed();
+ const otherDocument = univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: 'other-doc' });
+ const focusChanges: Array<Nullable<string>> = [];
+ const subscription = univerInstanceService.focused$.subscribe((unitId) => focusChanges.push(unitId));
+ univer.onDispose(() => subscription.unsubscribe());
+
+ executeEditorUndoRedoCommand({
+ commandId: UndoCommand.id,
+ commandService,
+ contextService,
+ editorUnitId,
+ preserveHostFocus,
+ univerInstanceService,
+ });
+ univerInstanceService.focusUnit(otherDocument.getUnitId());
+
+ await vi.waitFor(() => {
+ expect(editor.getBody()?.dataStream).toBe('\r\n');
+ });
+ await waitForCommandFinally();
+
+ expect(univerInstanceService.getFocusedUnit()).toBe(otherDocument);
+ expect(focusChanges).toEqual(['host-sheet', editorUnitId, otherDocument.getUnitId()]);
+ expect(contextService.getContextValue(DISABLE_AUTO_FOCUS_KEY)).toBe(false);
+ });
+
+ it('keeps the existing host autofocus behavior for editors without preserveHostFocus', async () => {
+ const { commandService, contextService, univerInstanceService, workbook, cellInput } = createTestBed();
+
+ executeEditorUndoRedoCommand({
+ commandId: UndoCommand.id,
+ commandService,
+ contextService,
+ editorUnitId,
+ univerInstanceService,
+ });
+
+ await vi.waitFor(() => {
+ expect(univerInstanceService.getFocusedUnit()).toBe(workbook);
+ });
+
+ expect(document.activeElement).toBe(cellInput);
+ expect(contextService.getContextValue(DISABLE_AUTO_FOCUS_KEY)).toBe(false);
+ });
+});
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.ts
index 80678ef913..af68f7355b 100644
--- 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.ts
@@ -14,22 +14,32 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommandService, IUniverInstanceService } from '@univerjs/core';
+import type { DocumentDataModel, ICommandService, IContextService, IUniverInstanceService } from '@univerjs/core';
+import {
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ RedoCommand,
+ UndoCommand,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DISABLE_AUTO_FOCUS_KEY, KeyCode, MetaKeys } from '@univerjs/ui';
import type { IKeyboardEventConfig } from './use-keyboard-event';
-import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';
-import { KeyCode, MetaKeys } from '@univerjs/ui';
export interface IExecuteEditorUndoRedoCommandOptions {
commandId: string;
commandService: ICommandService;
editorUnitId: string;
univerInstanceService: IUniverInstanceService;
+ contextService?: IContextService;
+ preserveHostFocus?: boolean;
}
export interface ICreateEditorUndoRedoKeyboardConfigOptions {
commandService: ICommandService;
univerInstanceService: IUniverInstanceService;
editorUnitId: string;
+ contextService?: IContextService;
+ preserveHostFocus?: boolean;
keyCodes?: IKeyboardEventConfig['keyCodes'];
handler?: IKeyboardEventConfig['handler'];
}
@@ -44,7 +54,7 @@ function isSheetFormulaEditor(editorUnitId: string, univerInstanceService: IUniv
}
export function executeEditorUndoRedoCommand(options: IExecuteEditorUndoRedoCommandOptions): void {
- const { commandId, commandService, editorUnitId, univerInstanceService } = options;
+ const { commandId, commandService, contextService, editorUnitId, preserveHostFocus, univerInstanceService } = options;
const shouldUseSheetEditorContext =
editorUnitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY ||
editorUnitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;
@@ -61,14 +71,28 @@ export function executeEditorUndoRedoCommand(options: IExecuteEditorUndoRedoComm
}
commandService.executeCommand(commandId).finally(() => {
- if (shouldRestoreFocus) {
+ if (!shouldRestoreFocus || univerInstanceService.getFocusedUnit()?.getUnitId() !== editorUnitId) {
+ return;
+ }
+
+ if (!preserveHostFocus || !contextService) {
+ univerInstanceService.focusUnit(previousFocusedUnitId);
+ return;
+ }
+
+ // Restore the host context without moving input focus out of its embedded editor.
+ const previousDisableAutoFocus = contextService.getContextValue(DISABLE_AUTO_FOCUS_KEY);
+ contextService.setContextValue(DISABLE_AUTO_FOCUS_KEY, true);
+ try {
univerInstanceService.focusUnit(previousFocusedUnitId);
+ } finally {
+ contextService.setContextValue(DISABLE_AUTO_FOCUS_KEY, previousDisableAutoFocus);
}
});
}
export function createEditorUndoRedoKeyboardConfig(options: ICreateEditorUndoRedoKeyboardConfigOptions): IKeyboardEventConfig {
- const { commandService, editorUnitId, handler, keyCodes = [], univerInstanceService } = options;
+ const { commandService, contextService, editorUnitId, handler, keyCodes = [], preserveHostFocus, univerInstanceService } = options;
const ctrlCommand = MetaKeys.CTRL_COMMAND;
const ctrlCommandShift = MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT;
@@ -85,11 +109,25 @@ export function createEditorUndoRedoKeyboardConfig(options: ICreateEditorUndoRed
switch (shortcut) {
case `${KeyCode.Z}:${ctrlCommand}`:
- executeEditorUndoRedoCommand({ commandId: UndoCommand.id, commandService, editorUnitId, univerInstanceService });
+ executeEditorUndoRedoCommand({
+ commandId: UndoCommand.id,
+ commandService,
+ contextService,
+ editorUnitId,
+ preserveHostFocus,
+ univerInstanceService,
+ });
return;
case `${KeyCode.Y}:${ctrlCommand}`:
case `${KeyCode.Z}:${ctrlCommandShift}`:
- executeEditorUndoRedoCommand({ commandId: RedoCommand.id, commandService, editorUnitId, univerInstanceService });
+ executeEditorUndoRedoCommand({
+ commandId: RedoCommand.id,
+ commandService,
+ contextService,
+ editorUnitId,
+ preserveHostFocus,
+ univerInstanceService,
+ });
return;
}
diff --git a/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsx b/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsx
index 4df5bf2d47..d0931e0522 100644
--- a/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsx
+++ b/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsx
@@ -273,6 +273,7 @@ function SheetPermissionPanelListContent({ ActionRowComponent }: Required<ISheet
className={clsx(`
univer-mt-3 univer-rounded-lg univer-p-3
hover:univer-bg-gray-50
+ dark:hover:!univer-bg-gray-800
`, borderClassName)}
onMouseMove={() => {
const { subUnitId, unitType } = rule;
@@ -313,6 +314,7 @@ function SheetPermissionPanelListContent({ ActionRowComponent }: Required<ISheet
className={`
univer-box-border univer-h-6 univer-rounded-sm univer-p-1
hover:univer-bg-gray-200
+ dark:hover:!univer-bg-gray-700
`}
onClick={() => handleEdit(rule as IPermissionPanelRule)}
>
@@ -326,6 +328,7 @@ function SheetPermissionPanelListContent({ ActionRowComponent }: Required<ISheet
className={`
univer-box-border univer-h-6 univer-rounded-sm univer-p-1
hover:univer-bg-gray-200
+ dark:hover:!univer-bg-gray-700
`}
onClick={() => handleDelete(rule)}
>
diff --git a/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx b/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
index 75025b02ba..2a105a4893 100644
--- a/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
+++ b/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
@@ -17,8 +17,6 @@
import type { IUser, LocaleType, UniverInstanceType } from '@univerjs/core';
import type { IAddCommentCommandParams, IThreadComment, IUpdateCommentCommandParams } from '@univerjs/thread-comment';
import type { IUniverUIConfig } from '@univerjs/ui';
-import type { LocaleKey } from '../locale/types';
-import type { IThreadCommentEditorInstance } from './ThreadCommentEditor';
import {
dateKit,
generateRandomId,
@@ -43,6 +41,8 @@ import {
import { UI_PLUGIN_CONFIG_KEY, useConfigValue, useDependency, useEvent, useObservable } from '@univerjs/ui';
import { useEffect, useMemo, useRef, useState } from 'react';
import { debounceTime, map, of, startWith } from 'rxjs';
+import type { LocaleKey } from '../locale/types';
+import type { IThreadCommentEditorInstance } from './ThreadCommentEditor';
import { SetActiveCommentOperation } from '../commands/operations/comment.operations';
import { transformDocument2TextNodes, transformTextNodes2Document } from './thread-comment-editor/util';
import { getThreadCommentEditorId } from './thread-comment-tree/util';
@@ -248,7 +248,10 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {
<li>
<button
type="button"
- className="hover:univer-bg-gray-200"
+ className={`
+ hover:univer-bg-gray-200
+ dark:hover:!univer-bg-gray-800
+ `}
onClick={() => onEditingChange?.(true)}
>
{localeService.t<LocaleKey>('thread-comment-ui.item.edit')}
@@ -257,7 +260,10 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {
<li>
<button
type="button"
- className="hover:univer-bg-gray-200"
+ className={`
+ hover:univer-bg-gray-200
+ dark:hover:!univer-bg-gray-800
+ `}
onClick={handleDeleteItem}
>
{localeService.t<LocaleKey>('thread-comment-ui.item.delete')}