UNPKG

@react-hookz/web

Version:

React hooks done right, for browser and SSR.

36 lines (35 loc) 1.61 kB
import { useMemo } from 'react'; import { useEventListener, useSyncedRef } from '..'; import { isBrowser } from "../util/const.js"; import { yieldFalse, yieldTrue } from "../util/misc.js"; var createKeyPredicate = function (keyFilter) { if (typeof keyFilter === 'function') return keyFilter; if (typeof keyFilter === 'string') return function (ev) { return ev.key === keyFilter; }; return keyFilter ? yieldTrue : yieldFalse; }; var WINDOW_OR_NULL = isBrowser ? window : null; /** * Executes callback when keyboard event occurred on target (window by default). * * @param keyOrPredicate Filters keypresses on which `callback` will be executed. * @param callback Function to call when key is pressed and `keyOrPredicate` matches positive. * @param deps Dependencies list that will be passed to underlying `useMemo`. * @param options Hook options. */ export function useKeyboardEvent(keyOrPredicate, callback, deps, options) { if (options === void 0) { options = {}; } var _a = options.event, event = _a === void 0 ? 'keydown' : _a, _b = options.target, target = _b === void 0 ? WINDOW_OR_NULL : _b, eventOptions = options.eventOptions; var cbRef = useSyncedRef(callback); var handler = useMemo(function () { var predicate = createKeyPredicate(keyOrPredicate); return function kbEventHandler(ev) { if (predicate(ev)) { cbRef.current.call(this, ev); } }; // eslint-disable-next-line react-hooks/exhaustive-deps }, deps); useEventListener(target, event, handler, eventOptions); }