Skip to content

Commit

Permalink
fix: fix menu item focus (#680)
Browse files Browse the repository at this point in the history
* chore: test

* fix: fix focus

---------

Co-authored-by: tanghui <[email protected]>
  • Loading branch information
MadCcc and yoyo837 authored Dec 6, 2023
1 parent 67baccb commit d21b6bb
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
9 changes: 7 additions & 2 deletions docs/examples/debug.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* eslint no-console:0 */

import React from 'react';
import React, { useRef } from 'react';
import type { CSSMotionProps } from 'rc-motion';
import Menu, { ItemGroup as MenuItemGroup } from '../../src';
import Menu, { ItemGroup as MenuItemGroup, MenuItem } from '../../src';
import type { MenuProps } from '../../src';
import '../../assets/index.less';
import '../../assets/menu.less';
Expand Down Expand Up @@ -52,6 +52,7 @@ export default () => {
const [inlineCollapsed, setInlineCollapsed] = React.useState(false);
const [forceRender, setForceRender] = React.useState(false);
const [openKeys, setOpenKeys] = React.useState<string[]>([]);
const menuRef = useRef();

const onRootClick = (info: MenuInfo) => {
console.log('Root Menu Item Click:', info);
Expand All @@ -68,6 +69,10 @@ export default () => {
return (
<>
<div>
<Menu ref={menuRef}>
<MenuItem key="light">Light</MenuItem>
</Menu>
<button onClick={() => menuRef.current.focus()}>focus</button>
<select value={mode} onChange={e => setMode(e.target.value as any)}>
<option value="inline">Inline</option>
<option value="vertical">Vertical</option>
Expand Down
5 changes: 4 additions & 1 deletion src/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,10 @@ const Menu = React.forwardRef<MenuRef, MenuProps>((props, ref) => {
);

const shouldFocusKey =
mergedActiveKey ?? element2key.get(focusableElements[0]);
mergedActiveKey ??
(focusableElements[0]
? element2key.get(focusableElements[0])
: childList.find(node => !node.props.disabled)?.key);

const elementToFocus = key2element.get(shouldFocusKey);

Expand Down
2 changes: 2 additions & 0 deletions tests/Menu.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,8 @@ describe('Menu', () => {
);

expect(menuRef.current?.list).toBe(container.querySelector('ul'));
act(() => menuRef.current.focus());
expect(document.activeElement).toBe(container.querySelector('li'));
});

it('should render a divider with role="separator"', () => {
Expand Down

0 comments on commit d21b6bb

Please sign in to comment.