|
1 |
| -import { KeyboardEvent } from "react"; |
| 1 | +import { |
| 2 | + type KeyboardEventHandler, |
| 3 | + type MouseEventHandler, |
| 4 | + type RefObject, |
| 5 | + useRef, |
| 6 | +} from "react"; |
2 | 7 |
|
3 |
| -export interface UseClickableResult { |
| 8 | +// Literally any object (ideally an HTMLElement) that has a .click method |
| 9 | +type ClickableElement = { |
| 10 | + click: () => void; |
| 11 | +}; |
| 12 | + |
| 13 | +export interface UseClickableResult< |
| 14 | + T extends ClickableElement = ClickableElement, |
| 15 | +> { |
| 16 | + ref: RefObject<T>; |
4 | 17 | tabIndex: 0;
|
5 | 18 | role: "button";
|
6 |
| - onClick: () => void; |
7 |
| - onKeyDown: (event: KeyboardEvent) => void; |
| 19 | + onClick: MouseEventHandler<T>; |
| 20 | + onKeyDown: KeyboardEventHandler<T>; |
8 | 21 | }
|
9 | 22 |
|
10 |
| -export const useClickable = (onClick: () => void): UseClickableResult => { |
| 23 | +/** |
| 24 | + * Exposes props to add basic click/interactive behavior to HTML elements that |
| 25 | + * don't traditionally have support for them. |
| 26 | + */ |
| 27 | +export const useClickable = < |
| 28 | + // T doesn't have a default type on purpose; the hook should error out if it |
| 29 | + // doesn't have an explicit type, or a type it can infer from onClick |
| 30 | + T extends ClickableElement, |
| 31 | +>( |
| 32 | + // Even though onClick isn't used in any of the internal calculations, it's |
| 33 | + // still a required argument, just to make sure that useClickable can't |
| 34 | + // accidentally be called in a component without also defining click behavior |
| 35 | + onClick: MouseEventHandler<T>, |
| 36 | +): UseClickableResult<T> => { |
| 37 | + const ref = useRef<T>(null); |
| 38 | + |
11 | 39 | return {
|
| 40 | + ref, |
12 | 41 | tabIndex: 0,
|
13 | 42 | role: "button",
|
14 | 43 | onClick,
|
15 |
| - onKeyDown: (event: KeyboardEvent) => { |
16 |
| - if (event.key === "Enter") { |
17 |
| - onClick(); |
| 44 | + |
| 45 | + // Most interactive elements automatically make Space/Enter trigger onClick |
| 46 | + // callbacks, but you explicitly have to add it for non-interactive elements |
| 47 | + onKeyDown: (event) => { |
| 48 | + if (event.key === "Enter" || event.key === " ") { |
| 49 | + // Can't call onClick from here because onKeydown's keyboard event isn't |
| 50 | + // compatible with mouse events. Have to use a ref to simulate a click |
| 51 | + ref.current?.click(); |
| 52 | + event.stopPropagation(); |
18 | 53 | }
|
19 | 54 | },
|
20 | 55 | };
|
|
0 commit comments