UNPKG

@wordpress/commands

Version:
87 lines (86 loc) 2.28 kB
// packages/commands/src/hooks/use-command.js import { useEffect, useRef } from "@wordpress/element"; import { useDispatch } from "@wordpress/data"; import { store as commandsStore } from "../store"; function useCommand(command) { const { registerCommand, unregisterCommand } = useDispatch(commandsStore); const currentCallbackRef = useRef(command.callback); useEffect(() => { currentCallbackRef.current = command.callback; }, [command.callback]); useEffect(() => { if (command.disabled) { return; } registerCommand({ name: command.name, context: command.context, label: command.label, searchLabel: command.searchLabel, icon: command.icon, keywords: command.keywords, callback: (...args) => currentCallbackRef.current(...args) }); return () => { unregisterCommand(command.name); }; }, [ command.name, command.label, command.searchLabel, command.icon, command.context, command.keywords, command.disabled, registerCommand, unregisterCommand ]); } function useCommands(commands) { const { registerCommand, unregisterCommand } = useDispatch(commandsStore); const currentCallbacksRef = useRef({}); useEffect(() => { if (!commands) { return; } commands.forEach((command) => { if (command.callback) { currentCallbacksRef.current[command.name] = command.callback; } }); }, [commands]); useEffect(() => { if (!commands) { return; } commands.forEach((command) => { if (command.disabled) { return; } registerCommand({ name: command.name, context: command.context, label: command.label, searchLabel: command.searchLabel, icon: command.icon, keywords: command.keywords, callback: (...args) => { const callback = currentCallbacksRef.current[command.name]; if (callback) { callback(...args); } } }); }); return () => { commands.forEach((command) => { unregisterCommand(command.name); }); }; }, [commands, registerCommand, unregisterCommand]); } export { useCommand, useCommands }; //# sourceMappingURL=use-command.js.map