Merge pull request #467 from plebbit/development

Development
This commit is contained in:
Tom (plebeius.eth)
2024-08-06 22:45:52 +02:00
committed by GitHub
23 changed files with 614 additions and 234 deletions
+4 -2
View File
@@ -33,8 +33,10 @@ const BoardLayout = () => {
return <NotFound />;
}
// force rerender of post form when navigating between pages
const key = `${subplebbitAddress}-${location.pathname}`;
// force rerender of post form when navigating between pages, except when opening settings modal in current view
const key = location.pathname.endsWith('/settings')
? `${subplebbitAddress}-${location.pathname.replace(/\/settings$/, '')}`
: `${subplebbitAddress}-${location.pathname}`;
return (
<div className={styles.boardLayout}>
@@ -124,6 +124,7 @@
color: var(--catalog-post-preview-color);
font-family: arial, helvetica, sans-serif;
font-size: 10pt;
overflow: hidden;
}
.postPreview .postSubject {
+13 -5
View File
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Link, useLocation, useParams } from 'react-router-dom';
import { Comment, useAccount, useAuthorAvatar, useComment, useEditedComment } from '@plebbit/plebbit-react-hooks';
import { Comment, useAccount, useAccountComments, useAuthorAvatar, useComment, useEditedComment } from '@plebbit/plebbit-react-hooks';
import Plebbit from '@plebbit/plebbit-js/dist/browser/index.js';
import styles from '../../views/post/post.module.css';
import { getCommentMediaInfo, getDisplayMediaInfoType, getHasThumbnail } from '../../lib/utils/media-utils';
@@ -101,7 +101,7 @@ const PostInfo = ({ openReplyModal, post, postReplyCount = 0, roles, isHidden }:
</span>
{!(isDescription || isRules) && (
<>
{isReply && author?.avatar && (
{author?.avatar && (
<span className={styles.authorAvatar}>
<img src={avatarImageUrl} alt='' />
</span>
@@ -138,7 +138,7 @@ const PostInfo = ({ openReplyModal, post, postReplyCount = 0, roles, isHidden }:
<Link to={`/p/${subplebbitAddress}/c/${cid}`} className={styles.linkToPost} title={t('link_to_post')} onClick={(e) => !cid && e.preventDefault()}>
c/
</Link>
<span className={styles.replyToPost} title={t('reply_to_post')} onMouseDown={() => openReplyModal && openReplyModal(cid)}>
<span className={styles.replyToPost} title={t('reply_to_post')} onMouseDown={() => openReplyModal && openReplyModal(cid, postCid)}>
{shortCid}
</span>
</>
@@ -240,6 +240,7 @@ const PostMedia = ({ post }: PostProps) => {
const PostMessage = ({ post }: PostProps) => {
const { cid, content, deleted, edit, original, parentCid, postCid, reason, removed, state, subplebbitAddress } = post || {};
const { isDescription, isRules } = post || {}; // custom properties, not from api
// TODO: commentAuthor is not available outside of editedComment, update when available
// const banned = !!post?.commentAuthor?.banExpiresAt;
const { t } = useTranslation();
@@ -320,7 +321,11 @@ const PostMessage = ({ post }: PostProps) => {
{!isReply && content.length > 1000 && !isInPostView && (
<span className={styles.abbr}>
<br />
<Trans i18nKey={'comment_too_long'} shouldUnescape={true} components={{ 1: <Link to={`/p/${subplebbitAddress}/c/${cid}`} /> }} />
<Trans
i18nKey={'comment_too_long'}
shouldUnescape={true}
components={{ 1: <Link to={`/p/${subplebbitAddress}/${isDescription ? 'description' : isRules ? 'rules' : `c/${cid}`}`} /> }}
/>
</span>
)}
{!cid && state === 'pending' && stateString !== 'Failed' && (
@@ -378,6 +383,9 @@ const PostDesktop = ({ openReplyModal, post, roles, showAllReplies, showReplies
const visiblelinksCount = useCountLinksInReplies(post, 5);
const totalLinksCount = useCountLinksInReplies(post);
const replyCount = replies?.length;
const { accountComments } = useAccountComments();
const isPostInAccountComments = accountComments?.find((comment) => comment.cid === cid);
const repliesCount = pinned ? replyCount : replyCount - 5;
const linksCount = pinned ? totalLinksCount : totalLinksCount - visiblelinksCount;
const { showOmittedReplies, setShowOmittedReplies } = useShowOmittedReplies();
@@ -434,7 +442,7 @@ const PostDesktop = ({ openReplyModal, post, roles, showAllReplies, showReplies
)}
</span>
)}
{post?.replyCount === undefined && !isInPendingPostView && (
{post?.replyCount === undefined && !isPostInAccountComments && !isInPendingPostView && (
<span className={styles.loadingString}>
<LoadingEllipsis string={t('loading_comments')} />
</span>
@@ -89,6 +89,7 @@
.linkType {
font-weight: normal;
text-transform: lowercase;
}
.linkField input[type="text"] {
+112 -19
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import {
@@ -18,13 +18,17 @@ import { getLinkMediaInfo } from '../../lib/utils/media-utils';
import { isValidURL } from '../../lib/utils/url-utils';
import { isAllView, isDescriptionView, isPostPageView, isRulesView, isSubscriptionsView } from '../../lib/utils/view-utils';
import { useDefaultSubplebbitAddresses } from '../../hooks/use-default-subplebbits';
import useReply from '../../hooks/use-reply';
import usePublishReply from '../../hooks/use-publish-reply';
import useChallengesStore from '../../stores/use-challenges-store';
import styles from './post-form.module.css';
import _ from 'lodash';
import useIsSubplebbitOffline from '../../hooks/use-is-subplebbit-offline';
import useFetchGifFirstFrame from '../../hooks/use-fetch-gif-first-frame';
import useAnonMode from '../../hooks/use-anon-mode';
type SubmitState = {
author: any | undefined;
signer: any | undefined;
subplebbitAddress: string | undefined;
title: string | undefined;
content: string | undefined;
@@ -38,15 +42,19 @@ type SubmitState = {
const { addChallenge } = useChallengesStore.getState();
const useSubmitStore = create<SubmitState>((set) => ({
author: undefined,
signer: undefined,
subplebbitAddress: undefined,
title: undefined,
content: undefined,
link: undefined,
spoiler: undefined,
publishCommentOptions: {},
setSubmitStore: ({ subplebbitAddress, title, content, link, spoiler }) =>
setSubmitStore: ({ author, signer, subplebbitAddress, title, content, link, spoiler }) =>
set((state) => {
const nextState = { ...state };
if (author !== undefined) nextState.author = author;
if (signer !== undefined) nextState.signer = signer;
if (subplebbitAddress !== undefined) nextState.subplebbitAddress = subplebbitAddress;
if (title !== undefined) nextState.title = title || undefined;
if (content !== undefined) nextState.content = content || undefined;
@@ -54,7 +62,13 @@ const useSubmitStore = create<SubmitState>((set) => ({
if (spoiler !== undefined) nextState.spoiler = spoiler || undefined;
nextState.publishCommentOptions = {
...nextState,
author: nextState.author,
signer: nextState.signer,
subplebbitAddress: nextState.subplebbitAddress,
title: nextState.title,
content: nextState.content,
link: nextState.link,
spoiler: nextState.spoiler,
onChallenge: (...args: any) => addChallenge(args),
onChallengeVerification: alertChallengeVerificationFailed,
onError: (error: Error) => {
@@ -65,19 +79,39 @@ const useSubmitStore = create<SubmitState>((set) => ({
};
return nextState;
}),
resetSubmitStore: () => set({ subplebbitAddress: undefined, title: undefined, content: undefined, link: undefined, spoiler: undefined, publishCommentOptions: {} }),
resetSubmitStore: () =>
set({
author: undefined,
signer: undefined,
subplebbitAddress: undefined,
title: undefined,
content: undefined,
link: undefined,
spoiler: undefined,
publishCommentOptions: {},
}),
}));
export const LinkTypePreviewer = ({ link }: { link: string }) => {
const { t } = useTranslation();
const mediaInfo = getLinkMediaInfo(link);
return isValidURL(link) ? mediaInfo?.type : t('invalid_url');
let type = mediaInfo?.type;
const gifFrameUrl = useFetchGifFirstFrame(mediaInfo?.url);
if (type === 'gif' && gifFrameUrl !== null) {
type = t('animated_gif');
} else if (type === 'gif' && gifFrameUrl === null) {
type = t('static_gif');
}
return isValidURL(link) ? type : t('invalid_url');
};
const PostFormTable = ({ closeForm }: { closeForm: () => void }) => {
const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid: string }) => {
const { t } = useTranslation();
const account = useAccount();
const { displayName } = account?.author || {};
const author = account?.author || {};
const { displayName } = author || {};
const [url, setUrl] = useState('');
const { title, content, link, publishCommentOptions, setSubmitStore, resetSubmitStore } = useSubmitStore();
const { index, publishComment } = usePublishComment(publishCommentOptions);
@@ -92,6 +126,10 @@ const PostFormTable = ({ closeForm }: { closeForm: () => void }) => {
const subscriptions = account?.subscriptions || [];
const defaultSubplebbitAddresses = useDefaultSubplebbitAddresses();
const { anonMode, getNewSigner, getExistingSigner } = useAnonMode(postCid);
const comment = useComment({ commentCid: postCid });
const address = comment?.author?.address;
const resetFields = () => {
if (textRef.current) {
textRef.current.value = '';
@@ -104,13 +142,29 @@ const PostFormTable = ({ closeForm }: { closeForm: () => void }) => {
}
};
const onPublishPost = () => {
const hasCalledAnonAddressRef = useRef(false);
const getAnonAddressForPost = useCallback(async () => {
if (anonMode && !hasCalledAnonAddressRef.current) {
hasCalledAnonAddressRef.current = true;
const newSigner = (await getNewSigner()) || {};
setSubmitStore({
signer: newSigner,
author: {
displayName,
address: newSigner.address,
},
});
}
}, [anonMode, getNewSigner, setSubmitStore, displayName]);
const onPublishPost = async () => {
if (!title && !content && !link) {
alert(`Cannot post empty comment`);
return;
}
if (link && !isValidURL(link)) {
alert(`Invalid link`);
alert('The provided link is not a valid URL.');
return;
}
@@ -139,7 +193,32 @@ const PostFormTable = ({ closeForm }: { closeForm: () => void }) => {
// in post page, publish a reply to the post
const isInPostView = isPostPageView(location.pathname, params);
const cid = params?.commentCid as string;
const { setContent, resetContent, replyIndex, publishReply } = useReply({ cid, subplebbitAddress });
const { setPublishReplyOptions, resetPublishReplyOptions, replyIndex, publishReply } = usePublishReply({ cid, subplebbitAddress });
const getAnonAddressForReply = useCallback(async () => {
if (anonMode && !hasCalledAnonAddressRef.current) {
hasCalledAnonAddressRef.current = true;
const existingSigner = getExistingSigner(address);
if (existingSigner) {
setPublishReplyOptions({
signer: existingSigner,
author: {
displayName,
address: existingSigner.address,
},
});
} else {
const newSigner = await getNewSigner();
setPublishReplyOptions({
signer: newSigner,
author: {
displayName,
address: newSigner.address,
},
});
}
}
}, [address, getExistingSigner, getNewSigner, setPublishReplyOptions, displayName, anonMode]);
const onPublishReply = () => {
const currentContent = textRef.current?.value || '';
@@ -154,16 +233,27 @@ const PostFormTable = ({ closeForm }: { closeForm: () => void }) => {
alert('The provided link is not a valid URL.');
return;
}
publishReply();
};
useEffect(() => {
if (typeof replyIndex === 'number') {
resetContent();
resetPublishReplyOptions();
resetFields();
closeForm();
}
}, [replyIndex, resetContent, closeForm]);
}, [replyIndex, resetPublishReplyOptions, closeForm]);
useEffect(() => {
if (anonMode) {
if (isInPostView) {
getAnonAddressForReply();
} else {
getAnonAddressForPost();
}
}
}, [anonMode, getAnonAddressForPost, getAnonAddressForReply, isInPostView]);
return (
<table className={styles.postFormTable}>
@@ -205,7 +295,7 @@ const PostFormTable = ({ closeForm }: { closeForm: () => void }) => {
ref={textRef}
onChange={(e) => {
const content = e.target.value.replace(/\n/g, '\n\n');
isInPostView ? setContent.content(content) : setSubmitStore({ content });
isInPostView ? setPublishReplyOptions({ content }) : setSubmitStore({ content });
}}
/>
</td>
@@ -221,7 +311,7 @@ const PostFormTable = ({ closeForm }: { closeForm: () => void }) => {
ref={urlRef}
onChange={(e) => {
setUrl(e.target.value);
isInPostView ? setContent.link(e.target.value) : setSubmitStore({ link: e.target.value });
isInPostView ? setPublishReplyOptions({ link: e.target.value }) : setSubmitStore({ link: e.target.value });
}}
/>
<span className={styles.linkType}> {url && <LinkTypePreviewer link={url} />}</span>
@@ -232,7 +322,10 @@ const PostFormTable = ({ closeForm }: { closeForm: () => void }) => {
<td>
[
<label>
<input type='checkbox' onChange={(e) => (isInPostView ? setContent.spoiler(e.target.checked) : setSubmitStore({ spoiler: e.target.checked }))} />
<input
type='checkbox'
onChange={(e) => (isInPostView ? setPublishReplyOptions({ spoiler: e.target.checked }) : setSubmitStore({ spoiler: e.target.checked }))}
/>
{_.capitalize(t('spoiler'))}?
</label>
]
@@ -283,7 +376,7 @@ const PostForm = () => {
comment = editedComment;
}
const { deleted, locked, removed } = comment || {};
const { deleted, locked, removed, postCid } = comment || {};
const isThreadClosed = deleted || locked || removed || isInDescriptionView || isInRulesView;
const [showForm, setShowForm] = useState(false);
@@ -310,7 +403,7 @@ const PostForm = () => {
]
</div>
) : (
<PostFormTable closeForm={() => setShowForm(false)} />
<PostFormTable closeForm={() => setShowForm(false)} postCid={postCid} />
)}
</div>
<div className={styles.postFormMobile}>
@@ -326,7 +419,7 @@ const PostForm = () => {
<button className={`${styles.showFormButton} button`} onClick={() => setShowForm(showForm ? false : true)}>
{showForm ? t('close_post_form') : isInPostView ? t('post_a_reply') : t('start_new_thread')}
</button>
{showForm && <PostFormTable closeForm={() => setShowForm(false)} />}
{showForm && <PostFormTable closeForm={() => setShowForm(false)} postCid={postCid} />}
<hr />
</>
)}
+14 -4
View File
@@ -74,7 +74,7 @@ const PostInfoAndMedia = ({ openReplyModal, post, postReplyCount = 0, roles }: P
</span>
{!(isDescription || isRules) && (
<>
{isReply && author?.avatar && (
{author?.avatar && (
<span className={styles.authorAvatar}>
<img src={avatarImageUrl} alt='' />
</span>
@@ -127,7 +127,7 @@ const PostInfoAndMedia = ({ openReplyModal, post, postReplyCount = 0, roles }: P
<Link to={`/p/${subplebbitAddress}/c/${cid}`} className={styles.linkToPost} title={t('link_to_post')} onClick={(e) => !cid && e.preventDefault()}>
c/
</Link>
<span className={styles.replyToPost} title={t('reply_to_post')} onMouseDown={() => openReplyModal && openReplyModal(cid)}>
<span className={styles.replyToPost} title={t('reply_to_post')} onMouseDown={() => openReplyModal && openReplyModal(cid, postCid)}>
{shortCid}
</span>
</>
@@ -164,6 +164,7 @@ const ReplyBacklinks = ({ post }: PostProps) => {
const PostMessageMobile = ({ post }: PostProps) => {
const { t } = useTranslation();
const { cid, content, deleted, edit, original, parentCid, postCid, reason, removed, state, subplebbitAddress } = post || {};
const { isDescription, isRules } = post || {}; // custom properties, not from api
// TODO: commentAuthor is not available outside of editedComment, update when available
// const banned = !!post?.commentAuthor?.banExpiresAt;
const [showOriginal, setShowOriginal] = useState(false);
@@ -202,7 +203,12 @@ const PostMessageMobile = ({ post }: PostProps) => {
<span className={styles.editedInfo}>
{showOriginal && <Markdown content={original?.content} />}
<br />
{t('comment_edited_at_timestamp', { timestamp: getFormattedDate(edit?.timestamp), interpolation: { escapeValue: false } })}{' '}
<Trans
i18nKey={'comment_edited_at_timestamp'}
values={{ timestamp: getFormattedDate(edit?.timestamp) }}
shouldUnescape={true}
components={{ 1: <Tooltip content={getFormattedTimeAgo(edit?.timestamp)} children={<></>} /> }}
/>{' '}
{reason && <>{t('reason_reason', { reason: reason, interpolation: { escapeValue: false } })} </>}
{showOriginal ? (
<Trans
@@ -239,7 +245,11 @@ const PostMessageMobile = ({ post }: PostProps) => {
{!isReply && content.length > 1000 && !isInPostView && (
<span className={styles.abbr}>
<br />
<Trans i18nKey={'comment_too_long'} shouldUnescape={true} components={{ 1: <Link to={`/p/${subplebbitAddress}/c/${cid}`} /> }} />
<Trans
i18nKey={'comment_too_long'}
shouldUnescape={true}
components={{ 1: <Link to={`/p/${subplebbitAddress}/${isDescription ? 'description' : isRules ? 'rules' : `c/${cid}`}`} /> }}
/>
</span>
)}
{!cid && state === 'pending' && stateString !== 'Failed' && (
+43 -9
View File
@@ -1,29 +1,31 @@
import { useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useLocation, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import Draggable from 'react-draggable';
import { setAccount, useAccount, useSubplebbit } from '@plebbit/plebbit-react-hooks';
import { setAccount, useAccount, useComment, useSubplebbit } from '@plebbit/plebbit-react-hooks';
import Plebbit from '@plebbit/plebbit-js/dist/browser/index.js';
import { getFormattedTimeAgo } from '../../lib/utils/time-utils';
import { isValidURL } from '../../lib/utils/url-utils';
import { isAllView, isSubscriptionsView } from '../../lib/utils/view-utils';
import useSelectedTextStore from '../../stores/use-selected-text-store';
import useReply from '../../hooks/use-reply';
import usePublishReply from '../../hooks/use-publish-reply';
import useIsMobile from '../../hooks/use-is-mobile';
import styles from './reply-modal.module.css';
import { LinkTypePreviewer } from '../post-form';
import _ from 'lodash';
import useAnonMode from '../../hooks/use-anon-mode';
interface ReplyModalProps {
closeModal: () => void;
parentCid: string;
postCid: string;
scrollY: number;
}
const ReplyModal = ({ closeModal, parentCid, scrollY }: ReplyModalProps) => {
const ReplyModal = ({ closeModal, parentCid, postCid, scrollY }: ReplyModalProps) => {
const { t } = useTranslation();
const { subplebbitAddress } = useParams() as { subplebbitAddress: string };
const { setContent, publishReply } = useReply({ cid: parentCid, subplebbitAddress });
const { setPublishReplyOptions, publishReply } = usePublishReply({ cid: parentCid, subplebbitAddress });
const account = useAccount();
const { displayName } = account?.author || {};
const [url, setUrl] = useState('');
@@ -31,7 +33,38 @@ const ReplyModal = ({ closeModal, parentCid, scrollY }: ReplyModalProps) => {
const urlRef = useRef<HTMLInputElement>(null);
const { selectedText } = useSelectedTextStore();
const onPublishReply = () => {
const { anonMode, getNewSigner, getExistingSigner } = useAnonMode(postCid);
const comment = useComment({ commentCid: postCid });
const address = comment?.author?.address;
const hasCalledAnonAddressRef = useRef(false);
const getAnonAddressForReply = useCallback(async () => {
if (anonMode && !hasCalledAnonAddressRef.current) {
hasCalledAnonAddressRef.current = true;
let signer = getExistingSigner(address);
if (!signer) {
signer = await getNewSigner();
if (signer) {
setPublishReplyOptions({
signer,
author: {
displayName,
address: signer.address,
},
});
}
}
}
}, [anonMode, address, getExistingSigner, getNewSigner, displayName, setPublishReplyOptions]);
useEffect(() => {
if (anonMode) {
getAnonAddressForReply();
}
}, [anonMode, getAnonAddressForReply]);
const onPublishReply = async () => {
const currentContent = textRef.current?.value || '';
const currentUrl = urlRef.current?.value || '';
@@ -44,6 +77,7 @@ const ReplyModal = ({ closeModal, parentCid, scrollY }: ReplyModalProps) => {
alert('The provided link is not a valid URL.');
return;
}
publishReply();
closeModal();
};
@@ -109,7 +143,7 @@ const ReplyModal = ({ closeModal, parentCid, scrollY }: ReplyModalProps) => {
// remove the prefix from the content to publish, and also add newlines for markdown
const contentWithoutPrefix = e.target.value.slice(contentPrefix.length).replace(/\n/g, '\n\n');
if (textRef.current && textRef.current.value !== contentWithoutPrefix) {
setContent.content(contentWithoutPrefix);
setPublishReplyOptions({ content: contentWithoutPrefix });
}
};
@@ -142,7 +176,7 @@ const ReplyModal = ({ closeModal, parentCid, scrollY }: ReplyModalProps) => {
placeholder={_.capitalize(t('link'))}
onChange={(e) => {
setUrl(e.target.value);
setContent.link(e.target.value);
setPublishReplyOptions({ link: e.target.value });
}}
/>
</div>
@@ -169,7 +203,7 @@ const ReplyModal = ({ closeModal, parentCid, scrollY }: ReplyModalProps) => {
<span className={styles.spoilerButton}>
[
<label>
<input type='checkbox' onChange={(e) => setContent.spoiler(e.target.checked)} />
<input type='checkbox' onChange={(e) => setPublishReplyOptions({ spoiler: e.target.checked })} />
{_.capitalize(t('spoiler'))}?
</label>
]
@@ -36,11 +36,32 @@
}
.deleteAccount {
color: red;
display: block;
margin-top: 10px;
}
.deleteAccount:not(:disabled) {
color: red;
}
.setting .createAccount {
margin-left: 5px;
}
.settingTip {
display: block;
font-size: 0.85em;
margin: 2px 0 10px 0;
padding-left: 19px;
}
.anonMode {
padding: 10px 0;
}
.anonMode label {
text-transform: capitalize;
}
.anonMode input[type="checkbox"] {
margin-right: 3px;
}
@@ -3,6 +3,21 @@ import { useTranslation } from 'react-i18next';
import { createAccount, deleteAccount, exportAccount, importAccount, setAccount, setActiveAccount, useAccount, useAccounts } from '@plebbit/plebbit-react-hooks';
import stringify from 'json-stringify-pretty-compact';
import styles from './account-settings.module.css';
import useAnonModeStore from '../../../stores/use-anon-mode-store';
const AnonMode = () => {
const anonMode = useAnonModeStore((state) => state.anonMode);
const setAnonMode = useAnonModeStore((state) => state.setAnonMode);
return (
<div className={styles.anonMode}>
<label>
<input type='checkbox' checked={anonMode} onChange={(e) => setAnonMode(e.target.checked)} /> anon mode
</label>
<span className={styles.settingTip}>Automatically use a different user ID in each thread</span>
</div>
);
};
const AccountSettings = () => {
const { t } = useTranslation();
@@ -167,7 +182,7 @@ const AccountSettings = () => {
<textarea value={text} onChange={(e) => setText(e.target.value)} autoCorrect='off' autoComplete='off' spellCheck='false' />
<div>
<button onClick={saveAccount}>{t('save')}</button> <button onClick={() => setText(accountJson)}>{t('reset')}</button>{' '}
<button onClick={_importAccount}>{t('import')}</button> <button onClick={_exportAccount}>{t('export')}</button>{' '}
<button onClick={_importAccount}>{t('import')}</button> <button onClick={_exportAccount}>{t('export')}</button> <AnonMode />
<button className={styles.deleteAccount} onClick={() => _deleteAccount(account?.name)}>
{t('delete_account')}
</button>
+52
View File
@@ -0,0 +1,52 @@
import { useAccount } from '@plebbit/plebbit-react-hooks';
import useAnonModeStore from '../stores/use-anon-mode-store';
const useAnonMode = (postCid?: string) => {
const { anonMode, threadSigners, setThreadSigner, setAddressSigner, getAddressSigner } = useAnonModeStore((state) => ({
anonMode: state.anonMode,
threadSigners: state.threadSigners,
setThreadSigner: state.setThreadSigner,
setAddressSigner: state.setAddressSigner,
getAddressSigner: state.getAddressSigner,
}));
const threadSigner = postCid ? threadSigners[postCid] : undefined;
const account = useAccount();
const getNewSigner = async () => {
if (anonMode) {
if (!postCid || !threadSigner) {
try {
const signer = await account?.plebbit.createSigner();
if (signer) {
if (postCid) {
setThreadSigner(postCid, signer);
} else {
setAddressSigner(signer);
}
}
return signer;
} catch (error) {
console.error('Failed to create anonymous signer:', error);
}
} else {
try {
const signer = await account?.plebbit.createSigner({ type: 'ed25519', privateKey: threadSigner?.privateKey });
return signer;
} catch (error) {
console.error('Failed to retrieve anonymous signer:', error);
}
}
}
return null;
};
const getExistingSigner = (address: string) => {
return getAddressSigner(address);
};
return { anonMode, getNewSigner, getExistingSigner };
};
export default useAnonMode;
+123
View File
@@ -0,0 +1,123 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams, useLocation } from 'react-router-dom';
import { useAccountComments, Subplebbit } from '@plebbit/plebbit-react-hooks';
import { isAllView } from '../lib/utils/view-utils';
import { useMultisubMetadata } from './use-default-subplebbits';
import useCatalogFiltersStore from '../stores/use-catalog-filters-store';
import _ from 'lodash';
import { getCommentMediaInfo, getHasThumbnail } from '../lib/utils/media-utils';
const useCatalogFeedRows = (columnCount: number, feed: any, isFeedLoaded: boolean, subplebbit: Subplebbit) => {
const { t } = useTranslation();
const { address, createdAt, description, rules, shortAddress, suggested, title } = subplebbit || {};
const { avatarUrl } = suggested || {};
const { showTextOnlyThreads } = useCatalogFiltersStore();
const location = useLocation();
const isInAllView = isAllView(location.pathname, useParams());
const multisub = useMultisubMetadata();
const { accountComments } = useAccountComments();
const feedWithFakePostsOnTop = useMemo(() => {
if (!isFeedLoaded) {
return []; // prevent rules and description from appearing while feed is loading
}
if (!description && !rules && !isInAllView) {
return feed;
}
const _feed = [...feed];
// show account comments instantly in the feed once published (cid defined), instead of waiting for the feed to update
const filteredComments = accountComments.filter((comment) => {
const { cid, deleted, link, postCid, removed, state, subplebbitAddress } = comment || {};
const commentMediaInfo = getCommentMediaInfo(comment);
const isMediaShowed = getHasThumbnail(commentMediaInfo, link);
return (
!deleted &&
!removed &&
state === 'succeeded' &&
(showTextOnlyThreads || (!showTextOnlyThreads && isMediaShowed)) &&
cid &&
cid === postCid &&
subplebbitAddress === address &&
!_feed.some((feedItem) => feedItem.cid === cid)
);
});
// show newest account comment at the top of the feed but after pinned posts
const lastPinnedIndex = _feed.map((post) => post.pinned).lastIndexOf(true);
if (filteredComments.length > 0) {
_feed.splice(
lastPinnedIndex + 1,
0,
...filteredComments.map((comment) => ({
...comment,
isAccountComment: true,
})),
);
}
// add subplebbit description and rules as fake posts at the top of the feed
if ((description && description.length > 0 && (showTextOnlyThreads || (!showTextOnlyThreads && suggested?.avatarUrl))) || isInAllView) {
_feed.unshift({
isDescription: true,
subplebbitAddress: address,
timestamp: createdAt,
author: { displayName: `## ${t('board_mods')}` },
content: isInAllView ? multisub?.description : description,
link: avatarUrl,
title: t('welcome_to_board', { board: isInAllView ? multisub?.title : title || `p/${shortAddress}`, interpolation: { escapeValue: false } }),
pinned: true,
locked: true,
});
}
if (rules && rules.length > 0 && showTextOnlyThreads) {
_feed.unshift({
isRules: true,
subplebbitAddress: address,
timestamp: createdAt,
author: { displayName: `## ${t('board_mods')}` },
content: rules.map((rule: string, index: number) => `${index + 1}. ${rule}`).join('\n'),
title: _.capitalize(t('rules')),
pinned: true,
locked: true,
});
}
return _feed;
}, [
accountComments,
feed,
description,
rules,
address,
isFeedLoaded,
createdAt,
title,
shortAddress,
avatarUrl,
t,
isInAllView,
multisub,
showTextOnlyThreads,
suggested?.avatarUrl,
]);
const rows = useMemo(() => {
const rows = [];
for (let i = 0; i < feedWithFakePostsOnTop.length; i += columnCount) {
rows.push(feedWithFakePostsOnTop.slice(i, i + columnCount));
}
return rows;
}, [feedWithFakePostsOnTop, columnCount]);
return rows;
};
export default useCatalogFeedRows;
+2 -4
View File
@@ -19,10 +19,8 @@ const useInitialTheme = () => {
if (isInPendingPostView) {
return currentTheme || 'yotsuba';
} else if (isInAllView) {
return getTheme('all') || 'yotsuba-b';
} else if (isInSubscriptionsView) {
return getTheme('subscriptions') || 'yotsuba-b';
} else if (isInAllView || isInSubscriptionsView) {
return getTheme('sfw') || 'yotsuba-b';
} else if (isInHomeView || isInNotFoundView) {
return 'yotsuba';
} else if (subplebbitAddress) {
+1 -1
View File
@@ -3,7 +3,7 @@ import { useEffect } from 'react';
import { Subplebbit } from '@plebbit/plebbit-react-hooks';
import { getFormattedTimeAgo } from '../lib/utils/time-utils';
import useSubplebbitOfflineStore from '../stores/use-subplebbit-offline-store';
import useSubplebbitsLoadingStartTimestamps from './use-subplebbits-loading-start-timestamps-store';
import useSubplebbitsLoadingStartTimestamps from '../stores/use-subplebbits-loading-start-timestamps-store';
const useIsSubplebbitOffline = (subplebbit: Subplebbit) => {
const { t } = useTranslation();
@@ -1,4 +1,4 @@
import { useMemo } from 'react';
import { useCallback } from 'react';
import { ChallengeVerification, Comment, PublishCommentOptions, usePublishComment } from '@plebbit/plebbit-react-hooks';
import { create } from 'zustand';
import { alertChallengeVerificationFailed } from '../lib/utils/challenge-utils';
@@ -7,16 +7,20 @@ import useChallengesStore from '../stores/use-challenges-store';
type SetReplyStoreData = {
subplebbitAddress: string;
parentCid: string;
author: any | undefined;
content: string | undefined;
link: string | undefined;
spoiler: boolean;
signer: any | undefined;
spoiler: boolean | undefined;
};
type ReplyState = {
author: { [parentCid: string]: any | undefined };
content: { [parentCid: string]: string | undefined };
link: { [parentCid: string]: string | undefined };
signer: { [parentCid: string]: any | undefined };
spoiler: { [parentCid: string]: boolean | undefined };
publishCommentOptions: PublishCommentOptions;
publishCommentOptions: { [parentCid: string]: PublishCommentOptions | undefined };
setReplyStore: (data: SetReplyStoreData) => void;
resetReplyStore: (parentCid: string) => void;
};
@@ -24,16 +28,20 @@ type ReplyState = {
const { addChallenge } = useChallengesStore.getState();
const useReplyStore = create<ReplyState>((set) => ({
author: {},
content: {},
link: {},
signer: {},
spoiler: {},
publishCommentOptions: {},
setReplyStore: (data: SetReplyStoreData) =>
set((state) => {
const { subplebbitAddress, parentCid, content, link, spoiler } = data;
const { subplebbitAddress, parentCid, author, content, link, signer, spoiler } = data;
const publishCommentOptions = {
subplebbitAddress,
parentCid,
author,
signer,
content,
link,
spoiler,
@@ -47,6 +55,8 @@ const useReplyStore = create<ReplyState>((set) => ({
},
};
return {
author: { ...state.author, [parentCid]: author },
signer: { ...state.signer, [parentCid]: signer },
content: { ...state.content, [parentCid]: content },
link: { ...state.link, [parentCid]: link },
spoiler: { ...state.spoiler, [parentCid]: spoiler },
@@ -56,6 +66,8 @@ const useReplyStore = create<ReplyState>((set) => ({
resetReplyStore: (parentCid) =>
set((state) => ({
author: { ...state.author, [parentCid]: undefined },
signer: { ...state.signer, [parentCid]: undefined },
content: { ...state.content, [parentCid]: undefined },
link: { ...state.link, [parentCid]: undefined },
spoiler: { ...state.spoiler, [parentCid]: undefined },
@@ -65,7 +77,9 @@ const useReplyStore = create<ReplyState>((set) => ({
const useReply = ({ cid, subplebbitAddress }: { cid: string; subplebbitAddress: string }) => {
const parentCid = cid;
const { content, link, spoiler, publishCommentOptions } = useReplyStore((state) => ({
const { author, signer, content, link, spoiler, publishCommentOptions } = useReplyStore((state) => ({
author: state.author[parentCid],
signer: state.signer[parentCid],
content: state.content[parentCid],
link: state.link[parentCid],
spoiler: state.spoiler[parentCid],
@@ -75,41 +89,27 @@ const useReply = ({ cid, subplebbitAddress }: { cid: string; subplebbitAddress:
const setReplyStore = useReplyStore((state) => state.setReplyStore);
const resetReplyStore = useReplyStore((state) => state.resetReplyStore);
const setContent = useMemo(
() => ({
content: (newContent: string) =>
setReplyStore({
subplebbitAddress,
parentCid,
content: newContent === '' ? undefined : newContent,
link: link || undefined,
spoiler: spoiler || false,
}),
link: (newLink: string) =>
setReplyStore({
subplebbitAddress,
parentCid,
content: content,
link: newLink || undefined,
spoiler: spoiler || false,
}),
spoiler: (newSpoiler: boolean) =>
setReplyStore({
subplebbitAddress,
parentCid,
content: content,
link: link || undefined,
spoiler: newSpoiler,
}),
}),
[subplebbitAddress, parentCid, setReplyStore, content, link, spoiler],
const setPublishReplyOptions = useCallback(
(options: Partial<SetReplyStoreData>) => {
setReplyStore({
subplebbitAddress,
parentCid,
author,
signer,
content,
link,
spoiler,
...options,
});
},
[subplebbitAddress, parentCid, author, signer, content, link, spoiler, setReplyStore],
);
const resetContent = useMemo(() => () => resetReplyStore(parentCid), [parentCid, resetReplyStore]);
const resetPublishReplyOptions = useCallback(() => resetReplyStore(parentCid), [parentCid, resetReplyStore]);
const { index, publishComment } = usePublishComment(publishCommentOptions);
return { setContent, resetContent, replyIndex: index, publishReply: publishComment };
return { setPublishReplyOptions, resetPublishReplyOptions, replyIndex: index, publishReply: publishComment, setReplyStore };
};
export default useReply;
+6 -4
View File
@@ -5,6 +5,7 @@ import useSelectedTextStore from '../stores/use-selected-text-store';
const useReplyModal = () => {
const [showReplyModal, setShowReplyModal] = useState(false);
const [activeCid, setActiveCid] = useState<string | null>(null);
const [threadCid, setThreadCid] = useState<string | null>(null);
const { resetSelectedText, setSelectedText } = useSelectedTextStore();
// on mobile, the css position is absolute instead of fixed, so we need to calculate the top position
@@ -22,7 +23,7 @@ const useReplyModal = () => {
text && setSelectedText(`>${text}\n`);
};
const openReplyModal = (cid: string) => {
const openReplyModal = (parentCid: string, postCid: string) => {
getSelectedText();
if (isMobile) {
@@ -30,14 +31,15 @@ const useReplyModal = () => {
setScrollY(currentScrollY);
}
if (activeCid && activeCid !== cid) {
if (activeCid && activeCid !== parentCid) {
return;
}
setActiveCid(cid);
setActiveCid(parentCid);
setThreadCid(postCid);
setShowReplyModal(true);
};
return { activeCid, closeModal, openReplyModal, scrollY, showReplyModal };
return { activeCid, threadCid, closeModal, openReplyModal, scrollY, showReplyModal };
};
export default useReplyModal;
+4 -8
View File
@@ -44,10 +44,8 @@ const useTheme = (): [string, (theme: string) => void] => {
const isInSubscriptionsView = isSubscriptionsView(location.pathname, params);
let storedTheme = null;
if (isInAllView) {
storedTheme = getTheme('all');
} else if (isInSubscriptionsView) {
storedTheme = getTheme('subscriptions');
if (isInAllView || isInSubscriptionsView) {
storedTheme = getTheme('sfw');
} else if (subplebbitAddress) {
const subplebbit = subplebbits.find((s) => s.address === subplebbitAddress);
if (subplebbit && subplebbit.tags && subplebbit.tags.some((tag) => nsfwTags.includes(tag))) {
@@ -67,10 +65,8 @@ const useTheme = (): [string, (theme: string) => void] => {
const isInAllView = isAllView(location.pathname, params);
const isInSubscriptionsView = isSubscriptionsView(location.pathname, params);
if (isInAllView) {
await setThemeStore('all', newTheme);
} else if (isInSubscriptionsView) {
await setThemeStore('subscriptions', newTheme);
if (isInAllView || isInSubscriptionsView) {
await setThemeStore('sfw', newTheme);
} else if (subplebbitAddress) {
const subplebbit = subplebbits.find((s) => s.address === subplebbitAddress);
if (subplebbit && subplebbit.tags && subplebbit.tags.some((tag) => nsfwTags.includes(tag))) {
+1 -1
View File
@@ -62,7 +62,7 @@ export const isHomeView = (pathname: string): boolean => {
};
export const isPendingPostView = (pathname: string, params: ParamsType): boolean => {
return pathname === `/profile/${params.accountCommentIndex}`;
return pathname === `/profile/${params.accountCommentIndex}` || pathname === `/profile/${params.accountCommentIndex}/settings`;
};
export const isPostPageView = (pathname: string, params: ParamsType): boolean => {
+60
View File
@@ -0,0 +1,60 @@
import { create } from 'zustand';
import localForageLru from '@plebbit/plebbit-react-hooks/dist/lib/localforage-lru/index.js';
interface AnonModeState {
anonMode: boolean;
threadSigners: { [key: string]: any };
addressSigners: { [address: string]: any };
setAnonMode: (mode: boolean) => void;
setThreadSigner: (postCid: string, signer: any) => void;
getThreadSigner: (postCid: string) => any | undefined;
setAddressSigner: (signer: any) => void;
getAddressSigner: (address: string) => any | undefined;
}
const anonModeStore = localForageLru.createInstance({
name: 'anonModeStore',
size: 1000,
});
const useAnonModeStore = create<AnonModeState>((set, get) => ({
anonMode: true,
threadSigners: {},
addressSigners: {},
setAnonMode: (mode: boolean) => set({ anonMode: mode }),
setThreadSigner: (postCid: string, signer: any) => {
set((state) => ({
threadSigners: { ...state.threadSigners, [postCid]: signer },
}));
anonModeStore.setItem(postCid, signer);
},
getThreadSigner: (postCid: string) => get().threadSigners[postCid],
setAddressSigner: (signer: any) => {
set((state) => ({
addressSigners: { ...state.addressSigners, [signer.address]: signer },
}));
anonModeStore.setItem(signer.address, signer);
},
getAddressSigner: (address: string) => get().addressSigners[address],
}));
const initializeAnonModeStore = async () => {
const entries: [string, any][] = await anonModeStore.entries();
const threadSigners: { [key: string]: any } = {};
const addressSigners: { [key: string]: any } = {};
entries.forEach(([key, value]) => {
if (value.address) {
addressSigners[value.address] = value;
}
threadSigners[key] = value;
});
useAnonModeStore.setState((state) => ({
threadSigners: { ...threadSigners, ...state.threadSigners },
addressSigners: { ...addressSigners, ...state.addressSigners },
}));
};
initializeAnonModeStore();
export default useAnonModeStore;
-6
View File
@@ -5,8 +5,6 @@ interface ThemeState {
themes: {
nsfw: string;
sfw: string;
all: string;
subscriptions: string;
};
currentTheme: string | null;
setTheme: (category: keyof ThemeState['themes'], theme: string) => void;
@@ -23,8 +21,6 @@ const useThemeStore = create<ThemeState>((set: StoreApi<ThemeState>['setState'],
themes: {
nsfw: 'yotsuba',
sfw: 'yotsuba-b',
all: 'yotsuba-b',
subscriptions: 'yotsuba-b',
},
currentTheme: null,
setTheme: async (category, theme) => {
@@ -44,8 +40,6 @@ const useThemeStore = create<ThemeState>((set: StoreApi<ThemeState>['setState'],
const themes: Record<keyof ThemeState['themes'], string> = {
nsfw: 'yotsuba',
sfw: 'yotsuba-b',
all: 'yotsuba-b',
subscriptions: 'yotsuba-b',
};
entries.forEach(([key, value]) => {
themes[key] = value;
+95 -65
View File
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useRef } from 'react';
import { useLocation, useParams } from 'react-router-dom';
import { useAccount, useBlock, useFeed, useSubplebbit } from '@plebbit/plebbit-react-hooks';
import { useAccount, useAccountComments, useBlock, useFeed, useSubplebbit } from '@plebbit/plebbit-react-hooks';
import { Virtuoso, VirtuosoHandle, StateSnapshot } from 'react-virtuoso';
import { useTranslation } from 'react-i18next';
import styles from './board.module.css';
@@ -45,29 +45,68 @@ const Board = () => {
const { sortType } = useSortingStore();
const { timeFilterSeconds } = useTimeFilter();
const feedOptions: any = {
subplebbitAddresses,
sortType,
postsPerPage: isInAllView || isInSubscriptionsView ? 5 : 25,
};
if (isInAllView || isInSubscriptionsView) {
feedOptions.newerThan = timeFilterSeconds;
}
const feedOptions: any = useMemo(
() => ({
subplebbitAddresses,
sortType,
postsPerPage: isInAllView || isInSubscriptionsView ? 5 : 25,
...(isInAllView || isInSubscriptionsView ? { newerThan: timeFilterSeconds } : {}),
}),
[subplebbitAddresses, sortType, timeFilterSeconds, isInAllView, isInSubscriptionsView],
);
const { feed, hasMore, loadMore, reset } = useFeed(feedOptions);
const { accountComments } = useAccountComments();
const resetTriggeredRef = useRef(false);
const setResetFunction = useFeedResetStore((state) => state.setResetFunction);
useEffect(() => {
setResetFunction(reset);
}, [reset, setResetFunction]);
}, [reset, setResetFunction, feed]);
// show account comments instantly in the feed once published (cid defined), instead of waiting for the feed to update
const filteredComments = useMemo(
() =>
accountComments.filter((comment) => {
const { cid, deleted, postCid, removed, state } = comment || {};
return (
!deleted &&
!removed &&
state === 'succeeded' &&
cid &&
cid === postCid &&
comment?.subplebbitAddress === subplebbitAddress &&
!feed.some((post) => post.cid === cid)
);
}),
[accountComments, subplebbitAddress, feed],
);
// show newest account comment at the top of the feed but after pinned posts
const combinedFeed = useMemo(() => {
const newFeed = [...feed];
const lastPinnedIndex = newFeed.map((post) => post.pinned).lastIndexOf(true);
if (filteredComments.length > 0) {
newFeed.splice(lastPinnedIndex + 1, 0, ...filteredComments);
}
return newFeed;
}, [feed, filteredComments]);
useEffect(() => {
if (filteredComments.length > 0 && !resetTriggeredRef.current) {
reset();
resetTriggeredRef.current = true;
}
}, [filteredComments, reset]);
const subplebbit = useSubplebbit({ subplebbitAddress });
const { createdAt, description, error, rules, shortAddress, state, suggested } = subplebbit || {};
const title = isInAllView ? t('all') : isInSubscriptionsView ? t('subscriptions') : subplebbit?.title;
const { activeCid, closeModal, openReplyModal, showReplyModal, scrollY } = useReplyModal();
const { activeCid, threadCid, closeModal, openReplyModal, showReplyModal, scrollY } = useReplyModal();
const { blocked, unblock } = useBlock({ address: subplebbitAddress });
const loadingStateString = useFeedStateString(subplebbitAddresses) || t('loading');
const loadingString = (
<div className={styles.stateString}>
@@ -75,6 +114,10 @@ const Board = () => {
<span className='red'>{state}</span>
) : isInSubscriptionsView && subscriptions?.length === 0 ? (
t('not_subscribed_to_any_board')
) : blocked ? (
'you have blocked this board'
) : !hasMore && feed.length === 0 ? (
t('no_posts')
) : (
<LoadingEllipsis string={loadingStateString} />
)}
@@ -87,40 +130,8 @@ const Board = () => {
</div>
);
const { blocked, unblock } = useBlock({ address: subplebbitAddress });
const Footer = () => {
let footerContent;
if (feed.length === 0) {
if (blocked) {
footerContent = 'you have blocked this board';
} else {
footerContent = t('no_posts');
}
}
if (hasMore || subplebbitAddresses.length === 0) {
footerContent = loadingString;
}
return (
<div className={styles.footer}>
{footerContent}
{blocked && (
<>
&nbsp;&nbsp;[
<span
className={styles.button}
onClick={() => {
unblock();
reset();
}}
>
Unblock
</span>
]
</>
)}
</div>
);
return <div className={styles.footer}>{loadingString}</div>;
};
// save the last Virtuoso state to restore it when navigating back
@@ -147,8 +158,8 @@ const Board = () => {
return (
<div className={styles.content}>
{location.pathname.endsWith('/settings') && <SettingsModal />}
{showReplyModal && activeCid && <ReplyModal closeModal={closeModal} parentCid={activeCid} scrollY={scrollY} />}
{feed.length > 0 && (
{showReplyModal && activeCid && threadCid && <ReplyModal closeModal={closeModal} parentCid={activeCid} postCid={threadCid} scrollY={scrollY} />}
{feed.length !== 0 ? (
<>
{rules && rules.length > 0 && <SubplebbitRules subplebbitAddress={subplebbitAddress} createdAt={createdAt} rules={rules} />}
{((description && description.length > 0) || isInAllView) && (
@@ -161,25 +172,44 @@ const Board = () => {
title={title}
/>
)}
</>
)}
<Virtuoso
increaseViewportBy={{ bottom: 1200, top: 1200 }}
totalCount={feed?.length || 0}
data={feed}
itemContent={(index, post) => {
const { deleted, locked, removed } = post || {};
const isThreadClosed = deleted || locked || removed;
<Virtuoso
increaseViewportBy={{ bottom: 1200, top: 1200 }}
totalCount={combinedFeed.length}
data={combinedFeed}
itemContent={(index, post) => {
const { deleted, locked, removed } = post || {};
const isThreadClosed = deleted || locked || removed;
return <Post index={index} post={post} openReplyModal={isThreadClosed ? () => alert(t('thread_closed_alert')) : openReplyModal} />;
}}
useWindowScroll={true}
components={{ Footer }}
endReached={loadMore}
ref={virtuosoRef}
restoreStateFrom={lastVirtuosoState}
initialScrollTop={lastVirtuosoState?.scrollTop}
/>
return <Post index={index} post={post} openReplyModal={isThreadClosed ? () => alert(t('thread_closed_alert')) : openReplyModal} />;
}}
useWindowScroll={true}
components={{ Footer }}
endReached={loadMore}
ref={virtuosoRef}
restoreStateFrom={lastVirtuosoState}
initialScrollTop={lastVirtuosoState?.scrollTop}
/>
</>
) : (
<div className={styles.footer}>
{loadingString}
{blocked && (
<>
&nbsp;&nbsp;[
<span
className={styles.button}
onClick={() => {
unblock();
reset();
}}
>
Unblock
</span>
]
</>
)}
</div>
)}
</div>
);
};
+5 -65
View File
@@ -1,86 +1,26 @@
import { useEffect, useMemo, useRef } from 'react';
import { useLocation, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Comment, useAccount, Subplebbit, useFeed, useSubplebbit, useBlock } from '@plebbit/plebbit-react-hooks';
import { Comment, useAccount, useFeed, useSubplebbit, useBlock } from '@plebbit/plebbit-react-hooks';
import { Virtuoso, VirtuosoHandle, StateSnapshot } from 'react-virtuoso';
import { getCommentMediaInfo, getHasThumbnail } from '../../lib/utils/media-utils';
import { isAllView, isSubscriptionsView } from '../../lib/utils/view-utils';
import useCatalogFeedRows from '../../hooks/use-catalog-feed-rows';
import useDefaultSubplebbits from '../../hooks/use-default-subplebbits';
import useFeedStateString from '../../hooks/use-feed-state-string';
import { useMultisubMetadata } from '../../hooks/use-default-subplebbits';
import useTimeFilter from '../../hooks/use-time-filter';
import useWindowWidth from '../../hooks/use-window-width';
import useCatalogFiltersStore from '../../stores/use-catalog-filters-store';
import useCatalogStyleStore from '../../stores/use-catalog-style-store';
import useFeedResetStore from '../../stores/use-feed-reset-store';
import useSortingStore from '../../stores/use-sorting-store';
import CatalogRow from '../../components/catalog-row';
import LoadingEllipsis from '../../components/loading-ellipsis';
import SettingsModal from '../../components/settings-modal';
import styles from './catalog.module.css';
import _ from 'lodash';
import { getCommentMediaInfo, getHasThumbnail } from '../../lib/utils/media-utils';
import useCatalogStyleStore from '../../stores/use-catalog-style-store';
const lastVirtuosoStates: { [key: string]: StateSnapshot } = {};
const useFeedRows = (columnCount: number, feed: any, isFeedLoaded: boolean, subplebbit: Subplebbit) => {
const { t } = useTranslation();
const { address, createdAt, description, rules, shortAddress, suggested, title } = subplebbit || {};
const { avatarUrl } = suggested || {};
const { showTextOnlyThreads } = useCatalogFiltersStore();
const location = useLocation();
const isInAllView = isAllView(location.pathname, useParams());
const multisub = useMultisubMetadata();
const feedWithDescriptionAndRules = useMemo(() => {
if (!isFeedLoaded) {
return []; // prevent rules and description from appearing while feed is loading
}
if (!description && !rules && !isInAllView) {
return feed;
}
const _feed = [...feed];
if ((description && description.length > 0 && (showTextOnlyThreads || (!showTextOnlyThreads && suggested?.avatarUrl))) || isInAllView) {
_feed.unshift({
isDescription: true,
subplebbitAddress: address,
timestamp: createdAt,
author: { displayName: `## ${t('board_mods')}` },
content: isInAllView ? multisub?.description : description,
link: avatarUrl,
title: t('welcome_to_board', { board: isInAllView ? multisub?.title : title || `p/${shortAddress}`, interpolation: { escapeValue: false } }),
pinned: true,
locked: true,
});
}
if (rules && rules.length > 0 && showTextOnlyThreads) {
_feed.unshift({
isRules: true,
subplebbitAddress: address,
timestamp: createdAt,
author: { displayName: `## ${t('board_mods')}` },
content: rules.map((rule: string, index: number) => `${index + 1}. ${rule}`).join('\n'),
title: _.capitalize(t('rules')),
pinned: true,
locked: true,
});
}
return _feed;
}, [feed, description, rules, address, isFeedLoaded, createdAt, title, shortAddress, avatarUrl, t, isInAllView, multisub, showTextOnlyThreads, suggested?.avatarUrl]);
const rows = useMemo(() => {
const rows = [];
for (let i = 0; i < feedWithDescriptionAndRules.length; i += columnCount) {
rows.push(feedWithDescriptionAndRules.slice(i, i + columnCount));
}
return rows;
}, [feedWithDescriptionAndRules, columnCount]);
return rows;
};
const catalogFilter = (comment: Comment) => {
const commentMediaInfo = getCommentMediaInfo(comment);
const hasThumbnail = getHasThumbnail(commentMediaInfo, comment?.link);
@@ -212,7 +152,7 @@ const Catalog = () => {
const isFeedLoaded = feed.length > 0 || state === 'failed';
const rows = useFeedRows(columnCount, feed, isFeedLoaded, subplebbit);
const rows = useCatalogFeedRows(columnCount, feed, isFeedLoaded, subplebbit);
// save the last Virtuoso state to restore it when navigating back
const virtuosoRef = useRef<VirtuosoHandle | null>(null);
+3 -3
View File
@@ -22,7 +22,7 @@ export interface PostProps {
roles?: Role[];
showAllReplies?: boolean;
showReplies?: boolean;
openReplyModal?: (cid: string) => void;
openReplyModal?: (parentCid: string, postCid: string) => void;
}
export const Post = ({ post, showAllReplies = false, showReplies = true, openReplyModal }: PostProps) => {
@@ -62,7 +62,7 @@ const PostPage = () => {
const subplebbit = useSubplebbit({ subplebbitAddress });
const { createdAt, description, rules, shortAddress, suggested, title } = subplebbit;
const { activeCid, closeModal, openReplyModal, showReplyModal, scrollY } = useReplyModal();
const { activeCid, threadCid, closeModal, openReplyModal, showReplyModal, scrollY } = useReplyModal();
const comment = useComment({ commentCid });
@@ -91,7 +91,7 @@ const PostPage = () => {
return (
<div className={styles.content}>
{isInSettigsView && <SettingsModal />}
{showReplyModal && activeCid && <ReplyModal closeModal={closeModal} parentCid={activeCid} scrollY={scrollY} />}
{showReplyModal && activeCid && threadCid && <ReplyModal closeModal={closeModal} parentCid={activeCid} postCid={threadCid} scrollY={scrollY} />}
{/* TODO: remove this replyCount error once api supports scrolling replies pages */}
{replyCount > 60 && <span className={styles.error}>Error: this thread has too many replies, some of them cannot be displayed right now.</span>}
{error && <span className={styles.error}>Error: {error.message}</span>}