import { useEffect, useRef } from 'react'; interface UseKeyboardOptions { enabled?: boolean; target?: EventTarget; } /** * Hook for handling keyboard events with automatic cleanup */ export function useKeyboard( handler: (event: KeyboardEvent) => void, options: UseKeyboardOptions = {} ) { const { enabled = true, target = document } = options; const handlerRef = useRef(handler); // Update handler ref when handler changes useEffect(() => { handlerRef.current = handler; }, [handler]); useEffect(() => { if (!enabled) return; const wrappedHandler = (event: KeyboardEvent) => { handlerRef.current(event); }; target.addEventListener('keydown', wrappedHandler); return () => target.removeEventListener('keydown', wrappedHandler); }, [enabled, target]); } /** * Hook for handling escape key with a callback */ export function useEscapeKey(onEscape: () => void, options: UseKeyboardOptions = {}) { const handleKeyDown = useCallback( (event: KeyboardEvent) => { if (event.key === 'Escape') { onEscape(); } }, [onEscape] ); useKeyboard(handleKeyDown, options); }