Skip to content

Commit

Permalink
feat: allow using spacebar or enter to trigger buttons
Browse files Browse the repository at this point in the history
It is a good practice for accessibility.
Cf https://webaim.org/techniques/keyboard/ or
any other resource on the Internet talking about buttons accessibiltiy.
  • Loading branch information
SuperMeepBoy committed Apr 23, 2024
1 parent 42f82ab commit 60cc2e9
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 8 deletions.
7 changes: 7 additions & 0 deletions src/components/sound/favorite/favorite.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { fade } from '@/lib/motion';

import styles from './favorite.module.css';

import { useKeyboardButton } from '@/hooks/useKeyboardButton';

interface FavoriteProps {
id: string;
}
Expand All @@ -17,11 +19,16 @@ export function Favorite({ id }: FavoriteProps) {

const variants = fade();

const handleKeyDown = useKeyboardButton(() => {
toggleFavorite(id);
});

return (
<AnimatePresence initial={false} mode="wait">
<button
aria-label="Add Sound to Favorites"
className={cn(styles.favoriteButton, isFavorite && styles.isFavorite)}
onKeyDown={handleKeyDown}
onClick={e => {
e.stopPropagation();
toggleFavorite(id);
Expand Down
13 changes: 5 additions & 8 deletions src/components/sound/sound.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import styles from './sound.module.css';

import type { Sound } from '@/data/types';

import { useKeyboardButton } from '@/hooks/useKeyboardButton';

interface SoundProps extends Sound {
functional: boolean;
hidden: boolean;
Expand Down Expand Up @@ -73,14 +75,9 @@ export function Sound({
toggle();
}, [toggle]);

const handleKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'Enter') {
toggle();
}
},
[toggle],
);
const handleKeyDown = useKeyboardButton(() => {
toggle();
});

return (
<div
Expand Down
19 changes: 19 additions & 0 deletions src/hooks/useKeyboardButton.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useCallback } from 'react';
import type { KeyboardEvent } from 'react';

export const useKeyboardButton = (
actionCallback: () => void,
): ((event: KeyboardEvent<HTMLElement>) => void) => {
const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLElement>) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
actionCallback();
event.stopPropagation();
}
},
[actionCallback],
);

return handleKeyDown;
};

0 comments on commit 60cc2e9

Please sign in to comment.