From 0fda717c2f29c5ba2330c383b4ab7c72c0039122 Mon Sep 17 00:00:00 2001 From: Olivier Tassinari Date: Sun, 29 Mar 2020 00:36:42 +0100 Subject: [PATCH] [Autocomplete] Fix multiselect regression --- .../src/Autocomplete/Autocomplete.test.js | 25 ++++++++++++++++++- .../src/useAutocomplete/useAutocomplete.js | 11 ++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 5e6c6054d6f486..23d950ed395ec3 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -77,7 +77,7 @@ describe('', () => { 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( ', () => { setProps({ value: 'two' }); checkHighlightIs('two'); }); + + it('should keep the current highlight if possible', () => { + const { getByRole } = render( + } + />, + ); + + 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', () => { diff --git a/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js b/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js index 5e058d12693643..23a59914b57c94 100644 --- a/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js +++ b/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js @@ -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), );