Files
5chan/src/components/post-form/post-form.tsx
T

433 lines
14 KiB
TypeScript
Raw Normal View History

import { useCallback, useEffect, useRef, useState } from 'react';
2024-03-20 13:08:08 +01:00
import { useTranslation } from 'react-i18next';
2024-04-26 19:13:23 +02:00
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import {
Comment,
PublishCommentOptions,
setAccount,
useAccount,
useAccountComment,
useComment,
useEditedComment,
usePublishComment,
useSubplebbit,
} from '@plebbit/plebbit-react-hooks';
2024-04-26 19:13:23 +02:00
import { create } from 'zustand';
import { alertChallengeVerificationFailed } from '../../lib/utils/challenge-utils';
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 useChallengesStore from '../../stores/use-challenges-store';
import styles from './post-form.module.css';
2024-04-28 17:12:19 +02:00
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';
2024-04-26 19:13:23 +02:00
type SubmitState = {
author: any | undefined;
signer: any | undefined;
2024-04-26 19:13:23 +02:00
subplebbitAddress: string | undefined;
title: string | undefined;
content: string | undefined;
link: string | undefined;
spoiler: boolean | undefined;
2024-04-26 19:13:23 +02:00
publishCommentOptions: PublishCommentOptions;
setSubmitStore: (data: Partial<SubmitState>) => void;
resetSubmitStore: () => void;
};
const { addChallenge } = useChallengesStore.getState();
2024-04-26 19:13:23 +02:00
const useSubmitStore = create<SubmitState>((set) => ({
author: undefined,
signer: undefined,
2024-04-26 19:13:23 +02:00
subplebbitAddress: undefined,
title: undefined,
content: undefined,
link: undefined,
spoiler: undefined,
2024-04-26 19:13:23 +02:00
publishCommentOptions: {},
setSubmitStore: ({ author, signer, subplebbitAddress, title, content, link, spoiler }) =>
2024-04-26 19:13:23 +02:00
set((state) => {
const nextState = { ...state };
if (author !== undefined) nextState.author = author;
if (signer !== undefined) nextState.signer = signer;
2024-04-26 19:13:23 +02:00
if (subplebbitAddress !== undefined) nextState.subplebbitAddress = subplebbitAddress;
if (title !== undefined) nextState.title = title || undefined;
if (content !== undefined) nextState.content = content || undefined;
if (link !== undefined) nextState.link = link || undefined;
if (spoiler !== undefined) nextState.spoiler = spoiler || undefined;
2024-04-26 19:13:23 +02:00
nextState.publishCommentOptions = {
author: nextState.author,
signer: nextState.signer,
subplebbitAddress: nextState.subplebbitAddress,
title: nextState.title,
content: nextState.content,
link: nextState.link,
spoiler: nextState.spoiler,
2024-04-26 19:13:23 +02:00
onChallenge: (...args: any) => addChallenge(args),
onChallengeVerification: alertChallengeVerificationFailed,
onError: (error: Error) => {
console.error(error);
let errorMessage = error.message;
alert(errorMessage);
},
};
return nextState;
}),
resetSubmitStore: () =>
set({
author: undefined,
signer: undefined,
subplebbitAddress: undefined,
title: undefined,
content: undefined,
link: undefined,
spoiler: undefined,
publishCommentOptions: {},
}),
2024-04-26 19:13:23 +02:00
}));
2024-03-20 13:00:11 +01:00
export const LinkTypePreviewer = ({ link }: { link: string }) => {
2024-05-31 16:51:22 +02:00
const { t } = useTranslation();
const mediaInfo = getLinkMediaInfo(link);
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, postCid }: { closeForm: () => void; postCid: string }) => {
2024-04-28 17:12:19 +02:00
const { t } = useTranslation();
const account = useAccount();
const author = account?.author || {};
const { displayName } = author || {};
2024-04-26 19:13:23 +02:00
const [url, setUrl] = useState('');
const { title, content, link, publishCommentOptions, setSubmitStore, resetSubmitStore } = useSubmitStore();
const { index, publishComment } = usePublishComment(publishCommentOptions);
const textRef = useRef<HTMLTextAreaElement>(null);
const urlRef = useRef<HTMLInputElement>(null);
const subjectRef = useRef<HTMLInputElement>(null);
const location = useLocation();
const isInAllView = isAllView(location.pathname, useParams());
const isInSubscriptionsView = isSubscriptionsView(location.pathname, useParams());
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 = '';
}
if (urlRef.current) {
urlRef.current.value = '';
}
if (subjectRef.current) {
subjectRef.current.value = '';
}
};
2024-08-06 21:51:45 +02:00
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,
},
});
}
2024-08-06 21:51:45 +02:00
}, [anonMode, getNewSigner, setSubmitStore, displayName]);
const onPublishPost = async () => {
2024-04-26 19:13:23 +02:00
if (!title && !content && !link) {
alert(`Cannot post empty comment`);
return;
}
if (link && !isValidURL(link)) {
alert('The provided link is not a valid URL.');
2024-04-26 19:13:23 +02:00
return;
}
2024-08-06 21:51:45 +02:00
publishComment();
2024-04-26 19:13:23 +02:00
};
const params = useParams();
const accountComment = useAccountComment({ commentIndex: params?.accountCommentIndex as any });
const subplebbitAddress = params?.subplebbitAddress || accountComment?.subplebbitAddress;
useEffect(() => {
if (subplebbitAddress) {
setSubmitStore({ subplebbitAddress });
}
}, [subplebbitAddress, setSubmitStore]);
// redirect to pending page when pending comment is created
const navigate = useNavigate();
useEffect(() => {
if (typeof index === 'number') {
resetSubmitStore();
resetFields();
2024-04-26 19:13:23 +02:00
navigate(`/profile/${index}`);
}
}, [index, resetSubmitStore, navigate]);
// in post page, publish a reply to the post
const isInPostView = isPostPageView(location.pathname, params);
const cid = params?.commentCid as string;
const { setPublishReplyOptions, resetPublishReplyOptions, replyIndex, publishReply } = useReply({ cid, subplebbitAddress });
2024-08-06 21:51:45 +02:00
const getAnonAddressForReply = useCallback(async () => {
if (anonMode && !hasCalledAnonAddressRef.current) {
hasCalledAnonAddressRef.current = true;
const existingSigner = getExistingSigner(address);
if (existingSigner) {
console.log('onPublishReply - existingSigner:', existingSigner);
setPublishReplyOptions({
signer: existingSigner,
author: {
displayName,
address: existingSigner.address,
},
});
} else {
2024-08-06 21:51:45 +02:00
const newSigner = await getNewSigner();
setPublishReplyOptions({
signer: newSigner,
author: {
displayName,
address: newSigner.address,
},
});
}
}
2024-08-06 21:51:45 +02:00
}, [address, getExistingSigner, getNewSigner, setPublishReplyOptions, displayName, anonMode]);
const onPublishReply = () => {
const currentContent = textRef.current?.value || '';
const currentUrl = urlRef.current?.value || '';
if (!currentContent.trim() && !currentUrl) {
alert(`Cannot post empty comment`);
return;
}
if (currentUrl && !isValidURL(currentUrl)) {
alert('The provided link is not a valid URL.');
return;
}
2024-08-06 21:51:45 +02:00
publishReply();
};
useEffect(() => {
if (typeof replyIndex === 'number') {
resetPublishReplyOptions();
resetFields();
closeForm();
}
}, [replyIndex, resetPublishReplyOptions, closeForm]);
2024-08-06 21:51:45 +02:00
useEffect(() => {
if (anonMode) {
if (isInPostView) {
getAnonAddressForReply();
} else {
getAnonAddressForPost();
}
}
}, [anonMode, getAnonAddressForPost, getAnonAddressForReply, isInPostView]);
return (
2024-04-24 15:20:55 +02:00
<table className={styles.postFormTable}>
<tbody>
<tr>
2024-04-28 17:12:19 +02:00
<td>{t('name')}</td>
<td>
2024-04-26 19:13:23 +02:00
<input
type='text'
2024-04-28 17:12:19 +02:00
placeholder={!displayName ? _.capitalize(t('anonymous')) : undefined}
2024-04-26 19:13:23 +02:00
defaultValue={displayName || undefined}
onChange={(e) => setAccount({ ...account, author: { ...account?.author, displayName: e.target.value } })}
/>
{isInPostView && <button onClick={onPublishReply}>{t('post')}</button>}
</td>
</tr>
{!isInPostView && (
<tr>
2024-04-28 17:12:19 +02:00
<td>{t('subject')}</td>
<td>
<input
type='text'
ref={subjectRef}
onChange={(e) => {
setSubmitStore({ title: e.target.value });
}}
/>
2024-04-28 17:12:19 +02:00
<button onClick={onPublishPost}>{t('post')}</button>
</td>
</tr>
)}
<tr>
2024-04-28 17:12:19 +02:00
<td>{t('comment')}</td>
2024-04-24 16:47:51 +02:00
<td>
<textarea
cols={48}
rows={4}
wrap='soft'
ref={textRef}
onChange={(e) => {
const content = e.target.value.replace(/\n/g, '\n\n');
isInPostView ? setPublishReplyOptions({ content }) : setSubmitStore({ content });
}}
/>
2024-04-24 16:47:51 +02:00
</td>
</tr>
<tr>
2024-04-28 17:12:19 +02:00
<td>{t('link')}</td>
<td className={styles.linkField}>
2024-04-26 19:13:23 +02:00
<input
type='text'
autoCorrect='off'
autoComplete='off'
spellCheck='false'
ref={urlRef}
2024-04-26 19:13:23 +02:00
onChange={(e) => {
setUrl(e.target.value);
isInPostView ? setPublishReplyOptions({ link: e.target.value }) : setSubmitStore({ link: e.target.value });
2024-04-26 19:13:23 +02:00
}}
/>
<span className={styles.linkType}> {url && <LinkTypePreviewer link={url} />}</span>
</td>
</tr>
<tr className={styles.spoilerButton}>
<td>{t('options')}</td>
<td>
[
<label>
<input
type='checkbox'
onChange={(e) => (isInPostView ? setPublishReplyOptions({ spoiler: e.target.checked }) : setSubmitStore({ spoiler: e.target.checked }))}
/>
2024-05-31 17:09:20 +02:00
{_.capitalize(t('spoiler'))}?
</label>
]
</td>
</tr>
{(isInAllView || isInSubscriptionsView) && (
<tr>
<td>{t('board')}</td>
<td>
<select onChange={(e) => setSubmitStore({ subplebbitAddress: e.target.value })} value={subplebbitAddress}>
2024-05-31 17:09:20 +02:00
<option value=''>--{t('no_board_selected')}--</option>
{isInAllView &&
defaultSubplebbitAddresses.map((address: string) => (
<option key={address} value={address}>
{address}
</option>
))}
{isInSubscriptionsView &&
subscriptions.map((sub: string) => (
<option key={sub} value={sub}>
{sub}
</option>
))}
</select>
</td>
</tr>
)}
</tbody>
</table>
);
};
const PostForm = () => {
2024-03-20 13:08:08 +01:00
const { t } = useTranslation();
2024-04-08 17:32:12 +02:00
const location = useLocation();
const params = useParams();
const isInDescriptionView = isDescriptionView(location.pathname, params);
const isInPostView = isPostPageView(location.pathname, params);
2024-04-08 17:32:12 +02:00
const isInRulesView = isRulesView(location.pathname, params);
const isInAllView = isAllView(location.pathname, params);
const isInSubscriptionsView = isSubscriptionsView(location.pathname, useParams());
2024-04-08 17:32:12 +02:00
const post = useComment({ commentCid: useParams().commentCid });
let comment: Comment = post;
// handle pending mod or author edit
const { editedComment } = useEditedComment({ comment });
if (editedComment) {
comment = editedComment;
}
const { deleted, locked, removed, postCid } = comment || {};
2024-04-08 17:32:12 +02:00
const isThreadClosed = deleted || locked || removed || isInDescriptionView || isInRulesView;
const [showForm, setShowForm] = useState(false);
2024-03-20 13:08:08 +01:00
const subplebbit = useSubplebbit({ subplebbitAddress: params?.subplebbitAddress });
const { isOffline, offlineTitle } = useIsSubplebbitOffline(subplebbit);
2024-03-20 13:00:11 +01:00
return (
2024-03-21 15:21:33 +01:00
<>
2024-04-24 15:20:55 +02:00
<div className={styles.postFormDesktop}>
{!(isInAllView || isInSubscriptionsView) && showForm && (isOffline || isOffline) && <div className={styles.offlineBoard}>{offlineTitle}</div>}
{isThreadClosed ? (
<div className={styles.closed}>
{t('thread_closed')}
<br />
{t('may_not_reply')}
</div>
) : !showForm ? (
<div>
[
<button className='button' onClick={() => setShowForm(true)}>
{isInPostView ? t('post_a_reply') : t('start_new_thread')}
</button>
]
</div>
) : (
<PostFormTable closeForm={() => setShowForm(false)} postCid={postCid} />
)}
2024-03-21 15:21:33 +01:00
</div>
2024-04-24 15:20:55 +02:00
<div className={styles.postFormMobile}>
{!(isInAllView || isInSubscriptionsView) && showForm && (isOffline || isOffline) && <div className={styles.offlineBoard}>{offlineTitle}</div>}
2024-04-08 17:46:36 +02:00
{isThreadClosed ? (
<div className={styles.closed}>
{t('thread_closed')}
2024-04-08 17:46:36 +02:00
<br />
{t('may_not_reply')}
2024-04-08 17:46:36 +02:00
</div>
) : (
2024-04-24 15:20:55 +02:00
<>
<button className={`${styles.showFormButton} button`} onClick={() => setShowForm(showForm ? false : true)}>
{showForm ? t('close_post_form') : isInPostView ? t('post_a_reply') : t('start_new_thread')}
2024-04-24 15:20:55 +02:00
</button>
{showForm && <PostFormTable closeForm={() => setShowForm(false)} postCid={postCid} />}
<hr />
2024-04-24 15:20:55 +02:00
</>
2024-04-08 17:46:36 +02:00
)}
2024-03-21 15:21:33 +01:00
</div>
</>
2024-03-20 13:00:11 +01:00
);
};
export default PostForm;