import { useEffect, useMemo, useRef, useState } from 'react'; import { Trans, 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 { CommentMediaInfo, getDisplayMediaInfoType, getHasThumbnail, getMediaDimensions } from '../../lib/utils/media-utils'; import { hashStringToColor, getTextColorForBackground } from '../../lib/utils/post-utils'; import { getFormattedDate, getFormattedTimeAgo } from '../../lib/utils/time-utils'; import { isValidURL } from '../../lib/utils/url-utils'; import { isAllView, isPendingPostView, isPostPageView, isSubscriptionsView } from '../../lib/utils/view-utils'; 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 useFetchGifFirstFrame from '../../hooks/use-fetch-gif-first-frame'; import useHide from '../../hooks/use-hide'; import useStateString from '../../hooks/use-state-string'; import CommentContent from '../comment-content'; import CommentMedia from '../comment-media'; import EditMenu from '../edit-menu/edit-menu'; import { canEmbed } from '../embed'; import LoadingEllipsis from '../loading-ellipsis'; import PostMenuDesktop from './post-menu-desktop'; import ReplyQuotePreview from '../reply-quote-preview'; import Tooltip from '../tooltip'; import { PostProps } from '../../views/post/post'; import { create } from 'zustand'; import _ from 'lodash'; import { shouldShowSnow } from '../../lib/snow'; 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 } = {}; interface ShowOmittedRepliesState { showOmittedReplies: Record; setShowOmittedReplies: (cid: string, showOmittedReplies: boolean) => void; } const useShowOmittedReplies = create((set) => ({ showOmittedReplies: {}, setShowOmittedReplies: (cid, showOmittedReplies) => set((state) => ({ showOmittedReplies: { ...state.showOmittedReplies, [cid]: showOmittedReplies, }, })), })); const PostInfo = ({ post, postReplyCount = 0, roles, isHidden, threadNumber }: PostProps) => { const { t } = useTranslation(); const { author, cid, deleted, locked, pinned, parentCid, postCid, reason, removed, state, subplebbitAddress, timestamp } = post || {}; const title = post?.title?.trim(); const { replies } = useReplies({ comment: post }); const { address, shortAddress } = author || {}; const displayName = author?.displayName?.trim(); const authorRole = roles?.[address]?.role?.replace('moderator', 'mod'); const stateString = useStateString(post); const isReply = parentCid; const { showOmittedReplies } = useShowOmittedReplies(); const { imageUrl: avatarImageUrl } = useAuthorAvatar({ author }); const { hideAvatars } = useAvatarVisibilityStore(); const defaultSubplebbits = useDefaultSubplebbits(); const boardPath = subplebbitAddress ? getBoardPath(subplebbitAddress, defaultSubplebbits) : undefined; const postMenuProps = useMemo(() => selectPostMenuProps(post), [post]); const params = useParams(); const location = useLocation(); const isInPostPageView = isPostPageView(location.pathname, params); 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 handleUserAddressClick = useAuthorAddressClick(); const numberOfPostsByAuthor = document.querySelectorAll(`[data-author-address="${shortAddress}"][data-post-cid="${postCid}"]`).length; 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 (
{isHidden ? parentCid && : } {title && (title.length <= 75 ? ( {title} ) : ( {title.slice(0, 75) + '(...)'} } content={title.length < 1000 ? title : title.slice(0, 1000) + `... ${t('title_too_long')}`} /> ))} {deleted ? ( _.capitalize(t('deleted')) ) : removed ? ( _.capitalize(t('removed')) ) : displayName ? ( displayName.length <= 20 ? ( displayName ) : ( ) ) : ( _.capitalize(t('anonymous')) )} {!(deleted || removed) && authorRole && ( {' '} ## Board {authorRole}{' '} )}{' '} {author?.avatar && !(deleted || removed) && !hideAvatars && avatarImageUrl ? ( ) : null} (ID:{' '} {deleted ? ( t('deleted') ) : removed ? ( t('removed') ) : ( 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 || showOmittedReplies[postCid] || (postReplyCount < 6 && !pinned)} /> )} ){' '} {getFormattedDate(timestamp)}} content={getFormattedTimeAgo(timestamp)} />{' '} {cid ? ( !cid && e.preventDefault()} > No. {post?.number || '?'} ) : ( <> CID: {state === 'failed' || stateString === 'Failed' ? _.capitalize(t('failed')) : state === 'pending' ? _.capitalize(t('pending')) : ''} )} {pinned && ( )} {locked && ( )} {!isInPostPageView && !isReply && !isHidden && ( [ !cid && e.preventDefault()}> {_.capitalize(t('reply'))} ] )} {!(removed || deleted) && } {cid && parentCid && replies && replies.map( (reply: Comment, index: number) => reply?.parentCid === cid && reply?.cid && !(reply?.deleted || reply?.removed) && , )}
); }; interface PostMediaProps { commentMediaInfo: CommentMediaInfo | undefined; hasThumbnail: boolean; spoiler: boolean; deleted: boolean; removed: boolean; linkHeight: number; linkWidth: number; parentCid: string; subplebbitAddress: string; isInAllView: boolean; isInSubscriptionsView: boolean; } const PostMedia = ({ commentMediaInfo, hasThumbnail, spoiler, deleted, removed, linkHeight, linkWidth, parentCid, subplebbitAddress, isInAllView, isInSubscriptionsView, }: PostMediaProps) => { const { t } = useTranslation(); const { url } = commentMediaInfo || {}; let type = commentMediaInfo?.type; const gifFrameUrl = useFetchGifFirstFrame(url); const defaultSubplebbits = useDefaultSubplebbits(); if (type === 'gif' && gifFrameUrl !== null) { type = 'animated gif'; } else if (type === 'gif' && gifFrameUrl === null) { type = 'static gif'; } const embedUrl = url && new URL(url); const [showThumbnail, setShowThumbnail] = useState(true); const mediaDimensions = getMediaDimensions(commentMediaInfo); const boardPath = getBoardPath(subplebbitAddress, defaultSubplebbits); return (
{subplebbitAddress && (isInAllView || isInSubscriptionsView) && boardPath && !parentCid && ( <> {t('board')}: {boardPath}{' '} )} {t('link')}:{' '} {spoiler ? _.capitalize(t('spoiler')) : url && url.length > 30 ? url.slice(0, 30) + '...' : url} {' '} ({type && _.lowerCase(getDisplayMediaInfoType(type, t))} {mediaDimensions && `, ${mediaDimensions}`}) {!showThumbnail && (type === 'iframe' || type === 'video' || type === 'audio') && ( -[ setShowThumbnail(true)}> {t('close')} ] )} {showThumbnail && !hasThumbnail && embedUrl && canEmbed(embedUrl) && ( -[ setShowThumbnail(false)}> {t('open')} ] )}
{(hasThumbnail || (!hasThumbnail && !showThumbnail) || spoiler) && (
)}
); }; 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, link, linkHeight, linkWidth, postCid, reason, removed, spoiler, subplebbitAddress, thumbnailUrl, parentCid } = 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 }); const isInAllView = isAllView(location.pathname); const params = useParams(); const isInSubscriptionsView = isSubscriptionsView(location.pathname, params); const commentMediaInfo = useCommentMediaInfo(link, thumbnailUrl, linkWidth, linkHeight); const hasThumbnail = getHasThumbnail(commentMediaInfo, link); return (
{'>>'}
{link && !hidden && !(deleted || removed) && isValidURL(link) && ( )} {!hidden && (!(removed || deleted) || ((removed || deleted) && reason)) && }
); }; const PostDesktop = ({ post, roles, showAllReplies, showReplies = true }: PostProps) => { const { t } = useTranslation(); const { author, cid, content, deleted, link, linkHeight, linkWidth, pinned, postCid, removed, spoiler, state, subplebbitAddress, thumbnailUrl, parentCid } = post || {}; const params = useParams(); const location = useLocation(); const navigationType = useNavigationType(); const isInPendingPostView = isPendingPostView(location.pathname, params); const isInPostPageView = isPostPageView(location.pathname, params); const isInAllView = isAllView(location.pathname); const isInSubscriptionsView = isSubscriptionsView(location.pathname, params); const defaultSubplebbits = useDefaultSubplebbits(); const boardPath = subplebbitAddress ? getBoardPath(subplebbitAddress, defaultSubplebbits) : undefined; const { hidden, unhide, hide } = useHide({ cid }); const isHidden = hidden && !isInPostPageView; const { replies, hasMore, loadMore } = useReplies({ comment: post, flat: true }); const visiblelinksCount = useCountLinksInReplies(post, 5); const totalLinksCount = useCountLinksInReplies(post); const replyCount = replies?.length; const repliesCount = pinned ? replyCount : replyCount - 5; const linksCount = pinned ? totalLinksCount : totalLinksCount - visiblelinksCount; const { showOmittedReplies, setShowOmittedReplies } = useShowOmittedReplies(); const stateString = useStateString(post) || t('downloading_board'); const commentMediaInfo = useCommentMediaInfo(link, thumbnailUrl, linkWidth, linkHeight); const hasThumbnail = getHasThumbnail(commentMediaInfo, link); // 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-desktop-${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; // Footer component for Virtuoso showing loading state const RepliesFooter = () => hasMore ? (
) : null; return (
{showReplies ? (

) : (
)}
{!isInPostPageView && showReplies && ( )}
{shouldShowSnow() && hasThumbnail && } {link && !isHidden && !(deleted || removed) && isValidURL(link) && ( )} {!isHidden && !content && !(deleted || removed) &&
} {!isHidden && }
{!isHidden && !isInPendingPostView && (replyCount > 5 || (pinned && repliesCount > 0)) && !isInPostPageView && ( setShowOmittedReplies(cid, !showOmittedReplies[cid])} /> {showOmittedReplies[cid] ? ( t('showing_all_replies') ) : linksCount > 0 ? ( }} values={{ repliesCount, linksCount }} /> ) : ( }} values={{ repliesCount }} /> )} )} {/* Virtuoso infinite scroll for post page view with more than 25 replies */} {!isHidden && showAllReplies && !isInPendingPostView && showReplies && replyCount > 25 && ( (
)} useWindowScroll={true} components={{ Footer: RepliesFooter }} endReached={loadMore} ref={virtuosoRef} restoreStateFrom={lastVirtuosoState} initialScrollTop={lastVirtuosoState?.scrollTop} /> )} {/* Non-virtualized rendering for post page view with 25 or fewer replies */} {!isHidden && showAllReplies && !isInPendingPostView && showReplies && replyCount <= 25 && filteredReplies.map((reply, index) => (
))} {/* Non-virtualized rendering for board view (last 5 replies or show omitted) */} {!isHidden && !showAllReplies && !(pinned && !isInPostPageView && !showOmittedReplies[cid]) && !isInPendingPostView && replies && showReplies && (showOmittedReplies[cid] ? filteredReplies : filteredReplies.slice(-5)).map((reply, index) => (
))}
{!isInPendingPostView && stateString && stateString !== 'Failed' && state !== 'succeeded' && isInPostPageView && !(!showReplies && !showAllReplies) ? (

) : ( state === 'failed' && {t('failed')} )}
); }; export default PostDesktop;