import { useEffect } from 'react' ; import type { IExecutor , IExecutorHandler , IExecutorHandlersCollection } from '@cloudbeaver/core-executor' ; import { useObjectRef } from './useObjectRef' ; interface IUseExecutorOptions < T > { executor : IExecutor < T > | IExecutorHandlersCollection < T > ; handlers ? : Array < IExecutorHandler < T > > ; postHandlers ? : Array < IExecutorHandler < T > > ; } export function useExecutor < T > ( options ) { const props = useObjectRef ( options ) ; useEffect ( ( ) => { if ( ! props . executor ) { return ; } const handlers = [ ] ; const postHandlers = [ ] ; if ( props . handlers ) { for ( let i = 0 ; i < props . handlers . length ; i ++ ) { const handler = ( data , contexts ) => props . handlers ?. [ i ] ( data , contexts ) ; props . executor . addHandler ( handler ) ; handlers . push ( handler ) ; } } if ( props . postHandlers ) { for ( let i = 0 ; i < props . postHandlers . length ; i ++ ) { const handler = ( data , contexts ) => props . postHandlers ?. [ i ] ( data , contexts ) ; props . executor . addPostHandler ( handler ) ; postHandlers . push ( handler ) ; } } return ( ) => { for ( const handler of handlers ) { props . executor . removeHandler ( handler ) ; } for ( const handler of postHandlers ) { props . executor . removePostHandler ( handler ) ; } } ; } , [ props . executor , props . handlers ?. length , props . postHandlers ?. length ] ) ; }