diff --git a/src/Menu.tsx b/src/Menu.tsx index be2cab34..fa3e5665 100644 --- a/src/Menu.tsx +++ b/src/Menu.tsx @@ -30,6 +30,7 @@ import MenuItem from './MenuItem'; import SubMenu, { SemanticName } from './SubMenu'; import { parseItems } from './utils/nodeUtil'; import { warnItemProp } from './utils/warnUtil'; +import { getFocusTarget } from './utils/commonUtil'; /** * Menu modify after refactor: @@ -406,7 +407,8 @@ const Menu = React.forwardRef((props, ref) => { const elementToFocus = key2element.get(shouldFocusKey); if (shouldFocusKey && elementToFocus) { - elementToFocus?.focus?.(options); + const focusTargetElement = getFocusTarget(elementToFocus); + focusTargetElement?.focus?.(options); } }, findItem: ({ key: itemKey }) => { diff --git a/src/MenuItem.tsx b/src/MenuItem.tsx index 1108eb03..99366ec1 100644 --- a/src/MenuItem.tsx +++ b/src/MenuItem.tsx @@ -10,6 +10,7 @@ import useActive from './hooks/useActive'; import useDirectionStyle from './hooks/useDirectionStyle'; import Icon from './Icon'; import type { MenuInfo, ItemData, MenuItemType } from './interface'; +import { getFocusTarget } from './utils/commonUtil'; import { warnItemProp } from './utils/warnUtil'; export interface MenuItemProps @@ -186,6 +187,11 @@ const InternalMenuItem = React.forwardRef((props: MenuItemProps, ref: React.Ref< onKeyDown?.(e); if (!mergedDisabled && e.which === KeyCode.ENTER) { + const target = e.target as HTMLElement | null; + if (target?.closest?.('a[href]')) { + return; + } + const info = getEventInfo(e); // Legacy. Key will also trigger click event @@ -199,6 +205,14 @@ const InternalMenuItem = React.forwardRef((props: MenuItemProps, ref: React.Ref< * We should manually trigger an active */ const onInternalFocus: React.FocusEventHandler = e => { + if (e.target === elementRef.current) { + const link = getFocusTarget(elementRef.current); + if (link && link !== elementRef.current) { + link.focus({ preventScroll: true }); + return; + } + } + onActive(eventKey); onFocus?.(e); }; diff --git a/src/hooks/useAccessibility.ts b/src/hooks/useAccessibility.ts index c4ba7dd9..2419d6cd 100644 --- a/src/hooks/useAccessibility.ts +++ b/src/hooks/useAccessibility.ts @@ -2,6 +2,7 @@ import { KeyCode, getFocusNodeList, raf } from '@rc-component/util'; import * as React from 'react'; import { getMenuId } from '../context/IdContext'; import type { MenuMode } from '../interface'; +import { getFocusTarget } from '../utils/commonUtil'; // destruct to reduce minify size const { LEFT, RIGHT, UP, DOWN, ENTER, ESC, HOME, END } = KeyCode; @@ -228,13 +229,7 @@ export function useAccessibility( const tryFocus = (menuElement: HTMLElement) => { if (menuElement) { - let focusTargetElement = menuElement; - - // Focus to link instead of menu item if possible - const link = menuElement.querySelector('a'); - if (link?.getAttribute('href')) { - focusTargetElement = link; - } + const focusTargetElement = getFocusTarget(menuElement); const targetKey = element2key.get(menuElement); triggerActiveKey(targetKey); @@ -247,7 +242,7 @@ export function useAccessibility( cleanRaf(); rafRef.current = raf(() => { if (activeRef.current === targetKey) { - focusTargetElement.focus(); + focusTargetElement?.focus(); } }); } diff --git a/src/utils/commonUtil.ts b/src/utils/commonUtil.ts index 8054c8c4..5810f4d2 100644 --- a/src/utils/commonUtil.ts +++ b/src/utils/commonUtil.ts @@ -25,3 +25,15 @@ export function parseChildren(children: React.ReactNode | undefined, keyPath: st return child; }); } + +/** + * Find the focus target within a menu element. + * If the menu element contains an anchor with href, focus the anchor instead. + */ +export function getFocusTarget(element?: HTMLElement | null): HTMLElement | null { + if (!element) { + return null; + } + const link = element.querySelector('a[href]'); + return link || element; +} diff --git a/tests/Focus.spec.tsx b/tests/Focus.spec.tsx index 3d90507f..6673e21f 100644 --- a/tests/Focus.spec.tsx +++ b/tests/Focus.spec.tsx @@ -1,6 +1,6 @@ /* eslint-disable no-undef */ import { act, fireEvent, render } from '@testing-library/react'; -import { spyElementPrototypes } from '@rc-component/util'; +import { spyElementPrototypes, KeyCode } from '@rc-component/util'; import React from 'react'; import Menu, { MenuItem, MenuItemGroup, MenuRef, SubMenu } from '../src'; @@ -186,5 +186,117 @@ describe('Focus', () => { expect(document.activeElement).toBe(getByTitle('Submenu')); expect(getByTestId('sub-menu')).toHaveClass('rc-menu-submenu-active'); }); + + it('should focus anchor link inside menu item through ref', async () => { + const menuRef = React.createRef(); + const { container } = await act(async () => + render( + + + Light + + , + ), + ); + + act(() => menuRef.current.focus()); + + const anchor = container.querySelector('a'); + expect(document.activeElement).toBe(anchor); + expect(container.querySelector('.rc-menu-item')).toHaveClass('rc-menu-item-active'); + }); + + it('should delegate focus to anchor link when menu item li is focused', async () => { + const onFocus = jest.fn(); + const { container } = await act(async () => + render( + + + Light + + , + ), + ); + + const anchor = container.querySelector('a'); + const focusSpy = jest.spyOn(anchor, 'focus'); + + fireEvent.focus(container.querySelector('.rc-menu-item')); + + expect(document.activeElement).toBe(anchor); + expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true }); + expect(onFocus).toHaveBeenCalledTimes(1); + expect(onFocus.mock.calls[0][0].target).toBe(anchor); + }); + + it('should preserve preventScroll option when focusing through ref', async () => { + const menuRef = React.createRef(); + const { container } = await act(async () => + render( + + + Light + + , + ), + ); + + const anchor = container.querySelector('a'); + const focusSpy = jest.spyOn(anchor, 'focus'); + + act(() => menuRef.current.focus({ preventScroll: true })); + + expect(document.activeElement).toBe(anchor); + expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true }); + }); + + it('should invoke click/select only once on Enter for anchor item and retain ordinary item activation', async () => { + const menuRef = React.createRef(); + const onClick = jest.fn(); + const onSelect = jest.fn(); + const onDeselect = jest.fn(); + + const { container } = await act(async () => + render( + + + Light + + Normal + , + ), + ); + + act(() => menuRef.current.focus()); + + const anchor = container.querySelector('a'); + expect(document.activeElement).toBe(anchor); + + // Pressing Enter on focused anchor should not duplicate click via keydown + native click + const keyDownNotPrevented = fireEvent.keyDown(anchor, { + which: KeyCode.ENTER, + keyCode: KeyCode.ENTER, + key: 'Enter', + }); + expect(keyDownNotPrevented).toBe(true); + expect(onClick).not.toHaveBeenCalled(); + + const clickNotPrevented = fireEvent.click(anchor); + expect(clickNotPrevented).toBe(true); + expect(onClick).toHaveBeenCalledTimes(1); + expect(onSelect).toHaveBeenCalledTimes(1); + expect(onDeselect).not.toHaveBeenCalled(); + + // Ordinary item without anchor should still activate via Enter keyDown + const items = container.querySelectorAll('.rc-menu-item'); + const normalItem = items[1]; + fireEvent.keyDown(normalItem, { + which: KeyCode.ENTER, + keyCode: KeyCode.ENTER, + key: 'Enter', + }); + expect(onClick).toHaveBeenCalledTimes(2); + expect(onSelect).toHaveBeenCalledTimes(2); + }); }); /* eslint-enable */