@wordpress/compose
Version:
WordPress higher-order components (HOCs).
61 lines (60 loc) • 2.19 kB
JavaScript
// packages/compose/src/hooks/use-keyboard-shortcut/index.js
import Mousetrap from "mousetrap";
import "mousetrap/plugins/global-bind/mousetrap-global-bind";
import { useEffect, useRef } from "@wordpress/element";
import { isAppleOS } from "@wordpress/keycodes";
function useKeyboardShortcut(shortcuts, callback, {
bindGlobal = false,
eventName = "keydown",
isDisabled = false,
// This is important for performance considerations.
target
} = {}) {
const currentCallbackRef = useRef(callback);
useEffect(() => {
currentCallbackRef.current = callback;
}, [callback]);
useEffect(() => {
if (isDisabled) {
return;
}
const mousetrap = new Mousetrap(
target && target.current ? target.current : (
// We were passing `document` here previously, so to successfully cast it to Element we must cast it first to `unknown`.
// Not sure if this is a mistake but it was the behavior previous to the addition of types so we're just doing what's
// necessary to maintain the existing behavior.
/** @type {Element} */
/** @type {unknown} */
document
)
);
const shortcutsArray = Array.isArray(shortcuts) ? shortcuts : [shortcuts];
shortcutsArray.forEach((shortcut) => {
const keys = shortcut.split("+");
const modifiers = new Set(
keys.filter((value) => value.length > 1)
);
const hasAlt = modifiers.has("alt");
const hasShift = modifiers.has("shift");
if (isAppleOS() && (modifiers.size === 1 && hasAlt || modifiers.size === 2 && hasAlt && hasShift)) {
throw new Error(
`Cannot bind ${shortcut}. Alt and Shift+Alt modifiers are reserved for character input.`
);
}
const bindFn = bindGlobal ? "bindGlobal" : "bind";
mousetrap[bindFn](
shortcut,
(...args) => currentCallbackRef.current(...args),
eventName
);
});
return () => {
mousetrap.reset();
};
}, [shortcuts, bindGlobal, eventName, target, isDisabled]);
}
var use_keyboard_shortcut_default = useKeyboardShortcut;
export {
use_keyboard_shortcut_default as default
};
//# sourceMappingURL=index.js.map