Skip to content

Commit

Permalink
[ButtonBase] Fix space handling for non native button elements (mui#1…
Browse files Browse the repository at this point in the history
  • Loading branch information
captain-yossarian authored and EsoterikStare committed Mar 30, 2020
1 parent 0b271dc commit 63abd74
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
10 changes: 6 additions & 4 deletions packages/material-ui/src/ButtonBase/ButtonBase.js
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ const ButtonBase = React.forwardRef(function ButtonBase(props, ref) {
});
}

if (event.target === event.currentTarget && isNonNativeButton() && event.key === ' ') {
event.preventDefault();
}

if (onKeyDown) {
onKeyDown(event);
}
Expand Down Expand Up @@ -240,15 +244,13 @@ const ButtonBase = React.forwardRef(function ButtonBase(props, ref) {

// Keyboard accessibility for non interactive elements
if (
onClick &&
event.target === event.currentTarget &&
isNonNativeButton() &&
event.key === ' ' &&
!event.defaultPrevented
) {
event.preventDefault();
if (onClick) {
onClick(event);
}
onClick(event);
}
});

Expand Down
9 changes: 6 additions & 3 deletions packages/material-ui/src/ButtonBase/ButtonBase.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -679,10 +679,11 @@ describe('<ButtonBase />', () => {
});

describe('keyboard accessibility for non interactive elements', () => {
it('does not call onClick when a spacebar is pressed on the element', () => {
it('does not call onClick when a spacebar is pressed on the element but prevents the default', () => {
const onKeyDown = spy(event => event.defaultPrevented);
const onClickSpy = spy(event => event.defaultPrevented);
const { getByRole } = render(
<ButtonBase onClick={onClickSpy} component="div">
<ButtonBase onClick={onClickSpy} onKeyDown={onKeyDown} component="div">
Hello
</ButtonBase>,
);
Expand All @@ -694,6 +695,8 @@ describe('<ButtonBase />', () => {
});

expect(onClickSpy.callCount).to.equal(0);
// defaultPrevented?
expect(onKeyDown.returnValues[0]).to.equal(true);
});

it('does call onClick when a spacebar is released on the element', () => {
Expand All @@ -712,7 +715,7 @@ describe('<ButtonBase />', () => {

expect(onClickSpy.callCount).to.equal(1);
// defaultPrevented?
expect(onClickSpy.returnValues[0]).to.equal(true);
expect(onClickSpy.returnValues[0]).to.equal(false);
});

it('does not call onClick when a spacebar is released and the default is prevented', () => {
Expand Down

0 comments on commit 63abd74

Please sign in to comment.