refactor, fix bugs

This commit is contained in:
Tom (plebeius.eth)
2025-01-30 17:09:21 +01:00
parent b1dc7ba486
commit 204fdfcace
4 changed files with 147 additions and 78 deletions
+55 -67
View File
@@ -1,21 +1,21 @@
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams } from 'react-router-dom'; import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { Comment, setAccount, useAccount, useAccountComment, useComment, useEditedComment, usePublishComment, useSubplebbit } from '@plebbit/plebbit-react-hooks'; import { Comment, setAccount, useAccount, useAccountComment, useComment, useEditedComment, useSubplebbit } from '@plebbit/plebbit-react-hooks';
import { getHasThumbnail, getLinkMediaInfo } from '../../lib/utils/media-utils'; import { getHasThumbnail, getLinkMediaInfo } from '../../lib/utils/media-utils';
import { formatMarkdown } from '../../lib/utils/post-utils'; import { formatMarkdown } from '../../lib/utils/post-utils';
import { isValidURL } from '../../lib/utils/url-utils'; import { isValidURL } from '../../lib/utils/url-utils';
import { isAllView, isDescriptionView, isPostPageView, isRulesView, isSubscriptionsView } from '../../lib/utils/view-utils'; import { isAllView, isDescriptionView, isPostPageView, isRulesView, isSubscriptionsView } from '../../lib/utils/view-utils';
import { useDefaultSubplebbitAddresses } from '../../hooks/use-default-subplebbits';
import usePublishReply from '../../hooks/use-publish-reply';
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'; import useAnonMode from '../../hooks/use-anon-mode';
import usePublishPostStore from '../../stores/use-publish-post-store'; import { useDefaultSubplebbitAddresses } from '../../hooks/use-default-subplebbits';
import useFetchGifFirstFrame from '../../hooks/use-fetch-gif-first-frame';
import useIsSubplebbitOffline from '../../hooks/use-is-subplebbit-offline';
import usePublishPost from '../../hooks/use-publish-post';
import usePublishReply from '../../hooks/use-publish-reply';
import FileUploader from '../../plugins/file-uploader'; import FileUploader from '../../plugins/file-uploader';
import styles from './post-form.module.css';
import { Capacitor } from '@capacitor/core'; import { Capacitor } from '@capacitor/core';
import _ from 'lodash';
const isAndroid = Capacitor.getPlatform() === 'android'; const isAndroid = Capacitor.getPlatform() === 'android';
@@ -36,12 +36,14 @@ export const LinkTypePreviewer = ({ link }: { link: string }) => {
const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid: string }) => { const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid: string }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const params = useParams();
const account = useAccount(); const account = useAccount();
const [url, setUrl] = useState('');
const author = account?.author || {}; const author = account?.author || {};
const { displayName } = author || {}; const { displayName } = author || {};
const [url, setUrl] = useState(''); const accountComment = useAccountComment({ commentIndex: params?.accountCommentIndex as any });
const { publishCommentOptions, setPublishPostStore, resetPublishPostStore } = usePublishPostStore(); const subplebbitAddress = params?.subplebbitAddress || accountComment?.subplebbitAddress;
const { index, publishComment } = usePublishComment(publishCommentOptions); const { setPublishPostOptions, postIndex, publishPost, publishPostOptions, resetPublishPostOptions } = usePublishPost({ subplebbitAddress });
const textRef = useRef<HTMLTextAreaElement>(null); const textRef = useRef<HTMLTextAreaElement>(null);
const urlRef = useRef<HTMLInputElement>(null); const urlRef = useRef<HTMLInputElement>(null);
@@ -69,23 +71,18 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
} }
}; };
const hasCalledAnonAddressRef = useRef(false);
const getAnonAddressForPost = useCallback(async () => { const getAnonAddressForPost = useCallback(async () => {
if (anonMode) { if (anonMode) {
if (!hasCalledAnonAddressRef.current) { const newSigner = (await getNewSigner()) || {};
hasCalledAnonAddressRef.current = true; setPublishPostOptions({
const newSigner = (await getNewSigner()) || {}; signer: newSigner,
setPublishPostStore({ author: {
signer: newSigner, address: newSigner.address,
author: { displayName: displayName || undefined,
address: newSigner.address, },
displayName: displayName || undefined, });
},
});
}
} else { } else {
setPublishPostStore({ setPublishPostOptions({
signer: undefined, signer: undefined,
author: { author: {
address: account?.author?.address, address: account?.author?.address,
@@ -93,7 +90,7 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
}, },
}); });
} }
}, [anonMode, getNewSigner, account, setPublishPostStore, displayName]); }, [anonMode, getNewSigner, account, setPublishPostOptions, displayName]);
const onPublishPost = () => { const onPublishPost = () => {
const currentTitle = subjectRef.current?.value.trim() || ''; const currentTitle = subjectRef.current?.value.trim() || '';
@@ -109,7 +106,7 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
return; return;
} }
if ((isInAllView || isInSubscriptionsView) && !publishCommentOptions.subplebbitAddress) { if ((isInAllView || isInSubscriptionsView) && !publishPostOptions.subplebbitAddress) {
alert(t('no_board_selected_warning')); alert(t('no_board_selected_warning'));
return; return;
} }
@@ -126,31 +123,22 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
} }
} }
publishComment(); publishPost();
}; };
const params = useParams();
const accountComment = useAccountComment({ commentIndex: params?.accountCommentIndex as any });
const subplebbitAddress = params?.subplebbitAddress || accountComment?.subplebbitAddress;
useEffect(() => {
if (subplebbitAddress) {
setPublishPostStore({ subplebbitAddress });
}
}, [subplebbitAddress, setPublishPostStore]);
// redirect to pending page when pending comment is created // redirect to pending page when pending comment is created
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
if (typeof index === 'number') { if (typeof postIndex === 'number') {
resetPublishPostStore(); resetPublishPostOptions();
resetFields(); resetFields();
navigate(`/profile/${index}`); navigate(`/profile/${postIndex}`);
} }
}, [index, resetPublishPostStore, navigate]); }, [postIndex, resetPublishPostOptions, navigate]);
useEffect(() => { useEffect(() => {
if (anonMode) { if (anonMode) {
setPublishPostStore({ setPublishPostOptions({
signer: undefined, signer: undefined,
author: { author: {
address: undefined, address: undefined,
@@ -159,7 +147,7 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
}); });
getAnonAddressForPost(); getAnonAddressForPost();
} else { } else {
setPublishPostStore({ setPublishPostOptions({
signer: undefined, signer: undefined,
author: { author: {
...account?.author, ...account?.author,
@@ -176,19 +164,18 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
const { setPublishReplyOptions, resetPublishReplyOptions, replyIndex, publishReply } = usePublishReply({ cid, subplebbitAddress }); const { setPublishReplyOptions, resetPublishReplyOptions, replyIndex, publishReply } = usePublishReply({ cid, subplebbitAddress });
const getAnonAddressForReply = useCallback(async () => { const getAnonAddressForReply = useCallback(async () => {
if (anonMode && !hasCalledAnonAddressRef.current) { const existingSigner = await getExistingSigner(address);
hasCalledAnonAddressRef.current = true; if (existingSigner) {
const existingSigner = await getExistingSigner(address); setPublishReplyOptions({
if (existingSigner) { signer: existingSigner,
setPublishReplyOptions({ author: {
signer: existingSigner, address: existingSigner.address,
author: { displayName: displayName || undefined,
address: existingSigner.address, },
displayName: displayName || undefined, });
}, } else {
}); const newSigner = await getNewSigner();
} else { if (newSigner) {
const newSigner = await getNewSigner();
setPublishReplyOptions({ setPublishReplyOptions({
signer: newSigner, signer: newSigner,
author: { author: {
@@ -198,11 +185,11 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
}); });
} }
} }
}, [address, getExistingSigner, getNewSigner, setPublishReplyOptions, anonMode, displayName]); }, [address, getExistingSigner, getNewSigner, setPublishReplyOptions, displayName]);
const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => { const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const formattedContent = formatMarkdown(e.target.value); const formattedContent = formatMarkdown(e.target.value);
isInPostView ? setPublishReplyOptions({ content: formattedContent }) : setPublishPostStore({ content: formattedContent }); isInPostView ? setPublishReplyOptions({ content: formattedContent }) : setPublishPostOptions({ content: formattedContent });
}; };
const onPublishReply = () => { const onPublishReply = () => {
@@ -238,7 +225,8 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
getAnonAddressForPost(); getAnonAddressForPost();
} }
} }
}, [anonMode, getAnonAddressForPost, getAnonAddressForReply, isInPostView]); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [anonMode, isInPostView]);
// on android, auto upload file to image hosting sites with open api // on android, auto upload file to image hosting sites with open api
const [isUploading, setIsUploading] = useState(false); const [isUploading, setIsUploading] = useState(false);
@@ -253,7 +241,7 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
if (urlRef.current) { if (urlRef.current) {
urlRef.current.value = result.url; urlRef.current.value = result.url;
} }
isInPostView ? setPublishReplyOptions({ link: result.url || undefined }) : setPublishPostStore({ link: result.url || undefined }); isInPostView ? setPublishReplyOptions({ link: result.url || undefined }) : setPublishPostOptions({ link: result.url || undefined });
if (result.fileName) { if (result.fileName) {
setUploadedFileName(result.fileName); setUploadedFileName(result.fileName);
} }
@@ -277,10 +265,10 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
if (isInPostView) { if (isInPostView) {
setPublishReplyOptions({ displayName }); setPublishReplyOptions({ displayName });
} else { } else {
setPublishPostStore({ displayName }); setPublishPostOptions({ displayName });
} }
} }
}, [displayName, isInPostView, setPublishReplyOptions, setPublishPostStore]); }, [displayName, isInPostView, setPublishReplyOptions, setPublishPostOptions]);
return ( return (
<table className={styles.postFormTable}> <table className={styles.postFormTable}>
@@ -298,7 +286,7 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
if (isInPostView) { if (isInPostView) {
setPublishReplyOptions({ displayName: newDisplayName }); setPublishReplyOptions({ displayName: newDisplayName });
} else { } else {
setPublishPostStore({ displayName: newDisplayName }); setPublishPostOptions({ displayName: newDisplayName });
} }
}} }}
/> />
@@ -317,7 +305,7 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
type='text' type='text'
ref={subjectRef} ref={subjectRef}
onChange={(e) => { onChange={(e) => {
setPublishPostStore({ title: e.target.value || undefined }); setPublishPostOptions({ title: e.target.value });
}} }}
/> />
<button onClick={onPublishPost}>{t('post')}</button> <button onClick={onPublishPost}>{t('post')}</button>
@@ -342,7 +330,7 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
disabled={isUploading} disabled={isUploading}
onChange={(e) => { onChange={(e) => {
setUrl(e.target.value); setUrl(e.target.value);
isInPostView ? setPublishReplyOptions({ link: e.target.value || undefined }) : setPublishPostStore({ link: e.target.value || undefined }); isInPostView ? setPublishReplyOptions({ link: e.target.value }) : setPublishPostOptions({ link: e.target.value });
}} }}
/> />
<span className={styles.linkType}> {url && <LinkTypePreviewer link={url} />}</span> <span className={styles.linkType}> {url && <LinkTypePreviewer link={url} />}</span>
@@ -366,7 +354,7 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
<label> <label>
<input <input
type='checkbox' type='checkbox'
onChange={(e) => (isInPostView ? setPublishReplyOptions({ spoiler: e.target.checked }) : setPublishPostStore({ spoiler: e.target.checked }))} onChange={(e) => (isInPostView ? setPublishReplyOptions({ spoiler: e.target.checked }) : setPublishPostOptions({ spoiler: e.target.checked }))}
/> />
{_.capitalize(t('spoiler'))}? {_.capitalize(t('spoiler'))}?
</label> </label>
@@ -377,7 +365,7 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
<tr> <tr>
<td>{t('board')}</td> <td>{t('board')}</td>
<td> <td>
<select onChange={(e) => setPublishPostStore({ subplebbitAddress: e.target.value })} value={subplebbitAddress}> <select onChange={(e) => setPublishPostOptions({ subplebbitAddress: e.target.value })} value={subplebbitAddress}>
<option value=''>{t('choose_one')}</option> <option value=''>{t('choose_one')}</option>
{isInAllView && {isInAllView &&
defaultSubplebbitAddresses.map((address: string) => ( defaultSubplebbitAddresses.map((address: string) => (
+2 -2
View File
@@ -262,7 +262,7 @@ const ReplyModal = ({ closeModal, showReplyModal, parentCid, postCid, scrollY, s
placeholder={displayName ? undefined : _.capitalize(t('name'))} placeholder={displayName ? undefined : _.capitalize(t('name'))}
onChange={(e) => { onChange={(e) => {
setAccount({ ...account, author: { ...account?.author, displayName: e.target.value } }); setAccount({ ...account, author: { ...account?.author, displayName: e.target.value } });
setPublishReplyOptions({ displayName: e.target.value || undefined }); setPublishReplyOptions({ displayName: e.target.value });
}} }}
/> />
</div> </div>
@@ -273,7 +273,7 @@ const ReplyModal = ({ closeModal, showReplyModal, parentCid, postCid, scrollY, s
placeholder={_.capitalize(t('link'))} placeholder={_.capitalize(t('link'))}
onChange={(e) => { onChange={(e) => {
setUrl(e.target.value); setUrl(e.target.value);
setPublishReplyOptions({ link: e.target.value || undefined }); setPublishReplyOptions({ link: e.target.value });
}} }}
/> />
</div> </div>
+75
View File
@@ -0,0 +1,75 @@
import { useCallback } from 'react';
import { Comment, useAccount, usePublishComment } from '@plebbit/plebbit-react-hooks';
import useAnonMode from './use-anon-mode';
import usePublishPostStore from '../stores/use-publish-post-store';
const usePublishPost = ({ subplebbitAddress }: { subplebbitAddress?: string }) => {
const account = useAccount();
const { anonMode } = useAnonMode();
const { author, signer, title, content, link, spoiler, publishCommentOptions } = usePublishPostStore((state) => ({
author: state.author,
signer: state.signer,
title: state.title === '' ? undefined : state.title,
content: state.content === '' ? undefined : state.content,
link: state.link === '' ? undefined : state.link,
spoiler: state.spoiler || false,
publishCommentOptions: state.publishCommentOptions,
}));
const setPublishPostStore = usePublishPostStore((state) => state.setPublishPostStore);
const resetPublishPostStore = usePublishPostStore((state) => state.resetPublishPostStore);
const createBaseOptions = useCallback(() => {
const baseOptions: Comment = {
subplebbitAddress,
title,
content,
link,
spoiler,
};
if (anonMode) {
baseOptions.author = {
address: signer?.address,
displayName: author?.displayName,
};
baseOptions.signer = signer;
} else {
baseOptions.author = {
...account?.author,
displayName: author?.displayName || account?.author?.displayName,
};
}
return baseOptions;
}, [anonMode, author, content, link, signer, spoiler, subplebbitAddress, title, account]);
const setPublishPostOptions = useCallback(
(options: Partial<Comment>) => {
const baseOptions = createBaseOptions();
const sanitizedOptions = Object.entries(options).reduce((acc, [key, value]) => {
acc[key] = value === '' ? undefined : value;
return acc;
}, {} as Partial<Comment>);
const newOptions = { ...baseOptions, ...sanitizedOptions };
setPublishPostStore(newOptions);
},
[createBaseOptions, setPublishPostStore],
);
const resetPublishPostOptions = useCallback(() => resetPublishPostStore(), [resetPublishPostStore]);
const { index, publishComment } = usePublishComment(publishCommentOptions);
return {
setPublishPostOptions,
resetPublishPostOptions,
postIndex: index,
publishPost: publishComment,
publishPostOptions: publishCommentOptions,
};
};
export default usePublishPost;
+15 -9
View File
@@ -1,4 +1,4 @@
import { PublishCommentOptions } from '@plebbit/plebbit-react-hooks'; import { Comment, PublishCommentOptions } from '@plebbit/plebbit-react-hooks';
import { create } from 'zustand'; import { create } from 'zustand';
import { alertChallengeVerificationFailed } from '../lib/utils/challenge-utils'; import { alertChallengeVerificationFailed } from '../lib/utils/challenge-utils';
import useChallengesStore from './use-challenges-store'; import useChallengesStore from './use-challenges-store';
@@ -29,8 +29,17 @@ const usePublishPostStore = create<SubmitState>((set) => ({
link: undefined, link: undefined,
spoiler: undefined, spoiler: undefined,
publishCommentOptions: {}, publishCommentOptions: {},
setPublishPostStore: ({ author, displayName, signer, subplebbitAddress, title, content, link, spoiler }) => setPublishPostStore: (comment: Comment) =>
set((state) => { set((state) => {
const { subplebbitAddress, author, content, link, signer, spoiler, title } = comment;
const displayName = 'displayName' in comment ? comment.displayName || undefined : author?.displayName;
const baseAuthor = author ? { ...author } : {};
delete baseAuthor.displayName;
const updatedAuthor = displayName ? { ...baseAuthor, displayName } : baseAuthor;
const nextState = { ...state }; const nextState = { ...state };
if (author !== undefined) nextState.author = author; if (author !== undefined) nextState.author = author;
if (displayName !== undefined) nextState.displayName = displayName; if (displayName !== undefined) nextState.displayName = displayName;
@@ -55,15 +64,12 @@ const usePublishPostStore = create<SubmitState>((set) => ({
}, },
}; };
if (nextState.signer) { if (Object.keys(updatedAuthor).length > 0) {
publishCommentOptions.signer = nextState.signer; publishCommentOptions.author = updatedAuthor;
} }
if (nextState.author || nextState.displayName) { if (nextState.signer) {
publishCommentOptions.author = { publishCommentOptions.signer = nextState.signer;
...nextState.author,
displayName: nextState.displayName,
};
} }
nextState.publishCommentOptions = publishCommentOptions; nextState.publishCommentOptions = publishCommentOptions;