support ssr when build app

This commit is contained in:
Ren Amamiya
2023-04-24 13:43:45 +07:00
parent 98637feba4
commit 0a56b85492
10 changed files with 5 additions and 7 deletions
+90
View File
@@ -0,0 +1,90 @@
import { AccountContext } from '@components/accountProvider';
import { FormChannel } from '@components/form/channel';
import NewsfeedLayout from '@components/layouts/newsfeed';
import { RelayContext } from '@components/relaysProvider';
import { channelMessagesAtom, channelReplyAtom } from '@stores/channel';
import { MESSAGE_RELAYS } from '@stores/constants';
import { dateToUnix, hoursAgo } from '@utils/getDate';
import { usePageContext } from '@utils/hooks/usePageContext';
import { useSetAtom } from 'jotai';
import { useResetAtom } from 'jotai/utils';
import { Suspense, lazy, useContext, useRef } from 'react';
import useSWRSubscription from 'swr/subscription';
const ChannelMessages = lazy(() => import('@components/channels/messages'));
export function Page() {
const pageContext = usePageContext();
const searchParams: any = pageContext.urlParsed.search;
const id = searchParams.id;
const pool: any = useContext(RelayContext);
const activeAccount: any = useContext(AccountContext);
const setChannelMessages = useSetAtom(channelMessagesAtom);
const resetChannelMessages = useResetAtom(channelMessagesAtom);
const resetChannelReply = useResetAtom(channelReplyAtom);
const now = useRef(new Date());
const muted = useRef(new Set());
const hided = useRef(new Set());
useSWRSubscription(id, () => {
// reset channel reply
resetChannelReply();
// reset channel messages
resetChannelMessages();
// subscribe for new messages
const unsubscribe = pool.subscribe(
[
{
authors: [activeAccount.pubkey],
kinds: [43, 44],
since: dateToUnix(hoursAgo(48, now.current)),
},
{
'#e': [id],
kinds: [42],
since: dateToUnix(hoursAgo(48, now.current)),
},
],
MESSAGE_RELAYS,
(event: { kind: number; tags: string[][]; pubkey: string; id: string }) => {
if (event.kind === 44) {
muted.current = muted.current.add(event.tags[0][1]);
} else if (event.kind === 43) {
hided.current = hided.current.add(event.tags[0][1]);
} else {
if (muted.current.has(event.pubkey)) {
console.log('muted');
} else if (hided.current.has(event.id)) {
console.log('hided');
} else {
setChannelMessages((prev) => [...prev, event]);
}
}
}
);
return () => {
unsubscribe();
};
});
return (
<NewsfeedLayout>
<div className="flex h-full w-full flex-col justify-between">
<Suspense fallback={<p>Loading...</p>}>
<ChannelMessages />
</Suspense>
<div className="shrink-0 p-3">
<FormChannel eventId={id} />
</div>
</div>
</NewsfeedLayout>
);
}