import { useEffect, useRef, useState } from 'react'; import { Trans, useTranslation } from 'react-i18next'; import { Link, useLocation, useParams } from 'react-router-dom'; import { Comment, useAccount, useAuthorAvatar, useComment, useEditedComment } from '@plebbit/plebbit-react-hooks'; import Plebbit from '@plebbit/plebbit-js/dist/browser/index.js'; import styles from '../../views/post/post.module.css'; import { getCommentMediaInfo, getDisplayMediaInfoType, getHasThumbnail } from '../../lib/utils/media-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 useAuthorAddressClick from '../../hooks/use-author-address-click'; import useEditCommentPrivileges from '../../hooks/use-author-privileges'; import useCountLinksInReplies from '../../hooks/use-count-links-in-replies'; import useHide from '../../hooks/use-hide'; import useReplies from '../../hooks/use-replies'; import useStateString from '../../hooks/use-state-string'; import CommentMedia from '../comment-media'; import EditMenu from '../edit-menu/edit-menu'; import { canEmbed } from '../embed'; import LoadingEllipsis from '../loading-ellipsis'; import Markdown from '../markdown'; 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'; 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 = ({ openReplyModal, post, postReplyCount = 0, roles, isHidden }: PostProps) => { const { t } = useTranslation(); const { author, cid, locked, pinned, parentCid, postCid, replyCount, shortCid, state, subplebbitAddress, timestamp } = post || {}; const title = post?.title?.trim(); const replies = useReplies(post); const { address, shortAddress } = author || {}; const displayName = author?.displayName?.trim(); const authorRole = roles?.[address]?.role; const { isDescription, isRules } = post || {}; // custom properties, not from api const stateString = useStateString(post); const isReply = parentCid; const { showOmittedReplies } = useShowOmittedReplies(); const { imageUrl: avatarImageUrl } = useAuthorAvatar({ author }); const params = useParams(); const location = useLocation(); const isInAllView = isAllView(location.pathname, params); const isInPostPageView = isPostPageView(location.pathname, params); const isInSubscriptionsView = isSubscriptionsView(location.pathname, params); const account = useAccount(); const accountShortAddress = account?.author?.shortAddress; // if reply by account is pending, it doesn't have an author yet const { isCommentAuthorMod, isAccountMod, isAccountCommentAuthor } = useEditCommentPrivileges({ commentAuthorAddress: address, subplebbitAddress }); const handleUserAddressClick = useAuthorAddressClick(); const numberOfPostsByAuthor = document.querySelectorAll(`[data-author-address="${shortAddress}"][data-post-cid="${postCid}"]`).length; return (
{!isHidden && } {title && (title.length <= 75 ? ( {title} ) : ( {title.slice(0, 75) + '(...)'} } content={title.length < 1000 ? title : title.slice(0, 1000) + `... ${t('title_too_long')}`} /> ))} {displayName ? ( displayName.length <= 20 ? ( displayName ) : ( ) ) : ( _.capitalize(t('anonymous')) )} {authorRole && ` ## Board ${authorRole}`}{' '} {!(isDescription || isRules) && ( <> {isReply && author?.avatar && } (u/ handleUserAddressClick(shortAddress || accountShortAddress, postCid)}> {shortAddress || accountShortAddress} } 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)} /> {isDescription || isRules ? '' : ' '} {subplebbitAddress && (isInAllView || isInSubscriptionsView) && !isReply && ( {' '} p/{subplebbitAddress && Plebbit.getShortAddress(subplebbitAddress)}{' '} )} {!(isDescription || isRules) && ( !cid && e.preventDefault()}> c/ {!cid ? ( {state === 'failed' || stateString === 'Failed' ? 'Failed' : 'Pending'} ) : ( openReplyModal && openReplyModal(cid)}> {shortCid} )} )} {pinned && ( )} {locked && ( )} {!isInPostPageView && !isReply && !isHidden && ( [ {_.capitalize(t('reply'))} ] )} {replyCount > 0 && parentCid && replies && replies.map((reply: Comment, index: number) => reply?.parentCid === cid && )}
); }; const PostMedia = ({ post }: PostProps) => { const { t } = useTranslation(); const { link, spoiler } = post || {}; const commentMediaInfo = getCommentMediaInfo(post); const { type, url } = commentMediaInfo || {}; const embedUrl = url && new URL(url); const hasThumbnail = getHasThumbnail(commentMediaInfo, link); const [showThumbnail, setShowThumbnail] = useState(true); return (
{t('link')}:{' '} {spoiler ? _.capitalize(t('spoiler')) : url && url.length > 30 ? url.slice(0, 30) + '...' : url} {' '} ({type && _.lowerCase(getDisplayMediaInfoType(type, t))}) {!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 PostMessage = ({ post }: PostProps) => { const { cid, content, deleted, edit, original, parentCid, postCid, reason, removed, state, subplebbitAddress } = post || {}; // TODO: commentAuthor is not available outside of editedComment, update when available // const banned = !!post?.commentAuthor?.banExpiresAt; const { t } = useTranslation(); const params = useParams(); const location = useLocation(); const isInPostView = isPostPageView(location.pathname, params); const [showOriginal, setShowOriginal] = useState(false); const displayContent = content && !isInPostView && content.length > 1000 ? content?.slice(0, 1000) + '(...)' : content; const isReply = parentCid; const isReplyingToReply = postCid !== parentCid; const stateString = useStateString(post); const loadingString = stateString && (
{stateString !== 'Failed' ? : stateString}
); const quotelinkReply = useComment({ commentCid: parentCid }); return (
{isReply && !(removed || deleted) && state !== 'failed' && isReplyingToReply && } {removed ? ( ({t('this_post_was_removed')})} content={`${_.capitalize(t('reason'))}: "${reason}"`} showTooltip={!!reason} /> ) : deleted ? ( {t('user_deleted_this_post')}} content={reason && `${t('reason')}: ${reason}`} /> ) : ( <> {!showOriginal && } {edit && original?.content !== post?.content && ( {showOriginal && }
} /> }} />{' '} {reason && <>{t('reason_reason', { reason: reason, interpolation: { escapeValue: false } })} } {showOriginal ? ( setShowOriginal(!showOriginal)} /> }} /> ) : ( setShowOriginal(!showOriginal)} /> }} /> )}
)} )} {/* TODO: commentAuthor is not available outside of editedComment, update when available */} {/* {banned && (

)} */} {!isReply && content.length > 1000 && !isInPostView && (
}} />
)} {!cid && state === 'pending' && stateString !== 'Failed' && ( <>
{loadingString} )}
); }; const Reply = ({ openReplyModal, postReplyCount, reply, roles }: PostProps) => { let post = reply; // handle pending mod or author edit const { editedComment } = useEditedComment({ comment: reply }); if (editedComment) { post = editedComment; } const { author, cid, content, link, postCid, subplebbitAddress } = post || {}; const isRouteLinkToReply = useLocation().pathname.startsWith(`/p/${subplebbitAddress}/c/${cid}`); const { hidden } = useHide({ cid }); return (
{'>>'}
{link && !hidden && isValidURL(link) && } {content && !hidden && }
); }; const PostDesktop = ({ openReplyModal, post, roles, showAllReplies, showReplies = true }: PostProps) => { const { t } = useTranslation(); const { author, cid, content, link, pinned, postCid, replyCount, subplebbitAddress } = post || {}; const { isDescription, isRules } = post || {}; // custom properties, not from api const params = useParams(); const location = useLocation(); const isInPendingPostView = isPendingPostView(location.pathname, params); const isInPostPageView = isPostPageView(location.pathname, params); const { hidden, unhide, hide } = useHide({ cid }); const isHidden = hidden && !isInPostPageView; const replies = useReplies(post); const visiblelinksCount = useCountLinksInReplies(post, 5); const totalLinksCount = useCountLinksInReplies(post); const repliesCount = pinned ? replyCount : replyCount - 5; const linksCount = pinned ? totalLinksCount : totalLinksCount - visiblelinksCount; const { showOmittedReplies, setShowOmittedReplies } = useShowOmittedReplies(); // scroll to reply if pathname is reply permalink (backlink) const replyRefs = useRef<(HTMLDivElement | null)[]>([]); useEffect(() => { const replyIndex = replies.findIndex((reply) => location.pathname === `/p/${subplebbitAddress}/c/${reply?.cid}`); if (replyIndex !== -1 && replyRefs.current[replyIndex]) { replyRefs.current[replyIndex]?.scrollIntoView(); } }, [location.pathname, replies, subplebbitAddress]); return (
{showReplies ? (

) : (
)}
{!isInPostPageView && !isDescription && !isRules && showReplies && ( )}
{link && !isHidden && isValidURL(link) && } {!isHidden && !content &&
} {!isHidden && content && }
{!isHidden && !isDescription && !isRules && !isInPendingPostView && (repliesCount > 5 || (pinned && repliesCount > 0)) && !isInPostPageView && ( setShowOmittedReplies(cid, !showOmittedReplies[cid])} /> {showOmittedReplies[cid] ? ( t('showing_all_replies') ) : linksCount > 0 ? ( }} values={{ repliesCount, linksCount }} /> ) : ( }} values={{ repliesCount }} /> )} )} {replyCount === undefined && ( )} {!isHidden && !(pinned && !isInPostPageView && !showOmittedReplies[cid]) && !isInPendingPostView && !isDescription && !isRules && replies && showReplies && (showAllReplies || showOmittedReplies[cid] ? replies : replies.slice(-5)).map((reply, index) => (
(replyRefs.current[index] = el)}>
))}
); }; export default PostDesktop;