import { useCallback } from 'react'; /** * Augments a component with default action handling. Default action refers to * the action produced by button-like interaction with the UI element: click or * space / enter key press * * @param onDefaultAction Action callback * @returns Props that should be passed to the component */ export function useDefaultAction( onDefaultAction: (evt: React.KeyboardEvent | React.MouseEvent) => void ): React.HTMLAttributes { const onClick = useCallback( (evt: React.MouseEvent) => { evt.stopPropagation(); onDefaultAction(evt); }, [onDefaultAction] ); const onKeyDown = useCallback( (evt: React.KeyboardEvent) => { if ( // Only handle keyboard events if they originated on the element evt.target === evt.currentTarget && [' ', 'Enter'].includes(evt.key) ) { evt.preventDefault(); evt.stopPropagation(); onDefaultAction(evt); } }, [onDefaultAction] ); return { onClick, onKeyDown }; }