mirror of
https://github.com/remvze/moodist.git
synced 2025-12-17 08:54:13 +00:00
feat: allow using spacebar or enter to trigger buttons
It is a good practice for accessibility. Cf https://webaim.org/techniques/keyboard/ or any other resource on the Internet talking about buttons accessibiltiy.
This commit is contained in:
parent
42f82ab95d
commit
60cc2e9369
3 changed files with 31 additions and 8 deletions
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
19
src/hooks/useKeyboardButton.ts
Normal file
19
src/hooks/useKeyboardButton.ts
Normal 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;
|
||||
};
|
||||
Loading…
Add table
Reference in a new issue