Skip to content

Commit

Permalink
[Chip] prevent event default when onDelete is triggered (mui#20051)
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon authored and EsoterikStare committed Mar 30, 2020
1 parent c24aa5f commit 36cfa84
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
22 changes: 19 additions & 3 deletions packages/material-ui/src/Chip/Chip.js
Expand Up @@ -277,6 +277,7 @@ const Chip = React.forwardRef(function Chip(props, ref) {
label,
onClick,
onDelete,
onKeyDown,
onKeyUp,
size = 'medium',
variant = 'default',
Expand All @@ -294,6 +295,21 @@ const Chip = React.forwardRef(function Chip(props, ref) {
}
};

const isDeleteKeyboardEvent = keyboardEvent =>
keyboardEvent.key === 'Backspace' || keyboardEvent.key === 'Delete';

const handleKeyDown = event => {
if (isDeleteKeyboardEvent(event)) {
// will be handled in keyUp, otherwise some browsers
// might init navigation
event.preventDefault();
}

if (onKeyDown) {
onKeyDown(event);
}
};

const handleKeyUp = event => {
if (onKeyUp) {
onKeyUp(event);
Expand All @@ -304,10 +320,9 @@ const Chip = React.forwardRef(function Chip(props, ref) {
return;
}

const key = event.key;
if (onDelete && (key === 'Backspace' || key === 'Delete')) {
if (onDelete && isDeleteKeyboardEvent(event)) {
onDelete(event);
} else if (key === 'Escape' && chipRef.current) {
} else if (event.key === 'Escape' && chipRef.current) {
chipRef.current.blur();
}
};
Expand Down Expand Up @@ -393,6 +408,7 @@ const Chip = React.forwardRef(function Chip(props, ref) {
aria-disabled={disabled ? true : undefined}
tabIndex={clickable || onDelete ? 0 : undefined}
onClick={onClick}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
ref={handleRef}
{...moreProps}
Expand Down
13 changes: 12 additions & 1 deletion packages/material-ui/src/Chip/Chip.test.js
Expand Up @@ -362,10 +362,21 @@ describe('<Chip />', () => {
['Backspace', 'Delete'].forEach(key => {
it(`should call onDelete '${key}' is released`, () => {
const handleDelete = spy();
const { getAllByRole } = render(<Chip onClick={() => {}} onDelete={handleDelete} />);
const handleKeyDown = spy(event => {
return event.defaultPrevented;
});
const { getAllByRole } = render(
<Chip onClick={() => {}} onKeyDown={handleKeyDown} onDelete={handleDelete} />,
);
const chip = getAllByRole('button')[0];
chip.focus();

fireEvent.keyDown(document.activeElement, { key });

// defaultPrevented?
expect(handleKeyDown.returnValues[0]).to.equal(true);
expect(handleDelete.callCount).to.equal(0);

fireEvent.keyUp(document.activeElement, { key });

expect(handleDelete.callCount).to.equal(1);
Expand Down

0 comments on commit 36cfa84

Please sign in to comment.