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

447 lines
16 KiB
TypeScript
Raw Normal View History

2025-11-25 13:13:38 +01:00
import { 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, setAccount, useAccount, useAccountComment, useAccountSubplebbits, useEditedComment } from '@plebbit/plebbit-react-hooks';
import Plebbit from '@plebbit/plebbit-js';
import useSubplebbitsStore from '@plebbit/plebbit-react-hooks/dist/stores/subplebbits';
import useSubplebbitsPagesStore from '@plebbit/plebbit-react-hooks/dist/stores/subplebbits-pages';
import { getHasThumbnail, getLinkMediaInfo } from '../../lib/utils/media-utils';
import { formatMarkdown } from '../../lib/utils/post-utils';
import { isValidURL } from '../../lib/utils/url-utils';
import { isAllView, isCatalogView, isModQueueView, isModView, isPostPageView, isSubscriptionsView } from '../../lib/utils/view-utils';
import { useDirectories } from '../../hooks/use-directories';
import { useResolvedSubplebbitAddress } from '../../hooks/use-resolved-subplebbit-address';
2025-01-30 17:09:21 +01:00
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 styles from './post-form.module.css';
import { Capacitor } from '@capacitor/core';
import _ from 'lodash';
const isAndroid = Capacitor.getPlatform() === 'android';
// Separate component for offline alert to isolate rerenders from updatingState
// Only this component will rerender when updatingState changes, not the whole PostForm
const OfflineAlert = ({ subplebbitAddress }: { subplebbitAddress: string | undefined }) => {
const subplebbit = useSubplebbitsStore((state) => (subplebbitAddress ? state.subplebbits[subplebbitAddress] : undefined));
const { isOffline, isOnlineStatusLoading, offlineTitle } = useIsSubplebbitOffline(subplebbit);
if (!isOffline && !isOnlineStatusLoading) {
return null;
}
return <div className={styles.offlineBoard}>{offlineTitle}</div>;
};
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('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();
2025-01-30 17:09:21 +01:00
const params = useParams();
const account = useAccount();
2025-01-30 17:09:21 +01:00
const [url, setUrl] = useState('');
const author = account?.author || {};
const { displayName } = author || {};
2025-01-30 17:09:21 +01:00
const accountComment = useAccountComment({ commentIndex: params?.accountCommentIndex as any });
const resolvedAddress = useResolvedSubplebbitAddress();
const subplebbitAddress = resolvedAddress || accountComment?.subplebbitAddress;
2025-01-30 17:09:21 +01:00
const { setPublishPostOptions, postIndex, publishPost, publishPostOptions, resetPublishPostOptions } = usePublishPost({ subplebbitAddress });
2024-04-26 19:13:23 +02:00
const textRef = useRef<HTMLTextAreaElement>(null);
const urlRef = useRef<HTMLInputElement>(null);
const subjectRef = useRef<HTMLInputElement>(null);
const location = useLocation();
2024-10-29 17:40:09 +01:00
const isInAllView = isAllView(location.pathname);
const isInModView = isModView(location.pathname);
const isInSubscriptionsView = isSubscriptionsView(location.pathname, useParams());
const subscriptions = account?.subscriptions || [];
const directories = useDirectories();
const { accountSubplebbits } = useAccountSubplebbits();
const accountSubplebbitAddresses = Object.keys(accountSubplebbits);
2025-01-31 23:53:24 +01:00
const [lengthError, setLengthError] = useState<string | null>(null);
const checkContentLength = useRef(
_.debounce((content: string, t: Function) => {
const length = content.trim().length;
if (length > 2000) {
setLengthError(`${t('error')}: ${t('comment_field_too_long', { length })}`);
} else {
setLengthError(null);
}
}, 1000),
).current;
const resetFields = () => {
if (textRef.current) {
textRef.current.value = '';
}
if (urlRef.current) {
urlRef.current.value = '';
}
if (subjectRef.current) {
subjectRef.current.value = '';
}
};
const onPublishPost = () => {
const currentTitle = subjectRef.current?.value.trim() || '';
const currentContent = textRef.current?.value.trim() || '';
const currentUrl = urlRef.current?.value.trim() || '';
2025-01-31 23:53:24 +01:00
checkContentLength.cancel();
setLengthError(null);
if (!currentTitle && !currentContent && !currentUrl) {
alert(t('empty_comment_alert'));
2024-04-26 19:13:23 +02:00
return;
}
if (currentUrl && !isValidURL(currentUrl)) {
alert(t('invalid_url_alert'));
return;
}
2025-01-31 23:53:24 +01:00
if (currentContent.length > 2000) {
alert(t('error') + ': ' + t('field_too_long'));
return;
}
if ((isInAllView || isInSubscriptionsView || isInModView) && !publishPostOptions.subplebbitAddress) {
alert(t('no_board_selected_warning'));
2024-04-26 19:13:23 +02:00
return;
}
if (!isInPostView) {
const linkMediaInfo = getLinkMediaInfo(currentUrl);
const hasThumbnail = getHasThumbnail(linkMediaInfo, currentUrl);
if (!hasThumbnail) {
const confirmMessage = t('missing_link_confirm');
if (!window.confirm(confirmMessage)) {
return;
}
}
}
2025-01-30 17:09:21 +01:00
publishPost();
2024-04-26 19:13:23 +02:00
};
// redirect to pending page when pending comment is created
const navigate = useNavigate();
useEffect(() => {
2025-01-30 17:09:21 +01:00
if (typeof postIndex === 'number') {
resetPublishPostOptions();
resetFields();
navigate(`/pending/${postIndex}`);
2024-04-26 19:13:23 +02:00
}
2025-01-30 17:09:21 +01:00
}, [postIndex, resetPublishPostOptions, navigate]);
// in post page, publish a reply to the post
const isInPostView = isPostPageView(location.pathname, params);
const cid = params?.commentCid as string;
2024-08-06 21:57:28 +02:00
const { setPublishReplyOptions, resetPublishReplyOptions, replyIndex, publishReply } = usePublishReply({ cid, subplebbitAddress });
const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const formattedContent = formatMarkdown(e.target.value);
2025-01-30 17:09:21 +01:00
isInPostView ? setPublishReplyOptions({ content: formattedContent }) : setPublishPostOptions({ content: formattedContent });
2025-01-31 23:53:24 +01:00
checkContentLength(formattedContent, t);
};
const onPublishReply = () => {
const currentContent = textRef.current?.value.trim() || '';
const currentUrl = urlRef.current?.value.trim() || '';
2025-01-31 23:53:24 +01:00
checkContentLength.cancel();
setLengthError(null);
if (!currentContent && !currentUrl) {
alert(t('empty_comment_alert'));
return;
}
if (currentUrl && !isValidURL(currentUrl)) {
alert(t('invalid_url_alert'));
return;
}
2025-01-31 23:53:24 +01:00
if (currentContent.length > 2000) {
alert(t('error') + ': ' + t('field_too_long'));
return;
}
2024-08-06 21:51:45 +02:00
publishReply();
};
useEffect(() => {
if (typeof replyIndex === 'number') {
resetPublishReplyOptions();
resetFields();
closeForm();
}
}, [replyIndex, resetPublishReplyOptions, closeForm]);
// on android, auto upload file to image hosting sites with open api
const [isUploading, setIsUploading] = useState(false);
const [uploadedFileName, setUploadedFileName] = useState<string | null>(null);
const handleUpload = async () => {
try {
setIsUploading(true);
const result = await FileUploader.pickAndUploadMedia();
console.log('Upload result:', result);
if (result.url) {
setUrl(result.url);
if (urlRef.current) {
urlRef.current.value = result.url;
}
2025-01-30 17:09:21 +01:00
isInPostView ? setPublishReplyOptions({ link: result.url || undefined }) : setPublishPostOptions({ link: result.url || undefined });
if (result.fileName) {
setUploadedFileName(result.fileName);
}
}
} catch (error) {
console.error('Upload failed:', error);
if (error instanceof Error && error.message !== 'File selection cancelled') {
alert(`${t('upload_failed')}: ${error.message}`);
} else if (typeof error === 'string' && error !== 'File selection cancelled') {
alert(`${t('upload_failed')}: ${error}`);
}
} finally {
setIsUploading(false);
}
};
2025-01-26 22:25:56 +01:00
const hasInitializedDisplayName = useRef(false);
useEffect(() => {
if (displayName && !hasInitializedDisplayName.current) {
hasInitializedDisplayName.current = true;
if (isInPostView) {
setPublishReplyOptions({ displayName });
} else {
2025-01-30 17:09:21 +01:00
setPublishPostOptions({ displayName });
2025-01-26 22:25:56 +01:00
}
}
2025-01-30 17:09:21 +01:00
}, [displayName, isInPostView, setPublishReplyOptions, setPublishPostOptions]);
2025-01-26 22:25:56 +01:00
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}
2024-08-08 17:48:45 +02:00
onChange={(e) => {
2025-01-25 22:07:45 +01:00
const newDisplayName = e.target.value.trim() || undefined;
setAccount({ ...account, author: { ...account?.author, displayName: newDisplayName } });
if (isInPostView) {
2025-01-25 22:07:45 +01:00
setPublishReplyOptions({ displayName: newDisplayName });
} else {
2025-01-30 17:09:21 +01:00
setPublishPostOptions({ displayName: newDisplayName });
}
2024-08-08 17:48:45 +02:00
}}
2024-04-26 19:13:23 +02:00
/>
{isInPostView && (
<button onClick={onPublishReply} disabled={isUploading}>
{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) => {
2025-01-30 17:09:21 +01:00
setPublishPostOptions({ 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={handleContentChange} />
2025-01-31 23:53:24 +01:00
{lengthError && <div className={styles.error}>{lengthError}</div>}
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}
disabled={isUploading}
2024-04-26 19:13:23 +02:00
onChange={(e) => {
setUrl(e.target.value);
2025-01-30 17:09:21 +01:00
isInPostView ? setPublishReplyOptions({ link: e.target.value }) : setPublishPostOptions({ link: e.target.value });
2024-04-26 19:13:23 +02:00
}}
/>
<span className={styles.linkType}> {url && <LinkTypePreviewer link={url} />}</span>
</td>
</tr>
{isAndroid && (
<tr className={styles.uploadButton}>
<td>{t('file')}</td>
<td>
<button onClick={handleUpload} disabled={isUploading}>
2024-11-04 17:42:14 +01:00
{isUploading ? t('uploading') : t('choose_file')}
</button>
2024-11-04 17:42:14 +01:00
<span>{uploadedFileName ? uploadedFileName : t('no_file_chosen')}</span>
</td>
</tr>
)}
<tr className={styles.spoilerButton}>
<td>{t('options')}</td>
<td>
[
<label>
<input
type='checkbox'
2025-01-30 17:09:21 +01:00
onChange={(e) => (isInPostView ? setPublishReplyOptions({ spoiler: e.target.checked }) : setPublishPostOptions({ spoiler: e.target.checked }))}
/>
2024-05-31 17:09:20 +02:00
{_.capitalize(t('spoiler'))}?
</label>
]
</td>
</tr>
{(isInAllView || isInSubscriptionsView || isInModView) && (
<tr>
<td>{t('board')}</td>
<td>
2025-01-30 17:09:21 +01:00
<select onChange={(e) => setPublishPostOptions({ subplebbitAddress: e.target.value })} value={subplebbitAddress}>
2024-10-13 18:49:45 +02:00
<option value=''>{t('choose_one')}</option>
{isInAllView &&
directories
.filter((subplebbit) => subplebbit.title && subplebbit.address)
.map((subplebbit) => (
<option key={subplebbit.address} value={subplebbit.address}>
{subplebbit.title}
</option>
))}
{isInModView &&
accountSubplebbitAddresses.map((address: string) => (
<option key={address} value={address}>
{address && Plebbit.getShortAddress({ 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 isInPostView = isPostPageView(location.pathname, params);
2024-10-29 17:40:09 +01:00
const isInAllView = isAllView(location.pathname);
const isInModView = isModView(location.pathname);
const isInModQueueView = isModQueueView(location.pathname);
const isInSubscriptionsView = isSubscriptionsView(location.pathname, params);
2025-12-29 16:40:33 +01:00
const isInCatalogView = isCatalogView(location.pathname, params);
2024-04-08 17:32:12 +02:00
const commentCid = params?.commentCid;
const post = useSubplebbitsPagesStore((state) => state.comments[commentCid as string]);
let comment: Comment = post;
// handle pending mod or author edit
const { editedComment } = useEditedComment({ comment });
if (editedComment) {
comment = editedComment;
}
const { deleted, locked, removed, postCid } = comment || {};
const isThreadClosed = deleted || locked || removed;
const [showForm, setShowForm] = useState(false);
2024-03-20 13:08:08 +01:00
const accountComment = useAccountComment({ commentIndex: params?.accountCommentIndex as any });
const resolvedAddress = useResolvedSubplebbitAddress();
const subplebbitAddress = resolvedAddress || accountComment?.subplebbitAddress;
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 || isInModView) && showForm && <OfflineAlert subplebbitAddress={subplebbitAddress} />}
{isInModQueueView ? (
<div className={styles.modQueueTitle}>{t('moderation_queue')}</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 || isInModView) && showForm && <OfflineAlert subplebbitAddress={subplebbitAddress} />}
{isInModQueueView ? (
<div className={styles.modQueueTitle}>{t('moderation_queue')}</div>
) : isThreadClosed ? (
2024-04-08 17:46:36 +02:00
<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} />}
2024-04-24 15:20:55 +02:00
</>
2024-04-08 17:46:36 +02:00
)}
2025-12-29 16:40:33 +01:00
{isInCatalogView && <hr />}
2024-03-21 15:21:33 +01:00
</div>
</>
2024-03-20 13:00:11 +01:00
);
};
export default PostForm;