All files / hooks/use-key-press/src useKeyPress.ts

94.56% Statements 87/92
86.25% Branches 69/80
100% Functions 11/11
94.5% Lines 86/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361                                      1x                   1x                                                                                                                                                                                                               94x   94x     94x   94x     94x       94x 94x 43x               94x                         94x 45x                                         94x 47x 50x           94x   4x 4x 4x 2x 2x 2x             94x   39x 39x 1x   38x 5x   33x 1x   33x 1x     33x 39x 31x       33x 33x     33x           33x           94x   16x 16x         16x 2x     2x     2x     2x 2x 2x           14x     14x 14x   14x   16x 10x 10x 10x 10x                     94x 3x 1x     2x     3x     94x 42x   2x 2x     40x 40x 1x     39x 42x   42x 37x   39x 37x         39x 42x   42x 39x 37x   39x 37x   39x                       94x    
import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import type { KeyPressTarget, UseKeyPressOptions } from "./types";
import {
  createMatcher,
  isEditableElement,
  isKeyPressSupported,
  resolveTarget,
} from "./utils";
 
// SSR-safe layout effect: sync refs before paint on the client, fall back to
// useEffect on the server (mirrors the house useEventListener pattern).
const useIsomorphicLayoutEffect =
  typeof window !== "undefined" ? useLayoutEffect : useEffect;
 
/** The four modifier flags tracked for a held trigger. */
type ModifierFlag = "ctrl" | "shift" | "alt" | "meta";
 
/**
 * Maps a modifier key's `event.key` value to the {@link ModifierFlag} it toggles.
 * Used on key-up to decide whether the released modifier was actually part of
 * the held trigger (releasing an unrelated modifier must not end the press).
 */
const MODIFIER_KEY_TO_FLAG: Record<string, ModifierFlag> = {
  Control: "ctrl",
  Shift: "shift",
  Alt: "alt",
  Meta: "meta",
};
 
/**
 * A React hook for detecting keyboard key presses, shortcuts, and combinations.
 *
 * Supports single keys (`"Escape"`), modifier combinations (`"mod+k"`,
 * `"ctrl+shift+s"`), multiple alternative bindings (`["ctrl+s", "meta+s"]`),
 * and custom predicates. The returned boolean reflects whether the target is
 * currently pressed (with `eventType: "both"`, the default).
 *
 * Features:
 * - Cross-platform `"mod"` alias (Ctrl on Windows/Linux, Cmd on macOS)
 * - Exact or loose modifier matching
 * - Match by logical key (`event.key`) or physical key (`event.code`)
 * - `onPress` / `onRelease` callbacks with the raw event (for `preventDefault`)
 * - Ignores auto-repeat and typing inside form fields (opt-in)
 * - Resets on window blur to avoid stuck-key state
 * - SSR compatible, with automatic listener cleanup
 *
 * @param target - The key(s) or predicate to detect. See {@link KeyPressTarget}.
 * @param options - Configuration options. See {@link UseKeyPressOptions}.
 * @returns `true` while the target key/combination is pressed.
 *
 * @example
 * ```tsx
 * // Single key state
 * function Modal({ onClose }: { onClose: () => void }) {
 *   const escapePressed = useKeyPress("Escape");
 *   useEffect(() => {
 *     if (escapePressed) onClose();
 *   }, [escapePressed, onClose]);
 *   return <div>Press Escape to close</div>;
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Cross-platform save shortcut with preventDefault
 * function Editor({ onSave }: { onSave: () => void }) {
 *   useKeyPress(["ctrl+s", "meta+s"], {
 *     preventDefault: true,
 *     onPress: () => onSave(),
 *   });
 *   return <textarea />;
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Command palette (mod = Ctrl on Win/Linux, Cmd on Mac)
 * function App() {
 *   const [open, setOpen] = useState(false);
 *   useKeyPress("mod+k", {
 *     preventDefault: true,
 *     onPress: () => setOpen((prev) => !prev),
 *   });
 *   return open ? <CommandPalette /> : null;
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Physical keys for game controls (layout-independent)
 * function Game() {
 *   const forward = useKeyPress("w", { matchBy: "code" });
 *   const left = useKeyPress("a", { matchBy: "code" });
 *   return <Player moving={forward} turningLeft={left} />;
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Predicate + scoped target
 * function NumericField() {
 *   const ref = useRef<HTMLInputElement>(null);
 *   const digitPressed = useKeyPress((e) => /^[0-9]$/.test(e.key), {
 *     target: ref,
 *   });
 *   return <input ref={ref} data-active={digitPressed} />;
 * }
 * ```
 */
export function useKeyPress(
  target: KeyPressTarget,
  options: UseKeyPressOptions = {}
): boolean {
  const {
    target: eventTarget,
    eventType = "both",
    enabled = true,
    preventDefault = false,
    stopPropagation = false,
    ignoreRepeat = true,
    ignoreInputElements = false,
    caseSensitive = false,
    matchBy = "key",
    exactModifiers = true,
    onPress,
    onRelease,
  } = options;
 
  const [pressed, setPressed] = useState(false);
 
  // Mirror of `pressed` for synchronous reads inside event handlers.
  const pressedRef = useRef(false);
  // The lower-cased `event.key` that established the current pressed state.
  const triggerKeyRef = useRef<string | null>(null);
  // Snapshot of the modifier state at the moment the trigger keydown matched.
  // Only modifiers that were held here should end the press when released.
  const triggerModifiersRef = useRef<Record<ModifierFlag, boolean> | null>(null);
 
  // Build the matcher once per distinct configuration. String/array targets are
  // parsed here; function targets are used as-is.
  const targetKey = typeof target === "function" ? target : JSON.stringify(target);
  const matcher = useMemo(
    () => createMatcher(target, matchBy, caseSensitive, exactModifiers),
    // `targetKey` captures the serialized/string-or-function identity of `target`.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [targetKey, matchBy, caseSensitive, exactModifiers]
  );
 
  // Keep the latest reactive config in a ref so the attached listeners never go
  // stale and never need to be re-registered when only callbacks/flags change.
  const configRef = useRef({
    matcher,
    eventType,
    preventDefault,
    stopPropagation,
    ignoreRepeat,
    ignoreInputElements,
    onPress,
    onRelease,
  });
  // Sync the latest config in a layout effect (not during render) so we never
  // mutate a ref while rendering — a render may be thrown away under concurrent
  // rendering / StrictMode. Listeners read `configRef.current` at event time.
  useIsomorphicLayoutEffect(() => {
    configRef.current = {
      matcher,
      eventType,
      preventDefault,
      stopPropagation,
      ignoreRepeat,
      ignoreInputElements,
      onPress,
      onRelease,
    };
  }, [
    matcher,
    eventType,
    preventDefault,
    stopPropagation,
    ignoreRepeat,
    ignoreInputElements,
    onPress,
    onRelease,
  ]);
 
  const setPressedState = useCallback((next: boolean) => {
    pressedRef.current = next;
    setPressed((prev) => (prev === next ? prev : next));
  }, []);
 
  // Clears any held state. When `releaseEvent` is supplied (window blur), fires
  // `onRelease` so onPress/onRelease stay balanced; when omitted (disable /
  // unsupported / unmount) it silently resets — see the onRelease JSDoc.
  const resetPressed = useCallback(
    (releaseEvent?: KeyboardEvent) => {
      triggerKeyRef.current = null;
      triggerModifiersRef.current = null;
      if (pressedRef.current) {
        setPressedState(false);
        Eif (releaseEvent) {
          configRef.current.onRelease?.(releaseEvent);
        }
      }
    },
    [setPressedState]
  );
 
  const handleKeyDown = useCallback(
    (event: KeyboardEvent) => {
      const config = configRef.current;
      if (config.ignoreInputElements && isEditableElement(event.target)) {
        return;
      }
      if (!config.matcher(event)) {
        return;
      }
      if (config.preventDefault) {
        event.preventDefault();
      }
      if (config.stopPropagation) {
        event.stopPropagation();
      }
 
      const isSuppressedRepeat = event.repeat && config.ignoreRepeat;
      if (!isSuppressedRepeat) {
        config.onPress?.(event);
      }
 
      // In keyup-only mode the pressed state is driven by key releases.
      Eif (config.eventType !== "keyup") {
        triggerKeyRef.current = event.key.toLowerCase();
        // Capture which modifiers were actually held when the trigger matched,
        // so key-up can tell a bare-key press from a modifier combination.
        triggerModifiersRef.current = {
          ctrl: event.ctrlKey,
          shift: event.shiftKey,
          alt: event.altKey,
          meta: event.metaKey,
        };
        setPressedState(true);
      }
    },
    [setPressedState]
  );
 
  const handleKeyUp = useCallback(
    (event: KeyboardEvent) => {
      const config = configRef.current;
      Iif (config.ignoreInputElements && isEditableElement(event.target)) {
        return;
      }
 
      // keyup-only mode: a matching release latches the pressed state.
      if (config.eventType === "keyup") {
        Iif (!config.matcher(event)) {
          return;
        }
        Iif (config.preventDefault) {
          event.preventDefault();
        }
        Iif (config.stopPropagation) {
          event.stopPropagation();
        }
        config.onRelease?.(event);
        setPressedState(true);
        return;
      }
 
      // "both" mode: release the held state when the primary key, or a modifier
      // that was actually part of the held trigger, is released. Releasing an
      // unrelated modifier (e.g. Shift while holding a bare "a") must NOT reset.
      Iif (!pressedRef.current) {
        return;
      }
      const released = event.key.toLowerCase();
      const modifierFlag = MODIFIER_KEY_TO_FLAG[event.key];
      const isTriggerModifierRelease =
        modifierFlag !== undefined &&
        triggerModifiersRef.current?.[modifierFlag] === true;
      if (released === triggerKeyRef.current || isTriggerModifierRelease) {
        triggerKeyRef.current = null;
        triggerModifiersRef.current = null;
        setPressedState(false);
        config.onRelease?.(event);
      }
    },
    [setPressedState]
  );
 
  // Focus left the window while a key was held: keyup will never arrive, so
  // reset. Fire onRelease with a synthetic keyup so onPress/onRelease stay
  // balanced instead of leaking a dangling press. Registered directly on the
  // blur event, so it must NOT be `resetPressed` (which would receive the raw
  // blur Event and mistake it for a KeyboardEvent).
  const handleBlur = useCallback(() => {
    if (!pressedRef.current) {
      return;
    }
    const synthetic =
      typeof KeyboardEvent !== "undefined"
        ? new KeyboardEvent("keyup")
        : undefined;
    resetPressed(synthetic);
  }, [resetPressed]);
 
  useEffect(() => {
    if (!isKeyPressSupported() || !enabled) {
      // Reset any lingering pressed state when disabled or unsupported.
      resetPressed();
      return;
    }
 
    const element = resolveTarget(eventTarget);
    if (!element) {
      return;
    }
 
    const listenDown = eventType === "both" || eventType === "keydown";
    const listenUp = eventType === "both" || eventType === "keyup";
 
    if (listenDown) {
      element.addEventListener("keydown", handleKeyDown as EventListener);
    }
    if (listenUp) {
      element.addEventListener("keyup", handleKeyUp as EventListener);
    }
 
    // Reset on blur so a key held while focus leaves the window/tab does not
    // remain "pressed" forever (keyup is never delivered in that case).
    const win = typeof window !== "undefined" ? window : null;
    win?.addEventListener("blur", handleBlur);
 
    return () => {
      if (listenDown) {
        element.removeEventListener("keydown", handleKeyDown as EventListener);
      }
      if (listenUp) {
        element.removeEventListener("keyup", handleKeyUp as EventListener);
      }
      win?.removeEventListener("blur", handleBlur);
    };
  }, [
    enabled,
    eventTarget,
    eventType,
    handleKeyDown,
    handleKeyUp,
    handleBlur,
    resetPressed,
  ]);
 
  return pressed;
}