Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ListboxUnstyled] Fix option state highlighted to prevent unnecessary focus #35838

Merged
merged 5 commits into from
Jan 31, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 data-testid="item-1">1</MenuItemUnstyled>
<MenuItemUnstyled data-testid="item-2">2</MenuItemUnstyled>
<MenuItemUnstyled data-testid="item-3">3</MenuItemUnstyled>
</MenuUnstyled>
);
}

it('when menu is opened it highlights one item and it must be the first one', () => {
const { getAllByTestId } = render(<Test />);
const [firstItem, ...otherItems] = getAllByTestId(/^item-/);
SaidMarar marked this conversation as resolved.
Show resolved Hide resolved

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);
SaidMarar marked this conversation as resolved.
Show resolved Hide resolved
});
});

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