From 41d7cfad499f4cb0b830474eaa4bd153d0393e3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Mangeonjean?= Date: Thu, 7 Mar 2024 11:06:20 +0100 Subject: [PATCH] fix: keep in sync highlighted index when the option still exists but was moved --- .../src/useAutocomplete/useAutocomplete.js | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/packages/mui-base/src/useAutocomplete/useAutocomplete.js b/packages/mui-base/src/useAutocomplete/useAutocomplete.js index 78bbfc0b11d436..8a228836c14fb2 100644 --- a/packages/mui-base/src/useAutocomplete/useAutocomplete.js +++ b/packages/mui-base/src/useAutocomplete/useAutocomplete.js @@ -478,7 +478,7 @@ export function useAutocomplete(props) { }, ); - const checkHighlightedOptionExists = () => { + const getPreviousHighlightedOptionIndex = () => { const isSameValue = (value1, value2) => { const label1 = value1 ? getOptionLabel(value1) : ''; const label2 = value2 ? getOptionLabel(value2) : ''; @@ -498,16 +498,12 @@ export function useAutocomplete(props) { const previousHighlightedOption = previousProps.filteredOptions[highlightedIndexRef.current]; if (previousHighlightedOption) { - const previousHighlightedOptionExists = filteredOptions.some((option) => { + return findIndex(filteredOptions, (option) => { return getOptionLabel(option) === getOptionLabel(previousHighlightedOption); }); - - if (previousHighlightedOptionExists) { - return true; - } } } - return false; + return -1; }; const syncHighlightedIndex = React.useCallback(() => { @@ -517,7 +513,9 @@ export function useAutocomplete(props) { // Check if the previously highlighted option still exists in the updated filtered options list and if the value and inputValue haven't changed // If it exists and the value and the inputValue haven't changed, return, otherwise continue execution - if (checkHighlightedOptionExists()) { + const previousHighlightedOptionIndex = getPreviousHighlightedOptionIndex(); + if (previousHighlightedOptionIndex !== -1) { + highlightedIndexRef.current = previousHighlightedOptionIndex; return; }