Skip to content

Commit

Permalink
Add test and refactor for clarity
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon committed Dec 27, 2019
1 parent 04eaeb0 commit 661a6d4
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
30 changes: 30 additions & 0 deletions packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -889,4 +889,34 @@ describe('<Autocomplete />', () => {
expect(textbox).to.not.have.focus;
});
});

describe('prop: getOptionLabel', () => {
it('is considered for falsy values when filtering the the list of options', () => {
const { getAllByRole } = render(
<Autocomplete
options={[0, 10, 20]}
getOptionLabel={option => (option === 0 ? 'Any' : option.toString())}
renderInput={params => <TextField {...params} autoFocus />}
value={0}
/>,
);

const options = getAllByRole('option');
expect(options).to.have.length(3);
});

it('is not considered for nullish values when filtering the list of options', () => {
const { getAllByRole } = render(
<Autocomplete
options={[null, 10, 20]}
getOptionLabel={option => (option === null ? 'Any' : option.toString())}
renderInput={params => <TextField {...params} autoFocus />}
value={null}
/>,
);

const options = getAllByRole('option');
expect(options).to.have.length(3);
});
});
});
10 changes: 6 additions & 4 deletions packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,8 @@ export default function useAutocomplete(props) {
const [openState, setOpenState] = React.useState(false);
const open = isOpenControlled ? openProp : openState;

const inputValueFilter =
!multiple && value != null && inputValue === getOptionLabel(value) ? '' : inputValue;
const inputValueIsSelectedValue =
!multiple && value != null && inputValue === getOptionLabel(value);

let popupOpen = open;

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

Expand Down Expand Up @@ -585,7 +587,7 @@ export default function useAutocomplete(props) {
inputRef.current.value.length,
);
}
} else if (freeSolo && inputValueFilter !== '') {
} else if (freeSolo && inputValue !== '' && inputValueIsSelectedValue === false) {
selectNewValue(event, inputValue);
}
break;
Expand Down

0 comments on commit 661a6d4

Please sign in to comment.