Files
5chan/src/hooks/use-state-string.ts
T

81 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-03-22 14:15:35 +01:00
import { useMemo } from 'react';
import { useClientsStates } from '@plebbit/plebbit-react-hooks';
import { debounce } from 'lodash';
2024-03-22 14:15:35 +01:00
interface CommentOrSubplebbit {
state?: string;
publishingState?: string;
updatingState?: string;
}
interface States {
[key: string]: string[];
}
const clientHosts: { [key: string]: string } = {};
const getClientHost = (clientUrl: string): string => {
if (!clientHosts[clientUrl]) {
try {
clientHosts[clientUrl] = new URL(clientUrl).hostname || clientUrl;
} catch (e) {
clientHosts[clientUrl] = clientUrl;
}
}
return clientHosts[clientUrl];
};
const useStateString = (commentOrSubplebbit: CommentOrSubplebbit): string | undefined => {
const { states: rawStates } = useClientsStates({ comment: commentOrSubplebbit }) as { states: States };
const debouncedStates = useMemo(() => {
const debouncedValue = debounce((value: States) => value, 300);
return debouncedValue(rawStates);
}, [rawStates]);
2024-03-22 14:15:35 +01:00
return useMemo(() => {
let stateString: string | undefined = '';
for (const state in debouncedStates) {
const clientUrls = debouncedStates[state];
const clientHosts = clientUrls.map((clientUrl: string) => getClientHost(clientUrl));
2024-03-22 14:15:35 +01:00
if (clientHosts.length === 0) {
continue;
}
if (stateString) {
stateString += ', ';
}
const formattedState = state.replaceAll('-', ' ').replace('ipfs', 'IPFS').replace('ipns', 'IPNS');
stateString += `${formattedState} from ${clientHosts.join(', ')}`;
}
if (!stateString && commentOrSubplebbit?.state !== 'succeeded') {
if (commentOrSubplebbit?.publishingState && commentOrSubplebbit?.publishingState !== 'stopped' && commentOrSubplebbit?.publishingState !== 'succeeded') {
stateString = commentOrSubplebbit.publishingState;
} else if (commentOrSubplebbit?.updatingState !== 'stopped' && commentOrSubplebbit?.updatingState !== 'succeeded') {
stateString = commentOrSubplebbit.updatingState;
2024-03-22 14:15:35 +01:00
}
if (stateString) {
stateString = stateString
.replaceAll('-', ' ')
2025-02-24 22:40:05 +01:00
.replace('ipfs', 'thread')
.replace('ipns', 'subplebbit')
2025-02-24 16:18:31 +01:00
.replace('fetching', 'downloading')
.replace('subplebbit subplebbit', 'board')
2025-02-24 16:18:31 +01:00
.replace('downloading subplebbit', 'downloading board');
2024-03-22 14:15:35 +01:00
}
}
if (stateString) {
stateString = stateString.charAt(0).toUpperCase() + stateString.slice(1);
}
return stateString === '' ? undefined : stateString;
}, [debouncedStates, commentOrSubplebbit]);
2024-03-22 14:15:35 +01:00
};
export default useStateString;