UNPKG

shortcut-key-sensor

Version:
64 lines (58 loc) 1.89 kB
import { useEffect, useCallback } from 'react'; var specialKeys = [{ key: "ctrlKey", original: "CONTROL", value: "CTRL" }, { key: "altKey", original: "ALT", value: "ALT" }, { key: "shiftKey", original: "SHIFT", value: "SHIFT" }]; function convertToStringPressedKeys(event) { var pressedKey = specialKeys.filter(function (specialKey) { return event[specialKey.key]; }).map(function (specialKey) { return specialKey.value; }); var keyPressed = event.key.toUpperCase(); var keyPressedIsSpecial = specialKeys.find(function (key) { return key.original === keyPressed; }); !keyPressedIsSpecial && pressedKey.push(keyPressed); return pressedKey.join("+"); } function ShortcutKeySensor(_ref) { var actions = _ref.actions, children = _ref.children; var handleKeyDown = function handleKeyDown(event) { var combinationKeys = convertToStringPressedKeys(event); var matchWithPressedKey = Object.prototype.hasOwnProperty.call(actions, combinationKeys); matchWithPressedKey && actions[combinationKeys](event); }; useEffect(function () { window.addEventListener('keydown', handleKeyDown); return function () { window.removeEventListener('keydown', handleKeyDown); }; }, []); return children; } var useShortcutKeySensor = function useShortcutKeySensor(combinationKeys, callback) { var memorizedCallback = useCallback(function (event) { var combinationPressedKeys = convertToStringPressedKeys(event); combinationPressedKeys === combinationKeys && callback(event); }, []); useEffect(function () { window.addEventListener('keydown', memorizedCallback); return function () { return window.removeEventListener('keydown', memorizedCallback); }; }, [memorizedCallback]); }; export default ShortcutKeySensor; export { useShortcutKeySensor }; //# sourceMappingURL=index.modern.js.map