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 | 1x 64x 64x 64x 64x 64x 64x 32x 64x 64x 64x 33x 33x 64x 3x 3x 1x 64x 30x 30x 1x 29x 4x 25x 1x 25x 25x 30x 23x 25x 25x 25x 64x 7x 7x 7x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 64x 31x 2x 2x 29x 29x 1x 28x 31x 31x 27x 28x 27x 28x 31x 31x 28x 27x 28x 27x 28x 64x | import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { KeyPressTarget, UseKeyPressOptions } from "./types";
import {
createMatcher,
isEditableElement,
isKeyPressSupported,
resolveTarget,
} from "./utils";
/**
* `event.key` values that represent modifier keys. Releasing any of these ends
* a held combination even if the primary key is still down.
*/
const MODIFIER_KEY_NAMES = new Set(["Control", "Shift", "Alt", "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);
// 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,
});
configRef.current = {
matcher,
eventType,
preventDefault,
stopPropagation,
ignoreRepeat,
ignoreInputElements,
onPress,
onRelease,
};
const setPressedState = useCallback((next: boolean) => {
pressedRef.current = next;
setPressed((prev) => (prev === next ? prev : next));
}, []);
const resetPressed = useCallback(() => {
triggerKeyRef.current = null;
if (pressedRef.current) {
setPressedState(false);
}
}, [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();
}
Iif (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();
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 any
// modifier that was part of the combination, is released.
Iif (!pressedRef.current) {
return;
}
const released = event.key.toLowerCase();
const isModifierRelease = MODIFIER_KEY_NAMES.has(event.key);
Eif (released === triggerKeyRef.current || isModifierRelease) {
triggerKeyRef.current = null;
setPressedState(false);
config.onRelease?.(event);
}
},
[setPressedState]
);
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", resetPressed);
return () => {
if (listenDown) {
element.removeEventListener("keydown", handleKeyDown as EventListener);
}
if (listenUp) {
element.removeEventListener("keyup", handleKeyUp as EventListener);
}
win?.removeEventListener("blur", resetPressed);
};
}, [enabled, eventTarget, eventType, handleKeyDown, handleKeyUp, resetPressed]);
return pressed;
}
|