Skip to content

Commit

Permalink
Merge pull request #7954 from marmelab/7935-fix-delete-leading-charac…
Browse files Browse the repository at this point in the history
…ter-autocomplete-input

Fix leading character in AutocompleteInput can not be deleted
  • Loading branch information
fzaninotto committed Jul 21, 2022
2 parents 6a27ce3 + 9781adb commit d5ea810
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
33 changes: 33 additions & 0 deletions packages/ra-ui-materialui/src/input/AutocompleteInput.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,39 @@ describe('<AutocompleteInput />', () => {
});
});

it('should allow to clear the first character', async () => {
render(
<AdminContext dataProvider={testDataProvider()}>
<SimpleForm onSubmit={jest.fn()} defaultValues={{ role: 2 }}>
<AutocompleteInput
{...defaultProps}
optionText="foobar"
choices={[
{ id: 2, foobar: 'foo' },
{ id: 3, foobar: 'bar' },
]}
/>
</SimpleForm>
</AdminContext>
);

const input = screen.getByLabelText(
'resources.users.fields.role'
) as HTMLInputElement;

fireEvent.focus(input);

userEvent.type(input, 'f');
await waitFor(() => {
expect(input.value).toEqual('f');
});

userEvent.type(input, '{backspace}');
await waitFor(() => {
expect(input.value).toEqual('');
});
});

it('should use optionText with a string value including "." as text identifier', async () => {
render(
<AdminContext dataProvider={testDataProvider()}>
Expand Down
8 changes: 5 additions & 3 deletions packages/ra-ui-materialui/src/input/AutocompleteInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -357,14 +357,14 @@ If you provided a React element for the optionText prop, you must also provide t
newInputValue: string,
reason: string
) => {
if (!doesQueryMatchSelection(newInputValue)) {
if (!doesQueryMatchSelection(newInputValue, event?.type)) {
setFilterValue(newInputValue);
debouncedSetFilter(newInputValue);
}
};

const doesQueryMatchSelection = useCallback(
filter => {
(filter: string, eventType?: string) => {
let selectedItemTexts = [];

if (multiple) {
Expand All @@ -375,7 +375,9 @@ If you provided a React element for the optionText prop, you must also provide t
selectedItemTexts = [getOptionLabel(selectedChoice)];
}

return selectedItemTexts.includes(filter);
return eventType && eventType === 'change'
? selectedItemTexts.includes(filter) && selectedChoice
: selectedItemTexts.includes(filter);
},
[getOptionLabel, multiple, selectedChoice]
);
Expand Down

0 comments on commit d5ea810

Please sign in to comment.