use-state-string.ts
1 import { useMemo } from 'react'; 2 import { useClientsStates } from '@plebbit/plebbit-react-hooks'; 3 4 interface CommentOrSubplebbit { 5 state?: string; 6 publishingState?: string; 7 updatingState?: string; 8 } 9 10 interface States { 11 [key: string]: string[]; 12 } 13 14 const clientHosts: { [key: string]: string } = {}; 15 16 const getClientHost = (clientUrl: string): string => { 17 if (!clientHosts[clientUrl]) { 18 try { 19 clientHosts[clientUrl] = new URL(clientUrl).hostname || clientUrl; 20 } catch (e) { 21 clientHosts[clientUrl] = clientUrl; 22 } 23 } 24 return clientHosts[clientUrl]; 25 }; 26 27 const useStateString = (commentOrSubplebbit: CommentOrSubplebbit): string | undefined => { 28 const { states } = useClientsStates({ comment: commentOrSubplebbit }) as { states: States }; 29 return useMemo(() => { 30 let stateString: string | undefined = ''; 31 32 for (const state in states) { 33 const clientUrls = states[state]; 34 const clientHosts = clientUrls.map((clientUrl) => getClientHost(clientUrl)); 35 36 if (clientHosts.length === 0) { 37 continue; 38 } 39 40 if (stateString) { 41 stateString += ', '; 42 } 43 44 const formattedState = state.replaceAll('-', ' ').replace('ipfs', 'IPFS').replace('ipns', 'IPNS'); 45 stateString += `${formattedState} from ${clientHosts.join(', ')}`; 46 } 47 48 if (!stateString && commentOrSubplebbit?.state !== 'succeeded') { 49 if (commentOrSubplebbit?.publishingState && commentOrSubplebbit?.publishingState !== 'stopped' && commentOrSubplebbit?.publishingState !== 'succeeded') { 50 stateString = commentOrSubplebbit.publishingState; 51 } else if (commentOrSubplebbit?.updatingState !== 'stopped' && commentOrSubplebbit?.updatingState !== 'succeeded') { 52 stateString = commentOrSubplebbit?.updatingState; 53 } 54 if (stateString) { 55 stateString = stateString.replaceAll('-', ' ').replace('ipfs', 'IPFS').replace('ipns', 'IPNS'); 56 } 57 } 58 59 if (stateString) { 60 stateString = stateString.charAt(0).toUpperCase() + stateString.slice(1); 61 } 62 63 return stateString === '' ? undefined : stateString; 64 }, [states, commentOrSubplebbit]); 65 }; 66 67 export default useStateString;