@wordpress/commands
Version:
Handles the commands menu.
65 lines (62 loc) • 1.71 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useCommand;
var _element = require("@wordpress/element");
var _data = require("@wordpress/data");
var _store = require("../store");
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Attach a command to the command palette. Used for static commands.
*
* @param {import('../store/actions').WPCommandConfig} command command config.
*
* @example
* ```js
* import { useCommand } from '@wordpress/commands';
* import { plus } from '@wordpress/icons';
*
* useCommand( {
* name: 'myplugin/my-command-name',
* label: __( 'Add new post' ),
* icon: plus,
* callback: ({ close }) => {
* document.location.href = 'post-new.php';
* close();
* },
* } );
* ```
*/
function useCommand(command) {
const {
registerCommand,
unregisterCommand
} = (0, _data.useDispatch)(_store.store);
const currentCallbackRef = (0, _element.useRef)(command.callback);
(0, _element.useEffect)(() => {
currentCallbackRef.current = command.callback;
}, [command.callback]);
(0, _element.useEffect)(() => {
if (command.disabled) {
return;
}
registerCommand({
name: command.name,
context: command.context,
label: command.label,
searchLabel: command.searchLabel,
icon: command.icon,
callback: (...args) => currentCallbackRef.current(...args)
});
return () => {
unregisterCommand(command.name);
};
}, [command.name, command.label, command.searchLabel, command.icon, command.context, command.disabled, registerCommand, unregisterCommand]);
}
//# sourceMappingURL=use-command.js.map
;