Skip to content

Commit

Permalink
[Autocomplete] Fix multiselect regression (#20315)
Browse files Browse the repository at this point in the history
  • Loading branch information
oliviertassinari authored Mar 29, 2020
1 parent bcbb349 commit d596401
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
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

0 comments on commit d596401

Please sign in to comment.