Skip to content

Commit d5ea810

Browse files
authoredJul 21, 2022
Merge pull request #7954 from marmelab/7935-fix-delete-leading-character-autocomplete-input
Fix leading character in AutocompleteInput can not be deleted
2 parents 6a27ce3 + 9781adb commit d5ea810

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed
 

‎packages/ra-ui-materialui/src/input/AutocompleteInput.spec.tsx

+33
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,39 @@ describe('<AutocompleteInput />', () => {
124124
});
125125
});
126126

127+
it('should allow to clear the first character', async () => {
128+
render(
129+
<AdminContext dataProvider={testDataProvider()}>
130+
<SimpleForm onSubmit={jest.fn()} defaultValues={{ role: 2 }}>
131+
<AutocompleteInput
132+
{...defaultProps}
133+
optionText="foobar"
134+
choices={[
135+
{ id: 2, foobar: 'foo' },
136+
{ id: 3, foobar: 'bar' },
137+
]}
138+
/>
139+
</SimpleForm>
140+
</AdminContext>
141+
);
142+
143+
const input = screen.getByLabelText(
144+
'resources.users.fields.role'
145+
) as HTMLInputElement;
146+
147+
fireEvent.focus(input);
148+
149+
userEvent.type(input, 'f');
150+
await waitFor(() => {
151+
expect(input.value).toEqual('f');
152+
});
153+
154+
userEvent.type(input, '{backspace}');
155+
await waitFor(() => {
156+
expect(input.value).toEqual('');
157+
});
158+
});
159+
127160
it('should use optionText with a string value including "." as text identifier', async () => {
128161
render(
129162
<AdminContext dataProvider={testDataProvider()}>

‎packages/ra-ui-materialui/src/input/AutocompleteInput.tsx

+5-3
Original file line numberDiff line numberDiff line change
@@ -357,14 +357,14 @@ If you provided a React element for the optionText prop, you must also provide t
357357
newInputValue: string,
358358
reason: string
359359
) => {
360-
if (!doesQueryMatchSelection(newInputValue)) {
360+
if (!doesQueryMatchSelection(newInputValue, event?.type)) {
361361
setFilterValue(newInputValue);
362362
debouncedSetFilter(newInputValue);
363363
}
364364
};
365365

366366
const doesQueryMatchSelection = useCallback(
367-
filter => {
367+
(filter: string, eventType?: string) => {
368368
let selectedItemTexts = [];
369369

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

378-
return selectedItemTexts.includes(filter);
378+
return eventType && eventType === 'change'
379+
? selectedItemTexts.includes(filter) && selectedChoice
380+
: selectedItemTexts.includes(filter);
379381
},
380382
[getOptionLabel, multiple, selectedChoice]
381383
);

0 commit comments

Comments
 (0)
Please sign in to comment.