Skip to content

Commit

Permalink
[Autocomplete] Remove tags with the Delete key (mui#33822)
Browse files Browse the repository at this point in the history
Co-authored-by: Sylvialynn Favello <sylvia-favello@docker.com>
  • Loading branch information
2 people authored and felipe.richter committed Dec 6, 2022
1 parent 5d4f563 commit 6a3b3c7
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
10 changes: 10 additions & 0 deletions packages/mui-base/src/AutocompleteUnstyled/useAutocomplete.js
Expand Up @@ -859,6 +859,16 @@ export default function useAutocomplete(props) {
});
}
break;
case 'Delete':
if (multiple && !readOnly && inputValue === '' && value.length > 0 && focusedTag !== -1) {
const index = focusedTag;
const newValue = value.slice();
newValue.splice(index, 1);
handleValue(event, newValue, 'removeOption', {
option: value[index],
});
}
break;
default:
}
}
Expand Down
36 changes: 36 additions & 0 deletions packages/mui-material/src/Autocomplete/Autocomplete.test.js
Expand Up @@ -486,6 +486,42 @@ describe('<Autocomplete />', () => {
expect(textbox).toHaveFocus();
});

it('deletes a focused tag when pressing the delete key', () => {
const handleChange = spy();
const options = ['one', 'two'];
render(
<Autocomplete
defaultValue={options}
options={options}
onChange={handleChange}
renderInput={(params) => <TextField {...params} autoFocus />}
multiple
/>,
);
const textbox = screen.getByRole('combobox');
const [firstSelectedValue, secondSelectedValue] = screen.getAllByRole('button');

// check that no tags get deleted when the tag is not a focused tag
fireEvent.keyDown(textbox, { key: 'Delete' });

expect(handleChange.callCount).to.equal(0);
expect(textbox).toHaveFocus();

// expect on focused tag to delete when pressing delete key
fireEvent.keyDown(textbox, { key: 'ArrowLeft' });

expect(secondSelectedValue).toHaveFocus();

fireEvent.keyDown(secondSelectedValue, { key: 'ArrowLeft' });

expect(firstSelectedValue).toHaveFocus();

fireEvent.keyDown(firstSelectedValue, { key: 'Delete' });

expect(handleChange.callCount).to.equal(1);
expect(textbox).toHaveFocus();
});

it('should keep listbox open on pressing left or right keys when inputValue is not empty', () => {
const handleClose = spy();
const options = ['one', 'two', 'three'];
Expand Down

0 comments on commit 6a3b3c7

Please sign in to comment.