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(docs-ui): stabilize paragraph menus and focus handoffs (#7696)

Univer33770fe73204
diff --git a/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts
index 80809f01c4..7e458fa8cf 100644
--- a/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts
@@ -109,7 +109,13 @@ describe('popup anchors with real document layout', () => {
}
});
- it.each([0, 1, 3])('covers a %i-character range through its trailing edge', (length) => {
+ it.each([
+ { startOffset: 1, length: 0 },
+ { startOffset: 1, length: 1 },
+ { startOffset: 1, length: 3 },
+ { startOffset: 5, length: 0 },
+ { startOffset: 6, length: 0 },
+ ])('anchors a $length-character range at $startOffset, including paragraph-end and empty carets', ({ startOffset, length }) => {
const context = new Proxy({
font: '',
webkitBackingStorePixelRatio: 1,
@@ -131,9 +137,12 @@ describe('popup anchors with real document layout', () => {
const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
id: 'popup-anchor-test',
body: {
- dataStream: 'A目CDZ\r\n',
- paragraphs: [{ startIndex: 5, paragraphId: 'paragraph-1' }],
- sectionBreaks: [{ startIndex: 6, sectionId: 'body' }],
+ dataStream: 'A目CDZ\r\r\n',
+ paragraphs: [
+ { startIndex: 5, paragraphId: 'paragraph-1' },
+ { startIndex: 6, paragraphId: 'paragraph-2' },
+ ],
+ sectionBreaks: [{ startIndex: 7, sectionId: 'body' }],
},
documentStyle: {
documentFlavor: DocumentFlavor.TRADITIONAL,
@@ -155,7 +164,7 @@ describe('popup anchors with real document layout', () => {
const documents = new Documents('popup-anchor-document', skeleton);
render.mainComponent = documents;
render.scene.addObject(documents);
- const bounds = calcDocRangePositions({ startOffset: 1, endOffset: 1 + length, collapsed: length === 0 }, render)!;
+ const bounds = calcDocRangePositions({ startOffset, endOffset: startOffset + length, collapsed: length === 0 }, render)!;
injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
injector.add([DocCanvasPopManagerService]);
const pendingRange = { startOffset: 1000, endOffset: 1001, collapsed: false };
@@ -176,11 +185,12 @@ describe('popup anchors with real document layout', () => {
skeleton.calculate();
expect(popupService.popups).toHaveLength(0);
pendingPopup.dispose();
- const lastGlyph = skeleton.findNodeByCharIndex(Math.max(1, length))!;
+ const lastGlyph = skeleton.findNodeByCharIndex(startOffset + Math.max(0, length - 1))!;
const lastGlyphBounds = calcDocGlyphPosition(lastGlyph, documents, skeleton)!;
expect(bounds).toHaveLength(1);
if (length === 0) {
expect(bounds[0].right).toBe(bounds[0].left);
+ expect(bounds[0].left).toBeCloseTo(lastGlyphBounds.left);
} else {
expect(bounds[0].right).toBeCloseTo(lastGlyphBounds.right);
expect(bounds[0].right).toBeGreaterThan(bounds[0].left);
diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
index 881b1e81a0..c2986d10fd 100644
--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
@@ -14,12 +14,37 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICustomBlock, ICustomTable, IDisposable, IDocumentBlockRange, INeedCheckDisposable, Nullable } from '@univerjs/core';
+import type {
+ DocumentDataModel,
+ ICustomBlock,
+ ICustomTable,
+ IDisposable,
+ IDocumentBlockRange,
+ INeedCheckDisposable,
+ Nullable,
+} from '@univerjs/core';
import type { IBoundRectNoAngle, IRenderContext, IRenderModule, ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IMutiPageParagraphBound, ITableBound, ITableParagraphBound } from './doc-event-manager.service';
import type { IEditorInputConfig } from './selection/doc-selection-render.service';
-import { BlockType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DocumentBlockType, getParagraphContentStartOffset, IContextService, Inject, IPermissionService, isInternalEditorID, PresetListType } from '@univerjs/core';
-import { canEditDocumentTargets, DocSelectionManagerService, DocSkeletonManagerService, getDocumentEditTargetObjectIds } from '@univerjs/docs';
+import {
+ BlockType,
+ DataStreamTreeTokenType,
+ Disposable,
+ DOC_RANGE_TYPE,
+ DocumentBlockType,
+ getParagraphContentStartOffset,
+ IContextService,
+ Inject,
+ IPermissionService,
+ isInternalEditorID,
+ PresetListType,
+} from '@univerjs/core';
+import {
+ canEditDocumentTargets,
+ DocSelectionManagerService,
+ DocSkeletonManagerService,
+ getDocumentEditTargetObjectIds,
+} from '@univerjs/docs';
import { DocumentEditArea } from '@univerjs/engine-render';
import { BehaviorSubject, combineLatest, first, throttleTime } from 'rxjs';
import { VIEWPORT_KEY } from '../basics/docs-view-key';
@@ -409,12 +434,13 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
return true;
}
+ this._isSlashMenuActive = true;
+ this.setParagraphMenuActive(true);
this._slashMenuRequest$.next({
anchorRect: this._getSlashMenuAnchorRect(config, paragraph),
nonce: ++this._slashMenuRequestNonce,
target,
});
- this._isSlashMenuActive = true;
return true;
}
diff --git a/packages/docs-ui/src/services/doc-popup-manager.service.ts b/packages/docs-ui/src/services/doc-popup-manager.service.ts
index 198bf8c5b0..9c58f69d23 100644
--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts
@@ -97,8 +97,27 @@ export interface IDocCanvasPopup extends Omit<IPopup, 'anchorRect$' | 'children'
export const calcDocRangePositions = (range: ITextRangeParam, currentRender: IRender): IBoundRectNoAngle[] | undefined => {
const { scene, mainComponent, engine } = currentRender;
const skeleton = currentRender.with(DocSkeletonManagerService).getSkeleton();
- const endIndex = range.collapsed ? range.startOffset : range.endOffset - 1;
- const positions = findDocRangeNodePositions(skeleton, range.startOffset, endIndex, range.segmentId, range.segmentPage);
+ let positions: ReturnType<typeof findDocRangeNodePositions>;
+ if (range.collapsed) {
+ // Paragraph separators are valid caret anchors, including at the start of an empty paragraph.
+ const caretPosition = skeleton.findNodePositionByCharIndex(
+ range.startOffset,
+ true,
+ range.segmentId,
+ range.segmentPage
+ );
+ if (caretPosition) {
+ positions = { startPosition: caretPosition, endPosition: caretPosition };
+ }
+ } else {
+ positions = findDocRangeNodePositions(
+ skeleton,
+ range.startOffset,
+ range.endOffset - 1,
+ range.segmentId,
+ range.segmentPage
+ );
+ }
const document = mainComponent as Documents;
if (!positions) {
diff --git a/packages/docs-ui/src/views/ParagraphMenu.tsx b/packages/docs-ui/src/views/ParagraphMenu.tsx
index 4ffad2e66a..d079bcb1c8 100644
--- a/packages/docs-ui/src/views/ParagraphMenu.tsx
+++ b/packages/docs-ui/src/views/ParagraphMenu.tsx
@@ -51,7 +51,6 @@ import {
RichTextEditingMutation,
} from '@univerjs/docs';
import { IRenderManagerService } from '@univerjs/engine-render';
-
import {
ContextMenuPanel,
IconManager,
@@ -60,7 +59,7 @@ import {
useDependency,
useObservable,
} from '@univerjs/ui';
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { BehaviorSubject } from 'rxjs';
import {
DocCopyCommand,
@@ -819,12 +818,10 @@ export function getParagraphMenuCommandTargetRange(
export function finishParagraphMenuCommand(
docParagraphMenuService: Pick<DocParagraphMenuService, 'hideParagraphMenu'> | null | undefined,
- layoutService: Pick<ILayoutService, 'focus'>,
hideMenu: () => void
) {
- docParagraphMenuService?.hideParagraphMenu(true);
hideMenu();
- layoutService.focus();
+ docParagraphMenuService?.hideParagraphMenu(true);
}
function getBlockSelectionRange(target: IDocBlockMenuTarget | null | undefined, paragraph?: IMutiPageParagraphBound | null): ITextRangeWithStyle | null {
@@ -894,6 +891,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const iconManager = useDependency(IconManager);
const anchorRef = useRef<HTMLDivElement>(null);
const isMouseOver = useRef(false);
+ const focusedMenuElementRef = useRef<HTMLElement | null>(null);
const hideTimerRef = useRef<number | null>(null);
const handledSlashRequestNonceRef = useRef(0);
const renderManagerService = useDependency(IRenderManagerService);
@@ -959,7 +957,25 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
anchorRect$.next(nextAnchorRect);
};
+ const restoreMenuFocus = useCallback(() => {
+ const focusedElement = focusedMenuElementRef.current;
+ focusedMenuElementRef.current = null;
+ if (!focusedElement) {
+ return;
+ }
+
+ const { activeElement, body } = focusedElement.ownerDocument;
+ // A portaled submenu can remove its focused button before the root menu closes.
+ if (activeElement === focusedElement || (!focusedElement.isConnected && activeElement === body)) {
+ layoutService.focus();
+ }
+ }, [layoutService]);
+
+ // Service-driven dismissal (for example scrolling) can unmount the entire popup.
+ useLayoutEffect(() => restoreMenuFocus, [restoreMenuFocus]);
+
const handleHideMenu = () => {
+ restoreMenuFocus();
setVisible(false);
setOpenMode('pointer');
targetRangeRef.current = null;
@@ -975,7 +991,13 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const scheduleHideMenu = () => {
clearHideTimer();
+ if (openMode === 'slash') {
+ return;
+ }
+
+ // Retain the interaction while crossing between the trigger, panel and portaled submenus.
hideTimerRef.current = window.setTimeout(() => {
+ hideTimerRef.current = null;
if (!isMouseOver.current && !isDraggingRef.current) {
handleHideMenu();
}
@@ -984,6 +1006,10 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const handleOpenMenu = (mode: ParagraphMenuOpenMode = 'pointer') => {
clearHideTimer();
+ if (openMode === 'slash') {
+ return;
+ }
+
const latestTarget = docParagraphMenuService?.activeTarget ?? activeTarget;
setParagraphMenuInteractionActive(docParagraphMenuService, true);
const targetRange = latestTarget
@@ -1102,7 +1128,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}
await commandService.executeCommand(SetInlineFormatTextColorCommand.id, { value: themeService.getColorFromTheme('gray.900') });
await commandService.executeCommand(SetInlineFormatTextBackgroundColorCommand.id, { value: themeService.getColorFromTheme('primary.600') });
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
return;
}
@@ -1119,7 +1145,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
},
},
});
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
return;
}
@@ -1138,7 +1164,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
if (wrappedCommandId) {
await commandService.executeCommand(wrappedCommandId);
}
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
return;
}
@@ -1155,13 +1181,13 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
replaceSelection(clipboardRange);
await executeResolvedCommand(option, clipboardRange);
}
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
return;
}
if (commandId === currentBlockCommandId) {
await unwrapActiveBlockRange();
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
return;
}
@@ -1180,7 +1206,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
params: commandParams as Record<string, unknown> | undefined,
}, nextRange);
}
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
return;
}
@@ -1193,7 +1219,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
commandId,
params: commandParams as Record<string, unknown> | undefined,
}, blockRange);
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
return;
}
}
@@ -1205,7 +1231,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
await executeResolvedCommand({
id: NormalTextHeadingCommand.id,
}, targetRange);
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
return;
}
@@ -1238,7 +1264,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
} finally {
restoreTextRanges(previousTextRanges);
}
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
};
const hoverBridgeStyle = visible && (menuDirection === 'left' || menuDirection === 'right')
@@ -1294,7 +1320,6 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}}
onMouseLeave={() => {
isMouseOver.current = false;
- setParagraphMenuInteractionActive(docParagraphMenuService, false);
cancelOpenMenu();
scheduleHideMenu();
}}
@@ -1426,7 +1451,6 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}}
onMouseLeave={() => {
isMouseOver.current = false;
- setParagraphMenuInteractionActive(docParagraphMenuService, false);
scheduleHideMenu();
}}
/>
@@ -1438,6 +1462,12 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
direction={menuDirection}
>
<section
+ onFocusCapture={(event) => {
+ focusedMenuElementRef.current = event.target;
+ }}
+ onBlurCapture={() => {
+ focusedMenuElementRef.current = null;
+ }}
onMouseEnter={(e) => {
popup.onPointerEnter?.(e);
setParagraphMenuInteractionActive(docParagraphMenuService, true);
@@ -1446,7 +1476,6 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}}
onMouseLeave={() => {
isMouseOver.current = false;
- setParagraphMenuInteractionActive(docParagraphMenuService, false);
scheduleHideMenu();
}}
>
@@ -1466,11 +1495,10 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}}
onMenuPointerLeave={() => {
isMouseOver.current = false;
- setParagraphMenuInteractionActive(docParagraphMenuService, false);
scheduleHideMenu();
}}
onCancel={() => {
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
}}
onOptionSelect={async (params) => {
const targetRange = targetRangeRef.current ?? getParagraphMenuTargetRange(activeParagraphBound);
@@ -1493,14 +1521,14 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
if (commandId === DocCopyCommand.id || commandId === DocCopyCommand.name) {
await docClipboardService.copy(SliceBodyType.copy, [tableRange]);
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
return;
}
if (commandId === DocPasteCommand.id) {
docSelectionManagerService.replaceDocRanges([afterTableRange], undefined, false);
await commandService.executeCommand(DocPasteCommand.id);
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
return;
}
@@ -1522,7 +1550,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
: commandParams);
}
- finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ finishParagraphMenuCommand(docParagraphMenuService, handleHideMenu);
univerInstanceService.focusUnit(popup.unitId);
return;
}