import { ChatClientState , StatefulChatClient } from '@internal/chat-stateful-client' ; import { ChatClientContext } from '../providers/ChatClientProvider' ; import { useState , useEffect , useRef , useMemo , useContext } from 'react' ; import { ChatThreadClientContext } from '../providers/ChatThreadClientProvider' ; public export const useSelector = < SelectorT extends ( state : ChatClientState , props : any ) => any , ParamT extends SelectorT | undefined > ( selector , selectorProps ? ) : ParamT extends SelectorT ? ReturnType < SelectorT > : undefined => { const chatClient = useContext ( ChatClientContext ) ; const threadId = useContext ( ChatThreadClientContext ) ?. threadId ; const mounted = useRef ( false ) ; useEffect ( ( ) => { mounted . current = true ; return ( ) => { mounted . current = false ; } ; } ) ; const threadConfigProps = useMemo ( ( ) => ( { threadId } ) , [ threadId ] ) ; const [ props , setProps ] = useState ( chatClient && selector ? selector ( chatClient . getState ( ) , selectorProps ?? threadConfigProps ) : undefined ) ; const propRef = useRef ( props ) ; propRef . current = props ; useEffect ( ( ) => { if ( ! chatClient || ! selector ) { return ; } const onStateChange = ( state ) : void => { const newProps = selector ( state , selectorProps ?? threadConfigProps ) ; if ( propRef . current !== newProps ) { setProps ( newProps ) ; } } ; chatClient . onStateChange ( onStateChange ) ; return ( ) => { chatClient . offStateChange ( onStateChange ) ; } ; } , [ chatClient , selector , selectorProps , threadConfigProps ] ) ; return selector ? props : undefined ; } ;