import { CallClientState , StatefulCallClient } from '@internal/calling-stateful-client' ; import { CallClientContext , useCall } from '../providers' ; import { useState , useEffect , useRef , useMemo , useContext } from 'react' ; public export const useSelector = < SelectorT extends ( state : CallClientState , props : any ) => any , ParamT extends SelectorT | undefined > ( selector , selectorProps ? ) : ParamT extends SelectorT ? ReturnType < SelectorT > : undefined => { const callClient = useContext ( CallClientContext ) ?. callClient ; const callId = useCall ( ) ?. id ; const mounted = useRef ( false ) ; useEffect ( ( ) => { mounted . current = true ; return ( ) => { mounted . current = false ; } ; } ) ; const callIdConfigProps = useMemo ( ( ) => ( { callId } ) , [ callId ] ) ; const [ props , setProps ] = useState ( callClient && selector ? selector ( callClient . getState ( ) , selectorProps ?? callIdConfigProps ) : undefined ) ; const propRef = useRef ( props ) ; propRef . current = props ; useEffect ( ( ) => { if ( ! callClient || ! selector ) { return ; } const onStateChange = ( state ) : void => { if ( ! mounted . current ) { return ; } const newProps = selector ( state , selectorProps ?? callIdConfigProps ) ; if ( propRef . current !== newProps ) { setProps ( newProps ) ; } } ; callClient . onStateChange ( onStateChange ) ; return ( ) => { callClient . offStateChange ( onStateChange ) ; } ; } , [ callClient , selector , selectorProps , callIdConfigProps , mounted ] ) ; return selector ? props : undefined ; } ;