Skip to content

Commit

Permalink
[Autocomplete] Fix filtering when value is already selected (#22935)
Browse files Browse the repository at this point in the history
  • Loading branch information
montelius committed Oct 9, 2020
1 parent 0f6292e commit a652d4f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
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

0 comments on commit a652d4f

Please sign in to comment.