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): stabilize context menu submenu interactions (#7978)

白熱d93672a79340
diff --git a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
index 7a740ece0d..4d4c732a36 100644
--- a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
+++ b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { Dispatch, KeyboardEvent, SetStateAction } from 'react';
+import type { Dispatch, KeyboardEvent, MouseEvent, RefObject, SetStateAction } from 'react';
import { isRealNum, LocaleService } from '@univerjs/core';
import { borderBottomClassName, borderClassName, clsx, cva, scrollbarClassName } from '@univerjs/design';
import { CheckMarkIcon, MoreLeftIcon, MoreRightIcon } from '@univerjs/icons';
@@ -87,6 +87,7 @@ interface IContextMenuMenuItemProps {
maxMenuHeight: number;
activeSubmenuKey: string | null;
setActiveSubmenuKey: Dispatch<SetStateAction<string | null>>;
+ pointerGraceRef: RefObject<IContextMenuPointerGrace | null>;
activeItemIds?: string[];
hiddenItemIds?: string[];
hoverSuppressed?: boolean;
@@ -98,6 +99,13 @@ interface IContextMenuMenuItemProps {
onOptionSelect?: (option: IValueOption) => void;
}
+interface IContextMenuPointerGrace {
+ menuKey: string;
+ contains: (event: MouseEvent<HTMLDivElement>) => boolean;
+ deferHover: (action: (() => void) | null) => void;
+ cancel: () => void;
+}
+
interface IContextMenuSchemaRenderGroup {
startIndex: number;
endIndex: number;
@@ -257,6 +265,7 @@ const contextMenuSubmenuPanelVariants = cva(
const contextMenuItemVariants = cva(
`
univer-relative univer-flex univer-border-none univer-bg-transparent univer-text-left univer-text-gray-900
+ rtl:!univer-text-right
dark:!univer-text-gray-0
`,
{
@@ -274,10 +283,17 @@ const contextMenuItemVariants = cva(
true: 'univer-cursor-not-allowed univer-opacity-60',
false: `
univer-cursor-pointer
- focus:univer-bg-gray-50 focus:univer-outline-none
- dark:focus:!univer-bg-gray-600
+ focus:univer-outline-none
+ focus-visible:univer-ring-2 focus-visible:univer-ring-inset focus-visible:univer-ring-primary-500
`,
},
+ submenuOpen: {
+ true: `
+ univer-bg-gray-50
+ dark:!univer-bg-gray-600
+ `,
+ false: '',
+ },
hoverSuppressed: {
true: '',
false: '',
@@ -858,6 +874,7 @@ function ContextMenuMenu(props: IContextMenuMenuProps) {
const localeService = useDependency(LocaleService);
const hiddenGroupStates = useContextGroupHiddenStates(menuSchemas);
const [activeSubmenuKey, setActiveSubmenuKey] = useState<string | null>(null);
+ const pointerGraceRef = useRef<IContextMenuPointerGrace | null>(null);
const visibleSchemas = useMemo(() => {
return menuSchemas.filter((item) => {
@@ -957,6 +974,7 @@ function ContextMenuMenu(props: IContextMenuMenuProps) {
rootMenuElement={rootMenuElement}
activeSubmenuKey={activeSubmenuKey}
setActiveSubmenuKey={setActiveSubmenuKey}
+ pointerGraceRef={pointerGraceRef}
onOptionSelect={onOptionSelect}
maxMenuHeight={maxMenuHeight}
hiddenItemIds={hiddenItemIds}
@@ -999,6 +1017,7 @@ function ContextMenuMenu(props: IContextMenuMenuProps) {
rootMenuElement={rootMenuElement}
activeSubmenuKey={activeSubmenuKey}
setActiveSubmenuKey={setActiveSubmenuKey}
+ pointerGraceRef={pointerGraceRef}
activeItemIds={activeItemIds}
hiddenItemIds={hiddenItemIds}
hoverSuppressed={hoverSuppressed}
@@ -1036,6 +1055,7 @@ function ContextMenuMenu(props: IContextMenuMenuProps) {
rootMenuElement={rootMenuElement}
activeSubmenuKey={activeSubmenuKey}
setActiveSubmenuKey={setActiveSubmenuKey}
+ pointerGraceRef={pointerGraceRef}
activeItemIds={activeItemIds}
hiddenItemIds={hiddenItemIds}
hoverSuppressed={hoverSuppressed}
@@ -1082,6 +1102,7 @@ function ContextMenuMenu(props: IContextMenuMenuProps) {
rootMenuElement={rootMenuElement}
activeSubmenuKey={activeSubmenuKey}
setActiveSubmenuKey={setActiveSubmenuKey}
+ pointerGraceRef={pointerGraceRef}
activeItemIds={activeItemIds}
hiddenItemIds={hiddenItemIds}
hoverSuppressed={hoverSuppressed}
@@ -1109,6 +1130,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
maxMenuHeight,
activeSubmenuKey,
setActiveSubmenuKey,
+ pointerGraceRef,
activeItemIds,
hiddenItemIds = [],
hoverSuppressed = false,
@@ -1144,6 +1166,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
const menuButtonRef = useRef<HTMLButtonElement | null>(null);
const submenuElementRef = useRef<HTMLDivElement | null>(null);
const submenuCloseTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const pendingHoverActionRef = useRef<(() => void) | null>(null);
const submenuId = useId();
const selections = useMemo(() => {
@@ -1173,13 +1196,16 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
const selectionsCommandId = selectorItem.selectionsCommandId;
const clearSubmenuCloseTimer = useCallback(() => {
- if (submenuCloseTimerRef.current == null) {
- return;
+ if (submenuCloseTimerRef.current != null) {
+ clearTimeout(submenuCloseTimerRef.current);
+ submenuCloseTimerRef.current = null;
}
- clearTimeout(submenuCloseTimerRef.current);
- submenuCloseTimerRef.current = null;
- }, []);
+ pendingHoverActionRef.current = null;
+ if (pointerGraceRef.current?.menuKey === menuKey) {
+ pointerGraceRef.current = null;
+ }
+ }, [menuKey, pointerGraceRef]);
const closeSubmenu = useCallback(() => {
clearSubmenuCloseTimer();
@@ -1189,8 +1215,11 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
const scheduleSubmenuClose = useCallback(() => {
clearSubmenuCloseTimer();
submenuCloseTimerRef.current = setTimeout(() => {
- submenuCloseTimerRef.current = null;
- if (!submenuElementRef.current?.contains(document.activeElement)) {
+ const pendingHoverAction = pendingHoverActionRef.current;
+ clearSubmenuCloseTimer();
+ if (pendingHoverAction) {
+ pendingHoverAction();
+ } else if (!submenuElementRef.current?.contains(document.activeElement)) {
closeSubmenu();
}
}, CONTEXT_MENU_SUBMENU_CLOSE_DELAY);
@@ -1203,10 +1232,10 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
useEffect(() => () => clearSubmenuCloseTimer(), [clearSubmenuCloseTimer]);
useEffect(() => {
- if (disabled) {
+ if (disabled || !submenuVisible) {
closeSubmenu();
}
- }, [closeSubmenu, disabled]);
+ }, [closeSubmenu, disabled, submenuVisible]);
useEffect(() => {
const submenuElement = submenuElementRef.current;
@@ -1295,6 +1324,26 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
setActiveSubmenuKey((currentKey) => (currentKey === menuKey ? null : currentKey));
};
+ const onPointerHover = (event: MouseEvent<HTMLDivElement>) => {
+ if (hoverSuppressed || (hasSubmenu && disabled)) {
+ return;
+ }
+
+ const applyHover = () => {
+ clearSubmenuCloseTimer();
+ setKeyboardSubmenuFocusRequested(false);
+ setActiveSubmenuKey(hasSubmenu ? menuKey : null);
+ };
+ const pointerGrace = pointerGraceRef.current;
+ if (pointerGrace && pointerGrace.menuKey !== menuKey && pointerGrace.contains(event)) {
+ pointerGrace.deferHover(applyHover);
+ return;
+ }
+
+ pointerGrace?.cancel();
+ applyHover();
+ };
+
const itemVariant: ContextMenuItemVariant = compact
? headerAction ? 'compactHeaderAction' : 'compact'
: 'default';
@@ -1302,7 +1351,8 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
sizeVariant,
variant: itemVariant,
disabled,
- hoverSuppressed,
+ hoverSuppressed: hoverSuppressed || (activeSubmenuKey !== null && !submenuVisible),
+ submenuOpen: submenuVisible,
active: resolveMenuItemActiveState(menuItem.id, activated, activeItemIds),
});
@@ -1331,25 +1381,14 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
<div
ref={menuItemElementRef}
className="univer-relative"
- onMouseEnter={() => {
- clearSubmenuCloseTimer();
- if (hasSubmenu && !disabled && !hoverSuppressed) {
- setKeyboardSubmenuFocusRequested(false);
- setSubmenuPositionReady(false);
- setActiveSubmenuKey(menuKey);
- return;
- }
-
- if (!hasSubmenu && !hoverSuppressed) {
- setActiveSubmenuKey(null);
- }
- }}
+ onMouseEnter={onPointerHover}
+ onMouseMove={onPointerHover}
onMouseLeave={(event) => {
- if (hasSubmenu) {
+ if (submenuVisible) {
if (submenuElementRef.current?.contains(document.activeElement)) {
return;
}
- const nextTarget = event.relatedTarget as Node | null;
+ const nextTarget = event.relatedTarget instanceof Node ? event.relatedTarget : null;
if (nextTarget && submenuElementRef.current?.contains(nextTarget)) {
return;
}
@@ -1358,6 +1397,25 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
return;
}
scheduleSubmenuClose();
+ const submenuRect = submenuElementRef.current?.firstElementChild?.getBoundingClientRect();
+ if (submenuRect) {
+ const { clientX: originX, clientY: originY } = event;
+ const edgeX = submenuPlacement === 'right' ? submenuRect.left : submenuRect.right;
+ // Protect the diagonal path to the submenu, including when it flips at a viewport edge.
+ pointerGraceRef.current = {
+ menuKey,
+ contains: ({ clientX, clientY }) => {
+ const progress = (clientX - originX) / (edgeX - originX);
+ return progress >= 0 && progress <= 1
+ && clientY >= originY + (submenuRect.top - originY) * progress
+ && clientY <= originY + (submenuRect.bottom - originY) * progress;
+ },
+ deferHover: (action) => { pendingHoverActionRef.current = action; },
+ cancel: clearSubmenuCloseTimer,
+ };
+ }
+ } else {
+ pointerGraceRef.current?.deferHover(null);
}
}}
>
@@ -1397,17 +1455,17 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
event.preventDefault();
event.stopPropagation();
+ pointerGraceRef.current?.cancel();
clearSubmenuCloseTimer();
setKeyboardSubmenuFocusRequested(true);
- setSubmenuPositionReady(false);
setActiveSubmenuKey(menuKey);
}}
onClick={(event) => {
+ pointerGraceRef.current?.cancel();
clearSubmenuCloseTimer();
if (hasSubmenu) {
if (headerAction) {
setKeyboardSubmenuFocusRequested(event.detail === 0);
- setSubmenuPositionReady(false);
setActiveSubmenuKey(menuKey);
return;
}
@@ -1425,7 +1483,6 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
}
setKeyboardSubmenuFocusRequested(event.detail === 0);
- setSubmenuPositionReady(false);
setActiveSubmenuKey(menuKey);
return;
}
@@ -1484,7 +1541,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
if (submenuElementRef.current?.contains(document.activeElement)) {
return;
}
- const nextTarget = event.relatedTarget as Node | null;
+ const nextTarget = event.relatedTarget instanceof Node ? event.relatedTarget : null;
if (nextTarget && menuItemElementRef.current?.contains(nextTarget)) {
return;
}
@@ -1542,12 +1599,14 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
univer-w-full univer-items-center univer-rounded-lg
univer-border-none univer-bg-transparent univer-px-3
univer-text-left univer-text-base
+ rtl:!univer-text-right
`
: `
univer-relative univer-box-border univer-flex univer-min-h-8
univer-w-full univer-items-center univer-rounded-md
univer-border-none univer-bg-transparent univer-px-2
univer-text-left univer-text-sm
+ rtl:!univer-text-right
`
: `
univer-relative univer-box-border univer-block univer-w-full
diff --git a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
index f8eb55c4ec..6ba58d82b5 100644
--- a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
+++ b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
@@ -425,7 +425,7 @@ describe('ContextMenuPanel', () => {
expect(TestState.cancels).toBe(1);
});
- it('enters, navigates, and exits a submenu with arrow keys', async () => {
+ it.each(['ltr', 'rtl'] as const)('enters, navigates, and exits a submenu with arrow keys in %s', async (direction) => {
renderWithDependencies(<ContextMenuPanel menuType="root" />, {
root: [
{
@@ -442,11 +442,11 @@ describe('ContextMenuPanel', () => {
createButtonItem('bring-front', { title: 'Bring to Front' }),
createButtonItem('send-back', { title: 'Send to Back' }),
],
- });
+ }, (injector) => injector.get(LocaleService).setDirection(direction));
const trigger = screen.getByRole('button', { name: 'Arrange' });
trigger.focus();
- fireEvent.keyDown(trigger, { key: 'ArrowRight' });
+ fireEvent.keyDown(trigger, { key: direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight' });
const first = await screen.findByRole('button', { name: 'Bring to Front' });
await nextFrame();
await waitFor(() => expect(document.activeElement).toBe(first));
@@ -455,10 +455,87 @@ describe('ContextMenuPanel', () => {
const second = screen.getByRole('button', { name: 'Send to Back' });
expect(document.activeElement).toBe(second);
- fireEvent.keyDown(second, { key: 'ArrowLeft' });
+ fireEvent.keyDown(second, { key: direction === 'rtl' ? 'ArrowRight' : 'ArrowLeft' });
expect(document.activeElement).toBe(trigger);
});
+ it.each(['click', 'pointer return', 'ArrowRight', 'Enter'])(
+ 'keeps a hovered submenu visible and usable after %s on its parent',
+ async (interaction) => {
+ const onOptionSelect = vi.fn();
+ renderWithDependencies(<ContextMenuPanel menuType="root" onOptionSelect={onOptionSelect} />, {
+ root: [{
+ key: 'copy-special',
+ order: 0,
+ item: {
+ id: 'copy-special',
+ type: MenuItemType.SUBITEMS,
+ title: 'Copy special',
+ },
+ }],
+ 'copy-special': [createButtonItem('copy-formula', { title: 'Copy formula only' })],
+ });
+ const trigger = screen.getByRole('button', { name: 'Copy special' });
+
+ fireEvent.mouseEnter(trigger);
+ await nextFrame();
+ expect(screen.getByRole('button', { name: 'Copy formula only' })).not.toBeNull();
+
+ if (interaction === 'click') {
+ fireEvent.click(trigger, { detail: 1 });
+ } else if (interaction === 'pointer return') {
+ const panel = trigger.closest('[tabindex="-1"]');
+ fireEvent.mouseLeave(trigger, { relatedTarget: panel });
+ fireEvent.mouseEnter(trigger);
+ } else {
+ trigger.focus();
+ fireEvent.keyDown(trigger, { key: interaction });
+ }
+ await nextFrame();
+ const option = screen.getByRole('button', { name: 'Copy formula only' });
+ if (interaction === 'ArrowRight' || interaction === 'Enter') {
+ expect(document.activeElement).toBe(option);
+ }
+ fireEvent.click(option);
+
+ expect(onOptionSelect).toHaveBeenCalledOnce();
+ expect(onOptionSelect).toHaveBeenCalledWith(expect.objectContaining({ id: 'copy-formula' }));
+ expect(screen.queryByRole('button', { name: 'Copy formula only' })).toBeNull();
+ }
+ );
+
+ it.each(['parent', 'submenu'])('closes the submenu when the pointer leaves the window from its %s', async (origin) => {
+ const contains = Node.prototype.contains;
+ // The test DOM accepts Window here, whereas browsers require a Node.
+ vi.spyOn(Node.prototype, 'contains').mockImplementation(function (this: Node, other) {
+ if (other !== null && !(other instanceof Node)) {
+ throw new TypeError('Node.contains requires a Node');
+ }
+ return contains.call(this, other);
+ });
+ renderWithDependencies(<ContextMenuPanel menuType="root" />, {
+ root: [{
+ key: 'color',
+ order: 0,
+ item: {
+ id: 'color',
+ type: MenuItemType.SELECTOR,
+ title: 'Color',
+ selections: [{ label: 'Red', value: 'red' }],
+ },
+ }],
+ });
+ const trigger = screen.getByRole('button', { name: 'Color' });
+ fireEvent.mouseEnter(trigger);
+ await nextFrame();
+ const submenu = document.getElementById(trigger.getAttribute('aria-controls')!)!;
+
+ fireEvent.mouseLeave(origin === 'parent' ? trigger : submenu, { relatedTarget: window });
+
+ expect(screen.queryByText('Red')).toBeNull();
+ expect(trigger.getAttribute('aria-expanded')).toBe('false');
+ });
+
it('selects an option from a selector submenu with the selector command id', () => {
renderWithDependencies(
<ContextMenuPanel
@@ -626,6 +703,79 @@ describe('ContextMenuPanel', () => {
expect(screen.getByText('docs-ui.fillColor')).not.toBeNull();
});
+ describe.each([
+ { direction: 'ltr' as const, triggerLeft: 100, side: 'right' },
+ { direction: 'ltr' as const, triggerLeft: 900, side: 'left' },
+ { direction: 'rtl' as const, triggerLeft: 600, side: 'left' },
+ { direction: 'rtl' as const, triggerLeft: 20, side: 'right' },
+ ])('pointer movement in $direction with a submenu opening to the $side', ({ direction, triggerLeft, side }) => {
+ it.each(['enter submenu', 'pause on sibling', 'click sibling', 'move away', 'leave sibling'])(
+ 'protects the diagonal path and handles %s',
+ async (interaction) => {
+ vi.stubGlobal('innerWidth', 1200);
+ const onOptionSelect = vi.fn();
+ renderWithDependencies(<ContextMenuPanel menuType="root" onOptionSelect={onOptionSelect} />, {
+ root: ['Paste', 'Clear'].map((title, order) => ({
+ key: title,
+ order,
+ item: { id: title, type: MenuItemType.SUBITEMS, title },
+ })),
+ Paste: ['Values', 'Format', 'Width', 'Borders', 'Formulas'].map((title) => createButtonItem(title, { title })),
+ Clear: [createButtonItem('clear-content', { title: 'Clear content' })],
+ }, (injector) => injector.get(LocaleService).setDirection(direction));
+ const paste = screen.getByRole('button', { name: 'Paste' });
+ const clear = screen.getByRole('button', { name: 'Clear' });
+ vi.spyOn(paste.parentElement!, 'getBoundingClientRect').mockReturnValue(new DOMRect(triggerLeft, 100, 200, 32));
+ fireEvent.mouseEnter(paste);
+ const submenu = document.getElementById(paste.getAttribute('aria-controls')!)!;
+ const submenuLeft = side === 'right' ? triggerLeft + 198 : triggerLeft - 198;
+ vi.spyOn(submenu, 'getBoundingClientRect').mockReturnValue(new DOMRect(submenuLeft, 100, 200, 180));
+ vi.spyOn(submenu.firstElementChild!, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(submenuLeft + (side === 'right' ? 20 : 0), 100, 180, 180)
+ );
+ await nextFrame();
+ expect(screen.getByRole('button', { name: 'Formulas' })).not.toBeNull();
+ expect(side === 'right'
+ ? Number.parseFloat(submenu.style.left) > triggerLeft
+ : Number.parseFloat(submenu.style.left) < triggerLeft).toBe(true);
+
+ vi.useFakeTimers();
+ const originX = triggerLeft + 100;
+ const step = side === 'right' ? 1 : -1;
+ fireEvent.mouseLeave(paste, { relatedTarget: clear, clientX: originX, clientY: 132 });
+ fireEvent.mouseEnter(clear, { clientX: originX + step * 30, clientY: 150 });
+
+ expect(screen.getByRole('button', { name: 'Formulas' })).not.toBeNull();
+ expect(screen.queryByText('Clear content')).toBeNull();
+
+ if (interaction === 'enter submenu') {
+ fireEvent.mouseMove(clear, { clientX: originX + step * 60, clientY: 165 });
+ fireEvent.mouseEnter(submenu);
+ act(() => vi.advanceTimersByTime(CONTEXT_MENU_SUBMENU_CLOSE_DELAY + 1));
+ fireEvent.click(screen.getByRole('button', { name: 'Formulas' }));
+ expect(onOptionSelect).toHaveBeenCalledWith(expect.objectContaining({ id: 'Formulas' }));
+ } else if (interaction === 'leave sibling') {
+ fireEvent.mouseLeave(clear, { relatedTarget: clear.closest('[tabindex="-1"]') });
+ act(() => vi.advanceTimersByTime(CONTEXT_MENU_SUBMENU_CLOSE_DELAY + 1));
+ expect(screen.queryByText('Clear content')).toBeNull();
+ expect(screen.queryByText('Formulas')).toBeNull();
+ } else {
+ if (interaction === 'pause on sibling') {
+ act(() => vi.advanceTimersByTime(CONTEXT_MENU_SUBMENU_CLOSE_DELAY + 1));
+ } else if (interaction === 'click sibling') {
+ fireEvent.click(clear, { detail: 1 });
+ } else {
+ fireEvent.mouseMove(clear, { clientX: originX, clientY: 160 });
+ }
+ expect(screen.getByText('Clear content')).not.toBeNull();
+ expect(screen.queryByText('Formulas')).toBeNull();
+ act(() => vi.advanceTimersByTime(CONTEXT_MENU_SUBMENU_CLOSE_DELAY + 1));
+ expect(screen.getByText('Clear content')).not.toBeNull();
+ }
+ }
+ );
+ });
+
it('closes an open submenu when its parent becomes disabled', async () => {
const disabled$ = new BehaviorSubject(false);