Skip to content

Commit

Permalink
fix(Card): prevent keyboard handler form abort (#829)
Browse files Browse the repository at this point in the history
Co-authored-by: Alexey <[email protected]>
  • Loading branch information
korvin89 and ogonkov authored Jul 19, 2023
1 parent 268f2d6 commit e45c902
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 9 deletions.
5 changes: 4 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@
"node": true,
"jest": true
},
"extends": ["plugin:testing-library/react"]
"extends": ["plugin:testing-library/react"],
"rules": {
"jsx-a11y/no-static-element-interactions": 0
}
},
{
"files": ["**/__stories__/**/*.[jt]s?(x)"],
Expand Down
4 changes: 2 additions & 2 deletions src/components/Card/Card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const Card = React.forwardRef<HTMLDivElement, CardProps>(function Card(pr
const defaultView = isTypeContainer || isTypeSelection ? 'outlined' : undefined;

const handleClick = isClickable ? onClick : undefined;
const {onKeyDown} = useActionHandlers(handleClick);
const {onKeyDown} = useActionHandlers(onClick);

return (
<div
Expand All @@ -85,7 +85,7 @@ export const Card = React.forwardRef<HTMLDivElement, CardProps>(function Card(pr
className,
)}
onClick={handleClick}
onKeyDown={onKeyDown}
onKeyDown={isClickable ? onKeyDown : undefined}
tabIndex={isClickable ? 0 : undefined}
data-qa={qa}
>
Expand Down
16 changes: 16 additions & 0 deletions src/components/Card/__tests__/Card.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,22 @@ describe('Card', () => {
expect(handleOnClick).toHaveBeenCalledTimes(0);
});

test('should not prevent keyboard events without handler', async () => {
render(
<Card>
<label>
Foobar <input />
</label>
</Card>,
);

const input = screen.getByLabelText('Foobar');

await userEvent.type(input, 'Test text with spaces');

expect(input).toHaveValue('Test text with spaces');
});

describe('should respond to clicks correctly', () => {
test('reacts to keystrokes if focused', async () => {
const user = userEvent.setup();
Expand Down
8 changes: 2 additions & 6 deletions src/components/utils/useActionHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,9 @@ interface UseActionHandlersResult<T> {
export function useActionHandlers<T>(callback?: AnyFunction): UseActionHandlersResult<T> {
const onKeyDown = React.useCallback(
(event: React.KeyboardEvent<T>) => {
if (['Enter', ' ', 'Spacebar'].includes(event.key)) {
event.preventDefault();

return callback?.(event);
if (callback && ['Enter', ' ', 'Spacebar'].includes(event.key)) {
callback(event);
}

return undefined;
},
[callback],
);
Expand Down

0 comments on commit e45c902

Please sign in to comment.