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 filtering when value is already selected #22935

Merged
merged 10 commits into from
Oct 9, 2020
31 changes: 31 additions & 0 deletions packages/material-ui/src/Autocomplete/Autocomplete.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2049,4 +2049,35 @@ describe('<Autocomplete />', () => {
);
});
});

it('should filter options when new input value matches option', () => {
const handleChange = spy();
const { getAllByRole, getByRole } = render(
<Autocomplete
openOnFocus
options={['one', 'two']}
onChange={handleChange}
renderInput={(params) => <TextField autoFocus {...params} />}
/>,
);
const textbox = getByRole('textbox');
const combobox = getByRole('combobox');

fireEvent.change(textbox, { target: { value: 'one' } });
fireEvent.keyDown(textbox, { key: 'ArrowDown' });
fireEvent.keyDown(textbox, { key: 'Enter' });
expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][1]).to.deep.equal('one');
expect(combobox).to.have.attribute('aria-expanded', 'false');

fireEvent.keyDown(textbox, { key: 'ArrowDown' });
expect(combobox).to.have.attribute('aria-expanded', 'true');

expect(getAllByRole('option')).to.have.length(2);

fireEvent.change(textbox, { target: { value: 'on' } });
fireEvent.change(textbox, { target: { value: 'one' } });

expect(getAllByRole('option')).to.have.length(1);
});
});
9 changes: 8 additions & 1 deletion packages/material-ui/src/useAutocomplete/useAutocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,8 @@ export default function useAutocomplete(props) {
state: 'open',
});

const [inputPristine, setInputPristine] = React.useState(true);

const inputValueIsSelectedValue =
!multiple && value != null && inputValue === getOptionLabel(value);

Expand All @@ -197,7 +199,10 @@ export default function useAutocomplete(props) {
}),
// we use the empty string to manipulate `filterOptions` to not filter any options
// i.e. the filter predicate always returns true
{ inputValue: inputValueIsSelectedValue ? '' : inputValue, getOptionLabel },
{
inputValue: inputValueIsSelectedValue && inputPristine ? '' : inputValue,
getOptionLabel,
},
)
: [];

Expand Down Expand Up @@ -495,6 +500,7 @@ export default function useAutocomplete(props) {
}

setOpenState(true);
setInputPristine(true);

if (onOpen) {
onOpen(event);
Expand Down Expand Up @@ -811,6 +817,7 @@ export default function useAutocomplete(props) {

if (inputValue !== newValue) {
setInputValueState(newValue);
setInputPristine(false);

if (onInputChange) {
onInputChange(event, newValue, 'input');
Expand Down