UNPKG

@wordpress/components

Version:
91 lines (86 loc) 2.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _element = require("@wordpress/element"); var _compose = require("@wordpress/compose"); var _jsxRuntime = require("react/jsx-runtime"); /** * WordPress dependencies */ /** * Internal dependencies */ function KeyboardShortcut({ target, callback, shortcut, bindGlobal, eventName }) { (0, _compose.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 = (0, _element.useRef)(null); const element = Object.entries(shortcuts !== null && shortcuts !== void 0 ? shortcuts : {}).map(([shortcut, callback]) => /*#__PURE__*/(0, _jsxRuntime.jsx)(KeyboardShortcut, { shortcut: shortcut, callback: callback, bindGlobal: bindGlobal, eventName: eventName, target: target }, shortcut)); // Render as non-visual if there are no children pressed. Keyboard // events will be bound to the document instead. if (!_element.Children.count(children)) { return /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, { children: element }); } return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", { ref: target, children: [element, children] }); } var _default = exports.default = KeyboardShortcuts; //# sourceMappingURL=index.js.map