Skip to content

[Autocomplete] Fix auto highlight when options change but not the length #46489

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

Merged
merged 8 commits into from
Aug 4, 2025
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
51 changes: 51 additions & 0 deletions packages/mui-material/src/Autocomplete/Autocomplete.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,57 @@ describe('<Autocomplete />', () => {
fireEvent.change(textbox, { target: { value: 'a' } });
checkHighlightIs(getByRole('listbox'), 'Bar');
});

// https://github.com/mui/material-ui/issues/45279
it('should auto highlight first option after options order changes with autoHighlight', () => {
const { setProps, getByRole } = render(
<Autocomplete
autoHighlight
open
options={['pediatric ent', 'pediatric flu', 'pediatrician', 'pediatric cough']}
renderInput={(params) => <TextField {...params} autoFocus />}
/>,
);

checkHighlightIs(getByRole('listbox'), 'pediatric ent');
setProps({
options: ['pediatrician', 'pediatric ent', 'pediatric flu', 'pediatric cough'],
});
checkHighlightIs(getByRole('listbox'), 'pediatrician');
});

it('should auto highlight first option when no match with input value with autoHighlight', () => {
const { getByRole } = render(
<Autocomplete
open
autoHighlight
options={['1', '2', '3', '4']}
value="5"
renderInput={(params) => <TextField {...params} autoFocus />}
/>,
);

checkHighlightIs(getByRole('listbox'), '1');
});

it('should auto highlight first option of rest after selecting an option with autoHighlight and filterSelectedOptions', () => {
const { getByRole } = render(
<Autocomplete
open
autoHighlight
options={['1', '2', '3', '4']}
renderInput={(params) => <TextField {...params} autoFocus />}
filterSelectedOptions
disableCloseOnSelect
/>,
);

const textbox = getByRole('combobox');

checkHighlightIs(getByRole('listbox'), '1');
fireEvent.keyDown(textbox, { key: 'Enter' });
checkHighlightIs(getByRole('listbox'), '2');
});
});

describe('highlight synchronisation', () => {
Expand Down
28 changes: 24 additions & 4 deletions packages/mui-material/src/useAutocomplete/useAutocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ import useControlled from '@mui/utils/useControlled';
import useId from '@mui/utils/useId';
import usePreviousProps from '@mui/utils/usePreviousProps';

function areArraysSame({ array1, array2, parser = (value) => value }) {
return (
array1 &&
array2 &&
array1.length === array2.length &&
array1.every((prevOption, index) => parser(prevOption) === parser(array2[index]))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to invert the logic using array.some for better performance?

if array1 is large, says >300 it could introduce performance issue.

Copy link
Contributor Author

@yafeng-c yafeng-c Jul 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I ask what's the specific solution you are suggesting?
if you mean !array1.some((prevOption, index) => parser(prevOption) !== parser(array2[index])), I don't think there will be improvement:

  1. if two array length are different then line 15 will not execute.
  2. every will return false and stop iterating immediately once a false returned in callback.
  3. if the two arrays are the same, some will still iterate the whole array1.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the clarification

);
}

// https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
function stripDiacritics(string) {
return string.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
Expand Down Expand Up @@ -456,6 +465,12 @@ function useAutocomplete(props) {
}
});

const filteredOptionsChanged = !areArraysSame({
array1: previousProps.filteredOptions,
array2: filteredOptions,
parser: getOptionLabel,
});

const getPreviousHighlightedOptionIndex = () => {
const isSameValue = (value1, value2) => {
const label1 = value1 ? getOptionLabel(value1) : '';
Expand All @@ -465,8 +480,11 @@ function useAutocomplete(props) {

if (
highlightedIndexRef.current !== -1 &&
previousProps.filteredOptions &&
previousProps.filteredOptions.length !== filteredOptions.length &&
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

strengthen this condition by checking if elements are the same.

!areArraysSame({
array1: previousProps.filteredOptions,
array2: filteredOptions,
parser: getOptionLabel,
}) &&
previousProps.inputValue === inputValue &&
(multiple
? value.length === previousProps.value.length &&
Expand Down Expand Up @@ -597,8 +615,10 @@ function useAutocomplete(props) {
}

React.useEffect(() => {
syncHighlightedIndex();
}, [syncHighlightedIndex]);
if (filteredOptionsChanged) {
syncHighlightedIndex();
}
}, [syncHighlightedIndex, filteredOptionsChanged]);

const handleOpen = (event) => {
if (open) {
Expand Down
Loading