import { useEffect } from 'react' import { AnyStateMachine, StateFrom } from 'xstate' import { Command, CommandBarMeta, createMachineCommand } from '../lib/commands' import { useCommandsContext } from './useCommandsContext' interface UseStateMachineCommandsArgs { state: StateFrom send: Function commandBarMeta?: CommandBarMeta commands: Command[] owner: string } export default function useStateMachineCommands({ state, send, commandBarMeta, owner, }: UseStateMachineCommandsArgs) { const { addCommands, removeCommands } = useCommandsContext() useEffect(() => { const newCommands = state.nextEvents .filter((e) => !['done.', 'error.'].some((n) => e.includes(n))) .map((type) => createMachineCommand({ type, state, send, commandBarMeta, owner, }) ) .filter((c) => c !== null) as Command[] addCommands(newCommands) return () => { removeCommands(newCommands) } }, [state]) }