import { useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Link, useLocation, useNavigationType, useParams } from 'react-router-dom'; import { Virtuoso, VirtuosoHandle, StateSnapshot } from 'react-virtuoso'; import { Comment, useAuthorAvatar, useEditedComment, useReplies } from '@plebbit/plebbit-react-hooks'; import Plebbit from '@plebbit/plebbit-js'; import styles from '../../views/post/post.module.css'; import { shouldShowSnow } from '../../lib/snow'; import { getHasThumbnail } from '../../lib/utils/media-utils'; import { getTextColorForBackground, hashStringToColor } from '../../lib/utils/post-utils'; import { getFormattedDate, getFormattedTimeAgo } from '../../lib/utils/time-utils'; import { isAllView, isModQueueView, isPendingPostView, isPostPageView, isSubscriptionsView } from '../../lib/utils/view-utils'; import useModQueueStore from '../../stores/use-mod-queue-store'; import { useDefaultSubplebbits } from '../../hooks/use-default-subplebbits'; import { getBoardPath } from '../../lib/utils/route-utils'; import useAvatarVisibilityStore from '../../stores/use-avatar-visibility-store'; import useAuthorAddressClick from '../../hooks/use-author-address-click'; import { useCommentMediaInfo } from '../../hooks/use-comment-media-info'; import useCountLinksInReplies from '../../hooks/use-count-links-in-replies'; import useHide from '../../hooks/use-hide'; import useStateString from '../../hooks/use-state-string'; import useScrollToReply from '../../hooks/use-scroll-to-reply'; import CommentContent from '../comment-content'; import CommentMedia from '../comment-media'; import LoadingEllipsis from '../loading-ellipsis'; import PostMenuMobile from './post-menu-mobile'; import ReplyQuotePreview from '../reply-quote-preview'; import Tooltip from '../tooltip'; import { PostProps } from '../../views/post/post'; import _ from 'lodash'; import useReplyModalStore from '../../stores/use-reply-modal-store'; import { selectPostMenuProps } from '../../lib/utils/post-menu-props'; // Store scroll position for replies virtuoso across navigations const lastVirtuosoStates: { [key: string]: StateSnapshot } = {}; const PostInfoAndMedia = ({ post, postReplyCount = 0, roles, threadNumber }: PostProps) => { const { t } = useTranslation(); const defaultSubplebbits = useDefaultSubplebbits(); const { author, cid, deleted, link, linkHeight, linkWidth, locked, parentCid, pinned, postCid, reason, removed, state, subplebbitAddress, timestamp, thumbnailUrl } = post || {}; const boardPath = subplebbitAddress ? getBoardPath(subplebbitAddress, defaultSubplebbits) : undefined; const isReply = parentCid; const title = post?.title?.trim(); const { address, shortAddress } = author || {}; const displayName = author?.displayName?.trim(); const authorRole = roles?.[address]?.role?.replace('moderator', 'mod'); const { imageUrl: avatarImageUrl } = useAuthorAvatar({ author }); const { hideAvatars } = useAvatarVisibilityStore(); const params = useParams(); const location = useLocation(); const isInAllView = isAllView(location.pathname); const isInPostPageView = isPostPageView(location.pathname, params); const isInSubscriptionsView = isSubscriptionsView(location.pathname, params); const isInModQueueView = isModQueueView(location.pathname); const { getAlertThresholdSeconds } = useModQueueStore(); const commentMediaInfo = useCommentMediaInfo(link, thumbnailUrl, linkWidth, linkHeight); const hasThumbnail = getHasThumbnail(commentMediaInfo, link); // Check if post is awaiting approval and over threshold (for mod queue view) const approved = post?.approved; const alreadyApproved = approved === true; const alreadyRejected = removed === true; const isAwaitingApproval = isInModQueueView && !alreadyApproved && !alreadyRejected; const timeWaiting = timestamp ? Date.now() / 1000 - timestamp : 0; const alertThresholdSeconds = getAlertThresholdSeconds(); const isOverThreshold = isAwaitingApproval && timeWaiting > alertThresholdSeconds; const stateString = useStateString(post); const postMenuProps = useMemo(() => selectPostMenuProps(post), [post]); const handleUserAddressClick = useAuthorAddressClick(); const numberOfPostsByAuthor = document.querySelectorAll(`[data-author-address="${shortAddress}"][data-post-cid="${postCid}"]`).length; const userID = address && Plebbit.getShortAddress({ address }); // should not be shortened to less than 12 characters, because users can create unlimited addresses/IDs before authenticating or passing challenges, so if the ID is short enough they can spoof it to troll users with the same ID const userIDBackgroundColor = hashStringToColor(userID); const userIDTextColor = getTextColorForBackground(userIDBackgroundColor); const { hidden } = useHide(post); const { openReplyModal } = useReplyModalStore(); const onReplyModalClick = () => { deleted ? isReply ? alert(t('this_reply_was_deleted')) : alert(t('this_thread_was_deleted')) : removed ? isReply ? alert(t('this_reply_was_removed')) : alert(t('this_thread_was_removed')) : openReplyModal && openReplyModal(cid, post?.number, postCid, threadNumber, subplebbitAddress); }; return ( <>
{removed ? ( _.capitalize(t('removed')) ) : deleted ? ( _.capitalize(t('deleted')) ) : displayName ? ( displayName.length <= 20 ? ( displayName ) : ( ) ) : ( _.capitalize(t('anonymous')) )}{' '} {!(deleted || removed) && authorRole && ( {' '} ## Board {authorRole}{' '}   )} {author?.avatar && !(deleted || removed) && !hideAvatars && avatarImageUrl ? ( ) : null} (ID: {''} {removed ? ( _.lowerCase(t('removed')) ) : deleted ? ( _.lowerCase(t('deleted')) ) : ( handleUserAddressClick(userID, postCid)} style={{ backgroundColor: userIDBackgroundColor, color: userIDTextColor }} > {userID} } content={`${numberOfPostsByAuthor === 1 ? t('1_post_by_this_id') : t('x_posts_by_this_id', { number: numberOfPostsByAuthor })}`} showTooltip={isInPostPageView || postReplyCount < 6} /> )} ){' '} {pinned && ( )} {locked && ( )} {title && ( {title.length <= 30 ? ( {title} ) : ( {title.slice(0, 30) + '(...)'}} content={title.length < 1000 ? title : title.slice(0, 1000) + `... ${t('title_too_long')}`} /> )} )} {subplebbitAddress && (isInAllView || isInSubscriptionsView) && !isReply && boardPath && (
{' '} Board: {boardPath}
)} {isInModQueueView && isOverThreshold ? ( <> {getFormattedDate(timestamp)}
} content={getFormattedTimeAgo(timestamp)} /> ( {getFormattedTimeAgo(timestamp)}) ) : ( {getFormattedDate(timestamp)}} content={getFormattedTimeAgo(timestamp)} /> )}{' '} {cid ? ( !cid && e.preventDefault()} > No. {post?.number || '?'} ) : ( <> No. {state === 'failed' || stateString === 'Failed' ? _.capitalize(t('failed')) : state === 'pending' ? _.capitalize(t('pending')) : ''} )}
{(hasThumbnail || link) && !(deleted || removed) && } ); }; const PostMediaContent = ({ post, link }: { post: any; link: string }) => { const [showThumbnail, setShowThumbnail] = useState(true); const { thumbnailUrl, linkWidth, linkHeight, spoiler, deleted, removed, parentCid } = post || {}; const commentMediaInfo = useCommentMediaInfo(link, thumbnailUrl, linkWidth, linkHeight); const hasThumbnail = getHasThumbnail(commentMediaInfo, link); return ( hasThumbnail && ( ) ); }; const ReplyBacklinks = ({ post }: PostProps) => { const { cid, parentCid } = post || {}; const { replies } = useReplies({ comment: post, flat: true }); return ( cid && parentCid && replies.length > 0 && (
{replies.map( (reply: Comment, index: number) => reply?.parentCid === cid && reply?.cid && !(reply?.deleted || reply?.removed) && , )}
) ); }; const Reply = ({ postReplyCount, reply, roles, threadNumber }: PostProps) => { let post = reply; // handle pending mod or author edit const { editedComment } = useEditedComment({ comment: reply }); if (editedComment) { post = editedComment; } const { author, cid, deleted, postCid, reason, removed, subplebbitAddress } = post || {}; const defaultSubplebbits = useDefaultSubplebbits(); const boardPath = subplebbitAddress ? getBoardPath(subplebbitAddress, defaultSubplebbits) : undefined; const location = useLocation(); const route = boardPath ? `/${boardPath}/thread/${cid}` : `/thread/${cid}`; const isRouteLinkToReply = cid ? location.pathname.startsWith(route) : false; const { hidden } = useHide({ cid }); return (
{!hidden && (!(removed || deleted) || ((removed || deleted) && reason)) && }
); }; const PostMobile = ({ post, roles, showAllReplies, showReplies = true, targetReplyCid, isModQueue, modQueueStatus, modQueueError, isPublishing, onApprove, onReject, }: PostProps) => { const { t } = useTranslation(); const { author, cid, pinned, postCid, replyCount, state, subplebbitAddress } = post || {}; const params = useParams(); const location = useLocation(); const navigationType = useNavigationType(); const isInPendingPostView = isPendingPostView(location.pathname, params); const isInPostView = isPostPageView(location.pathname, params); const defaultSubplebbits = useDefaultSubplebbits(); const boardPath = subplebbitAddress ? getBoardPath(subplebbitAddress, defaultSubplebbits) : undefined; const linksCount = useCountLinksInReplies(post); const { replies, hasMore, loadMore } = useReplies({ comment: post }); const isInPostPageView = isPostPageView(location.pathname, params); const { hidden, unhide } = useHide({ cid }); const stateString = useStateString(post) || t('loading_post'); // Filter out deleted replies with no children for both virtuoso and non-virtuoso rendering const filteredReplies = useMemo(() => (replies || []).filter((reply) => !(reply.deleted && (reply.replyCount === 0 || !reply.replyCount))), [replies]); // Virtuoso scroll position management for infinite replies const virtuosoRef = useRef(null); const virtuosoStateKey = `replies-mobile-${cid}`; useEffect(() => { if (!showAllReplies || !isInPostPageView) return; const currentKey = virtuosoStateKey; const setLastVirtuosoState = () => { virtuosoRef.current?.getState((snapshot: StateSnapshot) => { if (snapshot?.ranges?.length) { lastVirtuosoStates[currentKey] = snapshot; } }); }; window.addEventListener('scroll', setLastVirtuosoState); return () => window.removeEventListener('scroll', setLastVirtuosoState); }, [virtuosoStateKey, showAllReplies, isInPostPageView]); const lastVirtuosoState = navigationType === 'POP' ? lastVirtuosoStates?.[virtuosoStateKey] : undefined; const shouldScrollToReply = showAllReplies && showReplies && !isInPendingPostView && !!targetReplyCid; useScrollToReply({ targetReplyCid, replies: filteredReplies, hasMore, loadMore, virtuosoRef, enabled: shouldScrollToReply, }); // Footer component for Virtuoso showing loading state const RepliesFooter = () => hasMore ? (
) : null; return ( <> {hidden && !isInPostPageView ? ( <>
Show Hidden Thread ) : (
{(showReplies || isModQueue) && (

)}
{shouldShowSnow() && }
{!isInPostView && !isInPendingPostView && (showReplies || isModQueue) && (
{replyCount > 0 && `${replyCount} Replies`} {linksCount > 0 && ` / ${linksCount} Links`} {isModQueue ? (
{modQueueStatus === 'approved' ? ( {t('approved')} ) : modQueueStatus === 'rejected' ? ( {t('rejected')} ) : modQueueStatus === 'failed' ? ( {t('failed')} {modQueueError ? `: ${modQueueError}` : ''} ) : isPublishing ? ( ) : ( <> )}
) : ( {t('view_thread')} )}
)}
{/* Virtuoso infinite scroll for post page view when there's more content to paginate */} {!(pinned && !isInPostView) && showAllReplies && !isInPendingPostView && showReplies && hasMore && ( (
)} useWindowScroll={true} components={{ Footer: RepliesFooter }} endReached={loadMore} ref={virtuosoRef} restoreStateFrom={lastVirtuosoState} initialScrollTop={lastVirtuosoState?.scrollTop} /> )} {/* Non-virtualized rendering for post page view when all replies fit on one page */} {!(pinned && !isInPostView) && showAllReplies && !isInPendingPostView && showReplies && !hasMore && filteredReplies.map((reply, index) => (
))} {/* Non-virtualized rendering for board view (last 5 replies) */} {!(pinned && !isInPostView) && !showAllReplies && !isInPendingPostView && replies && showReplies && filteredReplies.slice(-5).map((reply, index) => (
))}
{!isInPendingPostView && stateString && stateString !== 'Failed' && state !== 'succeeded' && isInPostPageView && !(!showReplies && !showAllReplies) ? (
) : ( state === 'failed' && {t('failed')} )}
)} ); }; export default PostMobile;