import { useEffect , useState , useCallback } from 'react' ; import { Message } from '@proton/shared/lib/interfaces/mail/Message' ; import { useStore , useDispatch , useSelector } from 'react-redux' ; import { useGetElementsFromIDs } from '../mailbox/useElements' ; import { useGetConversation } from '../conversation/useConversation' ; import { MessageState } from '../../logic/messages/messagesTypes' ; import { RootState } from '../../logic/store' ; import { localID , messageByID } from '../../logic/messages/messagesSelectors' ; import { initialize } from '../../logic/messages/read/messagesReadActions' ; export const useGetLocalID = ( ) => { const store = useStore < RootState > ( ) ; return useCallback ( ( ID ) => localID ( store . getState ( ) , { ID } ) , [ ] ) ; } ; export const useGetMessage = ( ) => { const store = useStore < RootState > ( ) ; return useCallback ( ( ID ) => messageByID ( store . getState ( ) , { ID } ) , [ ] ) ; } ; interface ReturnValue { message : MessageState ; messageLoaded : boolean ; bodyLoaded : boolean ; } interface UseMessage { ( localID , conversationID ? ) : ReturnValue ; } export const useMessage = ( inputLocalID , conversationID = '' ) => { const dispatch = useDispatch ( ) ; const getLocalID = useGetLocalID ( ) ; const getElementsFromIDs = useGetElementsFromIDs ( ) ; const getMessage = useGetMessage ( ) ; const getConversationFromState = useGetConversation ( ) ; const messageState = useSelector ( ( state ) => messageByID ( state , { ID : inputLocalID } ) ) ; const initMessage = ( ) => { const localID = getLocalID ( inputLocalID ) ; const messageState = getMessage ( inputLocalID ) ; if ( messageState ) { return messageState ; } const [ messageFromElementsCache ] = getElementsFromIDs ( [ localID ] ) as Message [ ] ; const conversationState = getConversationFromState ( conversationID ) ; const messageFromConversationState = conversationState ?. Messages ?. find ( ( Message ) => Message . ID === localID ) ; const messageFromCache = messageFromElementsCache || messageFromConversationState ; const message = messageFromCache ? { localID , data : messageFromCache } : { localID } ; dispatch ( initialize ( message ) ) ; return message ; } ; const [ message , setMessage ] = useState < MessageState > ( initMessage ) ; useEffect ( ( ) => { setMessage ( initMessage ( ) ) ; } , [ inputLocalID ] ) ; useEffect ( ( ) => { if ( messageState ) { setMessage ( messageState ) ; } } , [ messageState ] ) ; const messageLoaded = ! ! message . data ?. Subject ; const bodyLoaded = ! ! message . messageDocument ?. initialized ; return { message , messageLoaded , bodyLoaded } ; } ;