Skip to content

Commit

Permalink
[material-ui][MenuList] Do not react to an event with modifier key pr…
Browse files Browse the repository at this point in the history
…essed (#43505)

Co-authored-by: ZeeshanTamboli <[email protected]>
  • Loading branch information
MateuszGroth and ZeeshanTamboli authored Aug 30, 2024
1 parent 1995dcc commit 00eb6b9
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
10 changes: 10 additions & 0 deletions packages/mui-material/src/MenuList/MenuList.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,16 @@ const MenuList = React.forwardRef(function MenuList(props, ref) {
const handleKeyDown = (event) => {
const list = listRef.current;
const key = event.key;
const isModifierKeyPressed = event.ctrlKey || event.metaKey || event.altKey;

if (isModifierKeyPressed) {
if (onKeyDown) {
onKeyDown(event);
}

return;
}

/**
* @type {Element} - will always be defined since we are in a keydown handler
* attached to an element. A keydown event is either dispatched to the activeElement
Expand Down
43 changes: 43 additions & 0 deletions packages/mui-material/test/integration/MenuList.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,49 @@ describe('<MenuList> integration', () => {
expect(menuitems[1]).to.have.property('tabIndex', -1);
expect(menuitems[2]).to.have.property('tabIndex', -1);
});

describe('when a modifier key is pressed', () => {
it('should not move the focus', () => {
const { getAllByRole } = render(
<MenuList autoFocusItem>
<MenuItem selected>Menu Item 1</MenuItem>
<MenuItem>Menu Item 2</MenuItem>
<MenuItem>Menu Item 3</MenuItem>
</MenuList>,
);

const menuitems = getAllByRole('menuitem');
fireEvent.keyDown(menuitems[0], { key: 'ArrowDown', ctrlKey: true });
expect(menuitems[0]).toHaveFocus();
expect(menuitems[1]).not.toHaveFocus();

fireEvent.keyDown(menuitems[0], { key: 'ArrowDown', altKey: true });
expect(menuitems[0]).toHaveFocus();
expect(menuitems[1]).not.toHaveFocus();

fireEvent.keyDown(menuitems[0], { key: 'ArrowDown', metaKey: true });
expect(menuitems[0]).toHaveFocus();
expect(menuitems[1]).not.toHaveFocus();
});

it('should call the onKeyDown and not prevent default on the event', () => {
const onKeyDown = spy();
const { getAllByRole } = render(
<MenuList autoFocusItem onKeyDown={onKeyDown}>
<MenuItem selected>Menu Item 1</MenuItem>
<MenuItem>Menu Item 2</MenuItem>
<MenuItem>Menu Item 3</MenuItem>
</MenuList>,
);

const menuitems = getAllByRole('menuitem');
fireEvent.keyDown(menuitems[0], { key: 'ArrowDown', ctrlKey: true });

expect(onKeyDown.callCount).to.equal(1);
expect(onKeyDown.firstCall.args[0]).to.have.property('ctrlKey', true);
expect(onKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', false);
});
});
});

describe('keyboard controls and tabIndex manipulation - preselected item', () => {
Expand Down

0 comments on commit 00eb6b9

Please sign in to comment.