Skip to content

Commit

Permalink
[ListboxUnstyled] Fix option state highlighted to prevent unnecessary…
Browse files Browse the repository at this point in the history
… focus (#35838)
  • Loading branch information
SaidMarar authored Jan 31, 2023
1 parent 14dba8d commit 94861ea
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/mui-base/src/ListboxUnstyled/useListbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ export default function useListbox<TOption>(props: UseListboxParameters<TOption>
return {
selected,
disabled,
highlighted: highlightedIndex === index,
highlighted: highlightedIndex === index && index !== -1,
};
};

Expand Down
34 changes: 34 additions & 0 deletions packages/mui-base/src/MenuUnstyled/MenuUnstyled.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import {
createMount,
createRenderer,
Expand Down Expand Up @@ -37,6 +38,39 @@ describe('MenuUnstyled', () => {
skip: ['reactTestRenderer', 'propsSpread', 'componentProp', 'slotsProp'],
}));

describe('after initialization', () => {
const spyFocus = spy();

function Test() {
React.useEffect(() => {
document.addEventListener('focus', spyFocus, true);
return () => {
document.removeEventListener('focus', spyFocus, true);
};
}, []);

return (
<MenuUnstyled {...defaultProps}>
<MenuItemUnstyled>1</MenuItemUnstyled>
<MenuItemUnstyled>2</MenuItemUnstyled>
<MenuItemUnstyled>3</MenuItemUnstyled>
</MenuUnstyled>
);
}

it('highlights the first item when the menu is opened', () => {
const { getAllByRole } = render(<Test />);
const [firstItem, ...otherItems] = getAllByRole('menuitem');

expect(firstItem.tabIndex).to.equal(0);
otherItems.forEach((item) => {
expect(item.tabIndex).to.equal(-1);
});
expect(spyFocus.callCount).to.equal(1);
expect(spyFocus.firstCall.args[0]).to.have.property('target', firstItem);
});
});

describe('keyboard navigation', () => {
it('changes the highlighted item using the arrow keys', () => {
const { getByTestId } = render(
Expand Down

0 comments on commit 94861ea

Please sign in to comment.