Merge pull request #26 from SuperMeepBoy/improve-accessibility-2

Allow using spacebar or enter to trigger buttons
This commit is contained in:
MAZE ✧ 2024-04-23 23:08:53 +03:30 committed by GitHub
commit ab9d47befb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 31 additions and 8 deletions

View file

@ -7,6 +7,8 @@ import { fade } from '@/lib/motion';
import styles from './favorite.module.css';
import { useKeyboardButton } from '@/hooks/useKeyboardButton';
interface FavoriteProps {
id: string;
}
@ -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);

View file

@ -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;
@ -73,14 +75,9 @@ export function Sound({
toggle();
}, [toggle]);
const handleKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'Enter') {
const handleKeyDown = useKeyboardButton(() => {
toggle();
}
},
[toggle],
);
});
return (
<div

View file

@ -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;
};