UNPKG

1.36 kBJavaScriptView Raw
1"use strict";
2var __importStar = (this && this.__importStar) || function (mod) {
3 if (mod && mod.__esModule) return mod;
4 var result = {};
5 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6 result["default"] = mod;
7 return result;
8};
9Object.defineProperty(exports, "__esModule", { value: true });
10var React = __importStar(require("react"));
11exports.useIsomorphicEffect = typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;
12function runKeyHandler(e, keyHandlers) {
13 var handler = keyHandlers[e.key];
14 if (handler) {
15 handler();
16 // if event was handled prevent other side effects (e.g. page scroll)
17 e.preventDefault();
18 }
19}
20exports.runKeyHandler = runKeyHandler;
21function useKeyDown(active, keyHandlers) {
22 var keyHandlersRef = React.useRef(keyHandlers);
23 keyHandlersRef.current = keyHandlers;
24 exports.useIsomorphicEffect(function () {
25 if (active) {
26 var handleKeyDown_1 = function (event) {
27 runKeyHandler(event, keyHandlersRef.current);
28 };
29 window.addEventListener('keydown', handleKeyDown_1);
30 return function () {
31 window.removeEventListener('keydown', handleKeyDown_1);
32 };
33 }
34 }, [active]);
35}
36exports.useKeyDown = useKeyDown;