@wordpress/components
Version:
UI components for WordPress.
60 lines (59 loc) • 1.87 kB
JavaScript
import { Children, useRef } from "@wordpress/element";
import { useKeyboardShortcut } from "@wordpress/compose";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
// packages/components/src/keyboard-shortcuts/index.tsx
function KeyboardShortcut({ target, callback, shortcut, bindGlobal, eventName }) {
useKeyboardShortcut(shortcut, callback, {
bindGlobal,
target,
eventName
});
return null;
}
/**
* `KeyboardShortcuts` is a component which handles keyboard sequences during the lifetime of the rendering element.
*
* When passed children, it will capture key events which occur on or within the children. If no children are passed, events are captured on the document.
*
* It uses the [Mousetrap](https://craig.is/killing/mice) library to implement keyboard sequence bindings.
*
* ```jsx
* import { KeyboardShortcuts } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyKeyboardShortcuts = () => {
* const [ isAllSelected, setIsAllSelected ] = useState( false );
* const selectAll = () => {
* setIsAllSelected( true );
* };
*
* return (
* <div>
* <KeyboardShortcuts
* shortcuts={ {
* 'mod+a': selectAll,
* } }
* />
* [cmd/ctrl + A] Combination pressed? { isAllSelected ? 'Yes' : 'No' }
* </div>
* );
* };
* ```
*/
function KeyboardShortcuts({ children, shortcuts, bindGlobal, eventName }) {
const target = useRef(null);
const element = Object.entries(shortcuts ?? {}).map(([shortcut, callback]) => /* @__PURE__ */ jsx(KeyboardShortcut, {
shortcut,
callback,
bindGlobal,
eventName,
target
}, shortcut));
if (!Children.count(children)) return /* @__PURE__ */ jsx(Fragment, { children: element });
return /* @__PURE__ */ jsxs("div", {
ref: target,
children: [element, children]
});
}
export { KeyboardShortcuts as default };
//# sourceMappingURL=index.mjs.map