(
isOpen: boolean,
onEscape: () => void,
options: {
preventDefault?: boolean
stopPropagation?: boolean
} = {},
)
| 7 | * @param options - Additional options for the hook |
| 8 | */ |
| 9 | export function useEscapeKey( |
| 10 | isOpen: boolean, |
| 11 | onEscape: () => void, |
| 12 | options: { |
| 13 | preventDefault?: boolean |
| 14 | stopPropagation?: boolean |
| 15 | } = {}, |
| 16 | ) { |
| 17 | const { preventDefault = true, stopPropagation = true } = options |
| 18 | |
| 19 | const handleKeyDown = useCallback( |
| 20 | (event: KeyboardEvent) => { |
| 21 | // Check isOpen inside the handler to ensure proper cleanup |
| 22 | if (event.key === "Escape" && isOpen) { |
| 23 | if (preventDefault) { |
| 24 | event.preventDefault() |
| 25 | } |
| 26 | if (stopPropagation) { |
| 27 | event.stopPropagation() |
| 28 | } |
| 29 | onEscape() |
| 30 | } |
| 31 | }, |
| 32 | [isOpen, onEscape, preventDefault, stopPropagation], |
| 33 | ) |
| 34 | |
| 35 | useEffect(() => { |
| 36 | // Always add the event listener to ensure proper cleanup on unmount |
| 37 | // The isOpen check is now inside the handler |
| 38 | window.addEventListener("keydown", handleKeyDown) |
| 39 | |
| 40 | return () => { |
| 41 | window.removeEventListener("keydown", handleKeyDown) |
| 42 | } |
| 43 | }, [handleKeyDown]) |
| 44 | } |
no outgoing calls
no test coverage detected