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

[Autocomplete] Fix multiselect regression #20315

Merged
Show file tree
Hide file tree
Changes from all 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
25 changes: 24 additions & 1 deletion packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ describe('<Autocomplete />', () => {
checkHighlightIs('one');
});

it('should set the focus on selected item when dropdown is expanded', () => {
it('should set the highlight on selected item when dropdown is expanded', () => {
const { getByRole, setProps } = render(
<Autocomplete
{...defaultProps}
Expand All @@ -95,6 +95,29 @@ describe('<Autocomplete />', () => {
setProps({ value: 'two' });
checkHighlightIs('two');
});

it('should keep the current highlight if possible', () => {
const { getByRole } = render(
<Autocomplete
{...defaultProps}
multiple
defaultValue={['one']}
options={['one', 'two', 'three']}
disableCloseOnSelect
renderInput={(params) => <TextField autoFocus {...params} />}
/>,
);

function checkHighlightIs(expected) {
expect(getByRole('listbox').querySelector('li[data-focus]')).to.have.text(expected);
}

checkHighlightIs('one');
fireEvent.keyDown(document.activeElement, { key: 'ArrowDown' });
checkHighlightIs('two');
fireEvent.keyDown(document.activeElement, { key: 'Enter' });
checkHighlightIs('two');
});
});

describe('prop: limitTags', () => {
Expand Down
11 changes: 11 additions & 0 deletions packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,17 @@ export default function useAutocomplete(props) {

// Synchronize the value with the highlighted index
if (!filterSelectedOptions && valueItem != null) {
const currentOption = filteredOptions[highlightedIndexRef.current];

// Keep the current highlighted index if possible
if (
multiple &&
currentOption &&
findIndex(value, (val) => getOptionSelected(currentOption, val)) !== -1
) {
return;
}

const itemIndex = findIndex(filteredOptions, (optionItem) =>
getOptionSelected(optionItem, valueItem),
);
Expand Down