Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ButtonBase] Fix space handling for non native button elements #19784

Merged
merged 3 commits into from
Feb 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
eps1lon marked this conversation as resolved.
Show resolved Hide resolved
});

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