react-use-record-hotkey
Version:
148 lines (143 loc) • 7.14 kB
JavaScript
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { useEventListener } from 'ahooks';
import React, { useRef, useState } from 'react';
import { mapKey } from "./parseHotkeys";
var MODIFIERS = ['ctrl', 'meta', 'alt', 'shift'];
var allowedChars = ['backquote', 'space', 'enter', 'minus', 'plus', 'equal', 'backspace', 'escape', 'pageup', 'pagedown', 'home', 'end', 'delete', 'tab', 'bracketleft', 'bracketright', 'semicolon', 'quote', 'comma', 'period', 'slash', 'backslash', 'up', 'down', 'left', 'right'];
var verify = function verify(hotkey) {
var hasModifier = MODIFIERS.some(function (modifier) {
return hotkey.has(modifier);
});
var hasNormalKey = Array.from(hotkey).some(function (key) {
return !MODIFIERS.includes(key);
});
return hasModifier && hasNormalKey;
};
// #region record-option
// #endregion record-option
/**
* Record hotkey from input element
* @see https://github.com/Wxh16144/react-record-hotkey.git
* @example
* ```tsx
* const [inputRef, keys, { start, stop, isRecording }] = useRecordHotkey({
* onClean: () => {
* console.log('Clean');
* },
* onConfirm: (hotkey) => {
* console.log(`Hotkey: ${Array.from(hotkey).join('+')}`);
* },
* });
*
* const hotkey = Array.from(keys).join('+');
*
* return (
* <div>
* <input ref={inputRef} autoFocus readOnly value={hotkey} />
* <button onClick={start}>Start</button>
* <button onClick={stop}>Stop</button>
* <p>Recording: {isRecording ? 'Yes' : 'No'}</p>
* <p>Hotkey: {hotkey}</p>
* </div>
* );
* ```
**/
var useRecordHotkey = function useRecordHotkey(opt) {
var _ref = opt || {},
onClean = _ref.onClean,
onConfirm = _ref.onConfirm,
_ref$startOnEnter = _ref.startOnEnter,
startOnEnter = _ref$startOnEnter === void 0 ? true : _ref$startOnEnter;
var ref = useRef(null);
var blurRef = useRef();
var _useState = useState(new Set()),
_useState2 = _slicedToArray(_useState, 2),
keys = _useState2[0],
setKeys = _useState2[1];
var _useState3 = useState(false),
_useState4 = _slicedToArray(_useState3, 2),
isRecording = _useState4[0],
setIsRecording = _useState4[1];
var reset = function reset() {
setKeys(new Set());
blurRef.current = null;
};
var start = React.useCallback(function () {
var _ref$current, _ref$current$focus;
reset();
setIsRecording(true);
(_ref$current = ref.current) === null || _ref$current === void 0 ? void 0 : (_ref$current$focus = _ref$current.focus) === null || _ref$current$focus === void 0 ? void 0 : _ref$current$focus.call(_ref$current);
}, []);
var stop = React.useCallback(function () {
var _ref$current2, _ref$current2$blur;
reset();
setIsRecording(false);
(_ref$current2 = ref.current) === null || _ref$current2 === void 0 ? void 0 : (_ref$current2$blur = _ref$current2.blur) === null || _ref$current2$blur === void 0 ? void 0 : _ref$current2$blur.call(_ref$current2);
}, []);
var isValid = verify(keys);
useEventListener('blur', function () {
setIsRecording(false);
if (isValid && blurRef.current !== 'escape') {
onConfirm === null || onConfirm === void 0 ? void 0 : onConfirm(keys);
} else {
onClean === null || onClean === void 0 ? void 0 : onClean();
reset();
}
blurRef.current = null;
}, {
target: ref
});
// useEventListener('focus', start, { target: ref });
useEventListener('keydown', function (event) {
var key = mapKey(event.code);
var someModifierIsPressed = MODIFIERS.some(function (key) {
return event["".concat(key, "Key")];
});
if (!isRecording) {
if (key === 'enter' && startOnEnter) {
start();
}
return;
}
event.stopPropagation();
event.preventDefault();
if (['escape', 'enter'].includes(key) && !someModifierIsPressed) {
var _event$target, _event$target$blur;
setIsRecording(false);
blurRef.current = key;
(_event$target = event.target) === null || _event$target === void 0 ? void 0 : (_event$target$blur = _event$target.blur) === null || _event$target$blur === void 0 ? void 0 : _event$target$blur.call(_event$target);
return;
}
// Define allowed keys
var keyIsAlphaNum = event.keyCode >= 48 && event.keyCode <= 90; // 48-90 is a-z, A-Z, 0-9
var keyIsBetweenF1andF12 = event.keyCode >= 112 && event.keyCode <= 123; // 112-123 is F1-F12
var keyIsAllowedChar = allowedChars.includes(key);
var modifiers = new Set(MODIFIERS.filter(function (key) {
return event["".concat(key, "Key")];
}));
if (modifiers.size > 0) {
var normalKey = (keyIsAlphaNum || keyIsBetweenF1andF12 || keyIsAllowedChar) && key;
setKeys(new Set([].concat(_toConsumableArray(Array.from(modifiers)), [normalKey]).filter(Boolean)));
} else {
reset();
}
}, {
target: ref
});
return [ref, keys, {
start: start,
stop: stop,
reset: reset,
isRecording: isRecording
}];
};
export default useRecordHotkey;