refactor: rename PostPage to Post, export Post component from Post view

This commit is contained in:
Tom (plebeius.eth)
2024-06-11 15:49:26 +02:00
parent 7100030043
commit 8e5a5919fa
30 changed files with 89 additions and 94 deletions
+1
View File
@@ -0,0 +1 @@
export { default } from './post-desktop';
@@ -0,0 +1,304 @@
import { useEffect, useRef, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Link, useLocation, useParams } from 'react-router-dom';
import { Comment, useAccount, useBlock, useComment } 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 { isValidURL } from '../../lib/utils/url-utils';
import { isAllView, isPendingPostView, isPostPageView, isSubscriptionsView } from '../../lib/utils/view-utils';
import useCountLinksInReplies from '../../hooks/use-count-links-in-replies';
import useEditCommentPrivileges from '../../hooks/use-author-privileges';
import useReplies from '../../hooks/use-replies';
import useStateString from '../../hooks/use-state-string';
import CommentMedia from '../comment-media';
import { canEmbed } from '../embed';
import LoadingEllipsis from '../loading-ellipsis';
import Markdown from '../markdown';
import PostMenuDesktop from './post-menu-desktop';
import EditMenu from '../edit-menu/edit-menu';
import ReplyQuotePreview from '../reply-quote-preview';
import { PostProps } from '../../views/post/post';
import Timestamp from '../timestamp';
import _ from 'lodash';
const PostInfo = ({ openReplyModal, post, roles, isHidden }: PostProps) => {
const { t } = useTranslation();
const { author, cid, locked, pinned, parentCid, postCid, replyCount, shortCid, state, subplebbitAddress, timestamp, title } = post || {};
const replies = useReplies(post);
const { address, displayName, shortAddress } = author || {};
const { isDescription, isRules } = post || {}; // custom properties, not from api
const stateString = useStateString(post);
const isReply = parentCid;
const params = useParams();
const location = useLocation();
const isInAllView = isAllView(location.pathname);
const isInPostView = isPostPageView(location.pathname, params);
const isInSubscriptionsView = isSubscriptionsView(location.pathname);
const shortDisplayName = displayName?.trim().length > 20 ? displayName?.trim().slice(0, 20).trim() + '...' : displayName?.trim();
const authorRole = roles?.[address]?.role;
const displayTitle = title && title.length > 75 ? title?.slice(0, 75) + '...' : title;
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 });
return (
<div className={styles.postInfo}>
{!isHidden && <EditMenu commentCid={cid} isAccountCommentAuthor={isAccountCommentAuthor} isAccountMod={isAccountMod} isCommentAuthorMod={isCommentAuthorMod} />}
{title && <span className={styles.subject}>{displayTitle} </span>}
<span className={styles.nameBlock}>
<span className={`${styles.name} ${(isDescription || isRules || authorRole) && styles.capcodeMod}`}>
{shortDisplayName || _.capitalize(t('anonymous'))}
{authorRole && ` ## Board ${authorRole}`}{' '}
</span>
{!(isDescription || isRules) && <span className={styles.userAddress}>(u/{shortAddress || accountShortAddress}) </span>}
</span>
<span className={styles.dateTime}>
<Timestamp timestamp={timestamp} />
{isDescription || isRules ? '' : ' '}
</span>
<span className={styles.postNum}>
{subplebbitAddress && (isInAllView || isInSubscriptionsView) && !isReply && (
<span className={styles.postNumLink}>
{' '}
<Link to={`/p/${subplebbitAddress}`}>p/{subplebbitAddress && Plebbit.getShortAddress(subplebbitAddress)}</Link>{' '}
</span>
)}
{!(isDescription || isRules) && (
<span className={styles.postNumLink}>
<Link to={`/p/${subplebbitAddress}/c/${cid}`} className={styles.linkToPost} title={t('link_to_post')} onClick={(e) => !cid && e.preventDefault()}>
c/
</Link>
{!cid ? (
<span className={styles.pendingCid}>{state === 'failed' || stateString === 'Failed' ? 'Failed' : 'Pending'}</span>
) : (
<span className={styles.replyToPost} title={t('reply_to_post')} onClick={() => openReplyModal && openReplyModal(cid)}>
{shortCid}
</span>
)}
</span>
)}
{pinned && (
<span className={`${styles.stickyIconWrapper} ${!locked && styles.addPaddingBeforeReply}`}>
<img src='/assets/icons/sticky.gif' alt='' className={styles.stickyIcon} title={t('sticky')} />
</span>
)}
{locked && (
<span className={`${styles.closedIconWrapper} ${styles.addPaddingBeforeReply} ${pinned && styles.addPaddingInBetween}`}>
<img src='/assets/icons/closed.gif' alt='' className={styles.closedIcon} title={t('closed')} />
</span>
)}
{!isInPostView && !isReply && !isHidden && (
<span className={styles.replyButton}>
[
<Link
to={isInAllView && isDescription ? '/p/all/description' : `/p/${subplebbitAddress}/${isDescription ? 'description' : isRules ? 'rules' : `c/${postCid}`}`}
>
{_.capitalize(t('reply'))}
</Link>
]
</span>
)}
</span>
<PostMenuDesktop post={post} />
{replyCount > 0 &&
parentCid &&
replies &&
replies.map((reply: Comment, index: number) => reply?.parentCid === cid && <ReplyQuotePreview key={index} isBacklinkReply={true} backlinkReply={reply} />)}
</div>
);
};
const PostMedia = ({ post }: PostProps) => {
const { t } = useTranslation();
const commentMediaInfo = getCommentMediaInfo(post);
const { type, url } = commentMediaInfo || {};
const embedUrl = url && new URL(url);
const hasThumbnail = getHasThumbnail(commentMediaInfo, post?.link);
const [showThumbnail, setShowThumbnail] = useState(true);
return (
<div className={styles.file}>
<div className={styles.fileText}>
{t('link')}:{' '}
<a href={url} target='_blank' rel='noopener noreferrer'>
{url && url.length > 30 ? url.slice(0, 30) + '...' : url}
</a>{' '}
({type && _.lowerCase(getDisplayMediaInfoType(type, t))})
{!showThumbnail && (type === 'iframe' || type === 'video' || type === 'audio') && (
<span>
{' '}
[
<span className={styles.closeMedia} onClick={() => setShowThumbnail(true)}>
{t('close')}
</span>
]
</span>
)}
{showThumbnail && !hasThumbnail && embedUrl && canEmbed(embedUrl) && (
<span>
{' '}
[
<span className={styles.closeMedia} onClick={() => setShowThumbnail(false)}>
{t('open')}
</span>
]
</span>
)}
</div>
{(hasThumbnail || (!hasThumbnail && !showThumbnail)) && (
<div className={styles.fileThumbnail}>
<CommentMedia commentMediaInfo={commentMediaInfo} post={post} showThumbnail={showThumbnail} setShowThumbnail={setShowThumbnail} />
</div>
)}
</div>
);
};
const PostMessage = ({ post }: PostProps) => {
const { cid, content, deleted, parentCid, postCid, reason, removed, spoiler, state, subplebbitAddress } = post || {};
const { t } = useTranslation();
const params = useParams();
const location = useLocation();
const isInPostView = isPostPageView(location.pathname, params);
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 && (
<div className={`${styles.stateString} ${styles.ellipsis}`}>{stateString !== 'Failed' ? <LoadingEllipsis string={stateString} /> : stateString}</div>
);
const quotelinkReply = useComment({ commentCid: parentCid });
return (
<blockquote className={styles.postMessage}>
{isReply && isReplyingToReply && <ReplyQuotePreview isQuotelinkReply={true} quotelinkReply={quotelinkReply} />}
{removed ? (
<span className={styles.removedContent}>({t('this_post_was_removed')})</span>
) : deleted ? (
<span className={styles.deletedContent}>{t('user_deleted_this_post')}</span>
) : (
<Markdown content={displayContent} spoiler={spoiler} />
)}
{(removed || deleted) && reason && (
<span>
<br />
<br />
{t('reason')}: {reason}
</span>
)}
{!isReply && content.length > 1000 && !isInPostView && (
<span className={styles.abbr}>
<br />
<Trans i18nKey={'comment_too_long'} shouldUnescape={true} components={{ 1: <Link to={`/p/${subplebbitAddress}/c/${cid}`} /> }} />
</span>
)}
{!cid && state === 'pending' && stateString !== 'Failed' && (
<>
<br />
{loadingString}
</>
)}
</blockquote>
);
};
const PostDesktop = ({ openReplyModal, post, roles, showAllReplies, showReplies = true }: PostProps) => {
const { cid, content, link, pinned, 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 { blocked, unblock, block } = useBlock({ cid });
const isHidden = blocked && !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;
// 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 (
<div className={styles.postDesktop}>
{showReplies ? (
<div className={styles.hrWrapper}>
<hr />
</div>
) : (
<div className={styles.replyQuotePreviewSpacer} />
)}
<div className={isHidden ? styles.postDesktopBlocked : ''}>
{!isInPostPageView && !isDescription && !isRules && showReplies && (
<span className={styles.hideButtonWrapper}>
<span className={`${styles.hideButton} ${blocked ? styles.unhideThread : styles.hideThread}`} onClick={blocked ? unblock : block} />
</span>
)}
{link && !isHidden && isValidURL(link) && <PostMedia post={post} />}
<PostInfo isHidden={isHidden} openReplyModal={openReplyModal} post={post} roles={roles} />
{!isHidden && !content && <div className={styles.spacer} />}
{!isHidden && content && <PostMessage post={post} />}
{!isHidden && !isDescription && !isRules && !isInPendingPostView && (replies.length > 5 || (pinned && replies.length > 0)) && !isInPostPageView && (
<span className={styles.summary}>
<span className={styles.expandButtonWrapper}>
<span className={styles.expandButton} />
</span>
{linksCount > 0 ? (
<Trans
i18nKey={'replies_and_links_omitted'}
shouldUnescape={true}
components={{ 1: <Link to={`/p/${subplebbitAddress}/c/${cid}`} /> }}
values={{ repliesCount, linksCount }}
/>
) : (
<Trans i18nKey={'replies_omitted'} shouldUnescape={true} components={{ 1: <Link to={`/p/${subplebbitAddress}/c/${cid}`} /> }} values={{ repliesCount }} />
)}
</span>
)}
{!isHidden &&
!(pinned && !isInPostPageView) &&
!isInPendingPostView &&
!isDescription &&
!isRules &&
replies &&
showReplies &&
(showAllReplies ? replies : replies.slice(-5)).map((reply, index) => {
const isRouteLinkToReply = location.pathname.startsWith(`/p/${subplebbitAddress}/c/${reply?.cid}`);
return (
<div key={index} className={styles.replyContainer} ref={(el) => (replyRefs.current[index] = el)}>
<div className={styles.replyDesktop}>
<div className={styles.sideArrows}>{'>>'}</div>
<div className={`${styles.reply} ${isRouteLinkToReply && styles.highlight}`} id={reply?.cid}>
<PostInfo openReplyModal={openReplyModal} post={reply} roles={roles} />
{reply.link && isValidURL(reply.link) && <PostMedia post={reply} />}
{reply.content && <PostMessage post={reply} />}
</div>
</div>
</div>
);
})}
</div>
</div>
);
};
export default PostDesktop;
@@ -0,0 +1 @@
export { default } from './post-menu-desktop';
@@ -0,0 +1,116 @@
.postMenu {
position: absolute;
background-color: var(--post-menu-desktop-background-color);
border-bottom: var(--post-menu-desktop-border-bottom);
border-right: var(--post-menu-desktop-border-right);
outline: none;
z-index: 2;
}
.postMenuBtnWrapper {
position: relative;
display: inline-block;
padding-left: 15px;
}
.postMenuBtn {
color: var(--post-menu-desktop-button-color);
transition: transform 0.1s;
transform: rotate(90deg);
position: absolute;
bottom: -4px;
}
.postMenuBtn:hover {
cursor: pointer;
color: var(--post-menu-desktop-button-color-hover);
}
.postMenuItem {
cursor: pointer;
padding: 2px 4px;
border: 1px solid var(--post-menu-desktop-item-border-color);
background-color: var(--post-menu-desktop-item-background-color);
border-bottom: none;
}
.postMenuItem:hover {
background-color: var(--post-menu-desktop-item-hover-background-color);
}
.dropdown {
position: relative;
}
.dropdownMenu {
position: absolute;
left: 100%;
top: -1px;
display: none;
border-bottom: var(--post-menu-desktop-border-bottom);
border-right: var(--post-menu-desktop-border-right);
}
.dropdown a {
text-decoration: none;
color: inherit;
}
.dropdown:hover .dropdownMenu {
display: block;
}
.postMenuBtnCatalogWrapper {
left: 5px;
top: 5px;
position: relative;
}
.postMenuBtnCatalog {
position: absolute;
bottom: 5px;
line-height: 1em;
color: var(--catalog-post-menu-desktop-btn-color);
opacity: var(--catalog-post-menu-desktop-btn-opacity);
transition: transform 0.1s;
}
.postMenuBtnCatalog:hover {
cursor: pointer;
color: var(--catalog-post-menu-desktop-btn-hover-color);
opacity: var(--catalog-post-menu-desktop-btn-hover-opacity);
}
.postMenuBtnCatalog {
/* preserve unicode triangle for button, some browsers will use an emoji */
font-variant: normal;
font-feature-settings: "tnum";
-webkit-font-feature-settings: "tnum"; /* Chrome, Opera, and Safari */
-moz-font-feature-settings: "tnum"; /* Firefox */
font-variant-numeric: tabular-nums;
}
@media (max-width: 640px) {
.postMenuBtn {
width: 1em;
text-align: center;
font-weight: 700;
font-size: 16px;
}
.postMenuBtnWrapper {
position: relative;
padding-right: 12px;
}
}
@media (min-width: 640px) {
.postMenuBtn {
right: -2px;
opacity: var(--post-menu-desktop-btn-opacity);
}
.stickyIconWrapper {
padding-right: 18px;
}
}
@@ -0,0 +1,182 @@
import { useState } from 'react';
import { createPortal } from 'react-dom';
import { useLocation, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { autoUpdate, flip, FloatingFocusManager, offset, shift, useClick, useDismiss, useFloating, useId, useInteractions, useRole } from '@floating-ui/react';
import { Comment, useBlock } from '@plebbit/plebbit-react-hooks';
import styles from './post-menu-desktop.module.css';
import { getCommentMediaInfo } from '../../../lib/utils/media-utils';
import { copyShareLinkToClipboard, isValidURL } from '../../../lib/utils/url-utils';
import { isAllView, isCatalogView, isPostPageView, isSubscriptionsView } from '../../../lib/utils/view-utils';
import _ from 'lodash';
interface PostMenuDesktopProps {
cid: string;
isDescription?: boolean;
isInAllView?: boolean;
isInSubscriptionsView?: boolean;
isRules?: boolean;
subplebbitAddress: string;
onClose: () => void;
}
const CopyLinkButton = ({ cid, subplebbitAddress, onClose }: PostMenuDesktopProps) => {
const { t } = useTranslation();
return (
<div
onClick={() => {
copyShareLinkToClipboard(subplebbitAddress, cid);
onClose();
}}
>
<div className={styles.postMenuItem}>{t('copy_link')}</div>
</div>
);
};
const ImageSearchButton = ({ url, onClose }: { url: string; onClose: () => void }) => {
const { t } = useTranslation();
const [isImageSearchMenuOpen, setIsImageSearchMenuOpen] = useState(false);
const { refs, floatingStyles } = useFloating({
placement: 'right-start',
middleware: [flip(), shift({ padding: 10 })],
});
return (
<div
className={`${styles.postMenuItem} ${styles.dropdown}`}
onMouseOver={() => setIsImageSearchMenuOpen(true)}
onMouseLeave={() => setIsImageSearchMenuOpen(false)}
ref={refs.setReference}
onClick={onClose}
>
{_.capitalize(t('image_search'))} »
{isImageSearchMenuOpen && (
<div ref={refs.setFloating} style={floatingStyles} className={styles.dropdownMenu}>
<a href={`https://lens.google.com/uploadbyurl?url=${url}`} target='_blank' rel='noreferrer'>
<div className={styles.postMenuItem}>Google</div>
</a>
<a href={`https://www.yandex.com/images/search?img_url=${url}&rpt=imageview`} target='_blank' rel='noreferrer'>
<div className={styles.postMenuItem}>Yandex</div>
</a>
<a href={`https://saucenao.com/search.php?url=${url}`} target='_blank' rel='noreferrer'>
<div className={styles.postMenuItem}>SauceNAO</div>
</a>
</div>
)}
</div>
);
};
const ViewOnButton = ({ cid, isDescription, isInAllView, isInSubscriptionsView, isRules, subplebbitAddress, onClose }: PostMenuDesktopProps) => {
const { t } = useTranslation();
const [isClientRedirectMenuOpen, setIsClientRedirectMenuOpen] = useState(false);
const viewOnOtherClientLink = `p/${isInAllView ? 'all' : isInSubscriptionsView ? 'subscriptions' : subplebbitAddress}${isDescription || isRules ? '' : `/c/${cid}`}`;
const { refs, floatingStyles } = useFloating({
placement: 'right-start',
middleware: [flip(), shift({ padding: 10 })],
});
return (
<div
className={`${styles.postMenuItem} ${styles.dropdown}`}
onMouseOver={() => setIsClientRedirectMenuOpen(true)}
onMouseLeave={() => setIsClientRedirectMenuOpen(false)}
ref={refs.setReference}
onClick={onClose}
>
{_.capitalize(t('view_on'))} »
{isClientRedirectMenuOpen && (
<div ref={refs.setFloating} style={floatingStyles} className={styles.dropdownMenu}>
<a href={`https://seedit.eth.limo/#/${viewOnOtherClientLink}`} target='_blank' rel='noreferrer'>
<div className={styles.postMenuItem}>Seedit</div>
</a>
<a href={`https://plebones.eth.limo/#/${viewOnOtherClientLink}`} target='_blank' rel='noreferrer'>
<div className={styles.postMenuItem}>Plebones</div>
</a>
</div>
)}
</div>
);
};
const PostMenuDesktop = ({ post }: { post: Comment }) => {
const { t } = useTranslation();
const { cid, isDescription, isRules, link, postCid, subplebbitAddress } = post || {};
const commentMediaInfo = getCommentMediaInfo(post);
const { thumbnail, type, url } = commentMediaInfo || {};
const [menuBtnRotated, setMenuBtnRotated] = useState(false);
const { blocked, unblock, block } = useBlock({ cid });
const location = useLocation();
const params = useParams();
const isInAllView = isAllView(location.pathname);
const isInCatalogView = isCatalogView(location.pathname, params);
const isInPostPageView = isPostPageView(location.pathname, params);
const isInSubscriptionsView = isSubscriptionsView(location.pathname);
const { refs, floatingStyles, context } = useFloating({
placement: 'bottom-start',
open: menuBtnRotated,
onOpenChange: setMenuBtnRotated,
middleware: [offset({ mainAxis: isInCatalogView ? -2 : 6, crossAxis: isInCatalogView ? -1 : 5 }), flip({ fallbackAxisSideDirection: 'end' }), shift({ padding: 10 })],
whileElementsMounted: autoUpdate,
});
const click = useClick(context);
const dismiss = useDismiss(context);
const role = useRole(context);
const { getReferenceProps, getFloatingProps } = useInteractions([click, dismiss, role]);
const headingId = useId();
const handleClose = () => setMenuBtnRotated(false);
return (
<>
<span className={isInCatalogView ? styles.postMenuBtnCatalogWrapper : styles.postMenuBtnWrapper} ref={refs.setReference} {...getReferenceProps()}>
<span
className={isInCatalogView ? styles.postMenuBtnCatalog : styles.postMenuBtn}
title='Post menu'
onClick={() => setMenuBtnRotated((prev) => !prev)}
style={{ transform: menuBtnRotated ? 'rotate(90deg)' : 'rotate(0deg)' }}
>
</span>
</span>
{menuBtnRotated &&
createPortal(
<FloatingFocusManager context={context} modal={false}>
<div className={styles.postMenu} ref={refs.setFloating} style={floatingStyles} aria-labelledby={headingId} {...getFloatingProps()}>
{cid && subplebbitAddress && <CopyLinkButton cid={cid} subplebbitAddress={subplebbitAddress} onClose={handleClose} />}
{!isInPostPageView && !isDescription && !isRules && (
<div
className={styles.postMenuItem}
onClick={() => {
blocked ? unblock() : block();
handleClose();
}}
>
{blocked ? (postCid === cid ? t('unhide_thread') : t('unhide_post')) : postCid === cid ? t('hide_thread') : t('hide_post')}
</div>
)}
{link && isValidURL(link) && (type === 'image' || type === 'gif' || thumbnail) && url && <ImageSearchButton url={url} onClose={handleClose} />}
<ViewOnButton
cid={cid}
isDescription={isDescription}
isInAllView={isInAllView}
isInSubscriptionsView={isInSubscriptionsView}
isRules={isRules}
subplebbitAddress={subplebbitAddress}
onClose={handleClose}
/>
</div>
</FloatingFocusManager>,
document.body,
)}
</>
);
};
export default PostMenuDesktop;