( onClick: MouseEventHandler<TElement>, role?: TRole, )
| 36 | * buttons. |
| 37 | */ |
| 38 | export const useClickable = < |
| 39 | TElement extends ClickableElement, |
| 40 | TRole extends ClickableAriaRole = ClickableAriaRole, |
| 41 | >( |
| 42 | onClick: MouseEventHandler<TElement>, |
| 43 | role?: TRole, |
| 44 | ): UseClickableResult<TElement, TRole> => { |
| 45 | const ref = useRef<TElement>(null); |
| 46 | |
| 47 | return { |
| 48 | ref, |
| 49 | onClick, |
| 50 | tabIndex: 0, |
| 51 | role: (role ?? "button") as TRole, |
| 52 | |
| 53 | /* |
| 54 | * Native buttons are programmed to handle both space and enter, but they're |
| 55 | * each handled via different event handlers. |
| 56 | * |
| 57 | * 99% of the time, you shouldn't be able to tell the difference, but one |
| 58 | * edge case behavior is that holding down Enter will continually fire |
| 59 | * events, while holding down Space won't fire anything until you let go. |
| 60 | */ |
| 61 | onKeyDown: (event) => { |
| 62 | if (event.key === "Enter") { |
| 63 | ref.current?.click(); |
| 64 | event.stopPropagation(); |
| 65 | } |
| 66 | }, |
| 67 | onKeyUp: (event) => { |
| 68 | if (event.key === " ") { |
| 69 | ref.current?.click(); |
| 70 | event.stopPropagation(); |
| 71 | } |
| 72 | }, |
| 73 | }; |
| 74 | }; |
no outgoing calls