Files
5chan/src/components/catalog-row/catalog-row.tsx
T

250 lines
9.4 KiB
TypeScript
Raw Normal View History

2024-06-08 11:27:29 +02:00
import { useEffect, useRef } from 'react';
2024-04-12 20:48:46 +02:00
import { useTranslation } from 'react-i18next';
2024-06-08 11:27:29 +02:00
import { Link, useLocation } from 'react-router-dom';
import { Comment, useComment } from '@plebbit/plebbit-react-hooks';
import { useFloating, offset, shift, size, autoUpdate, Placement } from '@floating-ui/react';
2024-04-12 17:47:30 +02:00
import { getCommentMediaInfo, getHasThumbnail } from '../../lib/utils/media-utils';
2024-06-08 11:27:29 +02:00
import { getFormattedTimeAgo } from '../../lib/utils/time-utils';
2024-05-17 17:25:25 +02:00
import { isAllView } from '../../lib/utils/view-utils';
2024-04-12 17:47:30 +02:00
import useFetchGifFirstFrame from '../../hooks/use-fetch-gif-first-frame';
import useCountLinksInReplies from '../../hooks/use-count-links-in-replies';
2024-06-08 11:27:29 +02:00
import useEditCommentPrivileges from '../../hooks/use-author-privileges';
2024-05-28 19:03:43 +02:00
import PostMenuDesktop from '../post/post-desktop/post-menu-desktop/';
2024-06-08 11:27:29 +02:00
import styles from './catalog-row.module.css';
import _ from 'lodash';
2024-04-12 17:47:30 +02:00
import React, { useState } from 'react';
2024-06-08 11:27:29 +02:00
import { createPortal } from 'react-dom';
interface CatalogPostMediaProps {
commentMediaInfo: any;
isOutOfFeed?: boolean;
linkWidth?: number;
linkHeight?: number;
}
export const CatalogPostMedia = ({ commentMediaInfo, isOutOfFeed, linkWidth, linkHeight }: CatalogPostMediaProps) => {
2024-04-12 17:47:30 +02:00
const { patternThumbnailUrl, thumbnail, type, url } = commentMediaInfo || {};
const iframeThumbnail = patternThumbnailUrl || thumbnail;
const gifFrameUrl = useFetchGifFirstFrame(type === 'gif' ? url : undefined);
const [isLoaded, setIsLoaded] = useState(false);
const [hasError, setHasError] = useState(false);
const handleLoad = () => setIsLoaded(true);
const handleError = () => setHasError(true);
const loadingStyle = { display: isLoaded ? 'block' : 'none' };
2024-04-12 14:28:06 +02:00
2024-04-12 17:47:30 +02:00
let displayWidth, displayHeight;
const maxThumbnailSize = 150;
if (linkWidth && linkHeight) {
let scale = Math.min(1, maxThumbnailSize / Math.max(linkWidth, linkHeight));
displayWidth = `${linkWidth * scale}px`;
displayHeight = `${linkHeight * scale}px`;
} else {
displayWidth = `${maxThumbnailSize}px`;
displayHeight = `${maxThumbnailSize}px`;
}
if (type === 'audio' || isOutOfFeed) {
2024-04-12 20:48:46 +02:00
displayWidth = 'unset';
displayHeight = 'unset';
}
2024-04-12 17:47:30 +02:00
const thumbnailDimensions = { '--width': displayWidth, '--height': displayHeight } as React.CSSProperties;
2024-05-17 17:25:25 +02:00
let thumbnailComponent: React.ReactNode = null;
if (type === 'image' && !hasError) {
thumbnailComponent = <img src={url} alt='' onLoad={handleLoad} onError={handleError} style={loadingStyle} />;
} else if (type === 'video' && !hasError) {
thumbnailComponent = thumbnail ? (
<img src={thumbnail} alt='' onLoad={handleLoad} onError={handleError} style={loadingStyle} />
) : (
2024-05-29 21:08:03 +02:00
// show first frame of the video, as a workaround for Safari not loading thumbnails
<video src={`${url}#t=0.001`} onError={handleError} />
);
} else if (type === 'webpage' && !hasError) {
thumbnailComponent = <img src={thumbnail} alt='' onLoad={handleLoad} onError={handleError} style={loadingStyle} />;
} else if (type === 'iframe' && iframeThumbnail && !hasError) {
thumbnailComponent = <img src={iframeThumbnail} alt='' onLoad={handleLoad} onError={handleError} style={loadingStyle} />;
} else if (type === 'gif' && gifFrameUrl && !hasError) {
thumbnailComponent = <img src={gifFrameUrl} alt='' onLoad={handleLoad} onError={handleError} style={loadingStyle} />;
} else if (type === 'audio') {
thumbnailComponent = <audio src={url} controls />;
}
return (
<div className={hasError ? '' : styles.mediaWrapper} style={thumbnailDimensions}>
{!isLoaded && !hasError && type !== 'video' && <span className={styles.loadingSkeleton} />}
{hasError ? <img className={styles.fileDeleted} src='/assets/filedeleted-res.gif' alt='File deleted' /> : thumbnailComponent}
</div>
);
};
const CatalogPost = ({ post }: { post: Comment }) => {
const { t } = useTranslation();
2024-06-08 11:27:29 +02:00
const { author, cid, content, isDescription, isRules, lastChildCid, link, linkHeight, linkWidth, locked, pinned, replyCount, subplebbitAddress, timestamp, title } =
post || {};
const commentMediaInfo = getCommentMediaInfo(post);
const hasThumbnail = getHasThumbnail(commentMediaInfo, link);
2024-05-17 17:25:25 +02:00
const location = useLocation();
const isInAllView = isAllView(location.pathname);
const postLink = isInAllView && isDescription ? `/p/all/description` : `/p/${subplebbitAddress}/${isDescription ? 'description' : isRules ? 'rules' : `c/${cid}`}`;
2024-04-12 17:47:30 +02:00
const linkCount = useCountLinksInReplies(post);
2024-04-12 20:48:46 +02:00
const threadIcons = (
<div className={styles.threadIcons}>
{pinned && <span className={styles.stickyIcon} title={t('sticky')} />}
{locked && <span className={styles.closedIcon} title={t('closed')} />}
</div>
);
2024-06-08 11:27:29 +02:00
const [hoveredCid, setHoveredCid] = useState<string | null>(null);
const [showPortal, setShowPortal] = useState<boolean>(false);
const placementRef = useRef<Placement>('right-start');
const availableWidthRef = useRef<number>(0);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const { refs, floatingStyles, update } = useFloating({
placement: placementRef.current,
middleware: [
shift({ padding: 10 }),
offset({ mainAxis: -7 }),
size({
apply({ availableWidth, elements }) {
availableWidthRef.current = availableWidth;
if (availableWidth >= 250) {
elements.floating.style.maxWidth = `${availableWidth - 12}px`;
} else if (placementRef.current === 'right-start') {
placementRef.current = 'left-start';
}
},
}),
],
whileElementsMounted: autoUpdate,
});
useEffect(() => {
const handleResize = () => {
const availableWidth = availableWidthRef.current;
if (availableWidth >= 250) {
placementRef.current = 'right-start';
} else {
placementRef.current = 'left-start';
}
update();
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [update]);
const handleMouseOver = () => {
setHoveredCid(cid);
timeoutRef.current = setTimeout(() => setShowPortal(true), 250);
};
const handleMouseLeave = () => {
setHoveredCid(null);
setShowPortal(false);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
};
const lastReply = useComment({ commentCid: lastChildCid });
const { isCommentAuthorMod: isCatalogPostAuthorMod, commentAuthorRole: catalogPostAuthorRole } = useEditCommentPrivileges({
commentAuthorAddress: author?.address,
subplebbitAddress,
});
const { isCommentAuthorMod: isLastReplyAuthorMod, commentAuthorRole: lastReplyAuthorRole } = useEditCommentPrivileges({
commentAuthorAddress: lastReply?.author?.address,
subplebbitAddress,
});
2024-04-12 17:47:30 +02:00
return (
2024-06-08 11:27:29 +02:00
<>
<div className={styles.post} ref={refs.setReference}>
<div onMouseOver={handleMouseOver} onMouseLeave={handleMouseLeave}>
{hasThumbnail ? (
<Link to={postLink}>
<div className={styles.mediaPaddingWrapper}>
{threadIcons}
<CatalogPostMedia commentMediaInfo={commentMediaInfo} isOutOfFeed={isDescription || isRules} linkWidth={linkWidth} linkHeight={linkHeight} />
</div>
</Link>
) : (
threadIcons
)}
<div className={styles.meta}>
R: <b>{replyCount || '0'}</b>
{linkCount > 0 && (
<span>
{' '}
/ L: <b>{linkCount}</b>
</span>
)}
<span className={`${styles.postMenu} ${hoveredCid && styles.postMenuVisible}`}>
<PostMenuDesktop post={post} />
</span>
2024-04-12 17:47:30 +02:00
</div>
2024-06-08 11:27:29 +02:00
<Link to={postLink}>
<div className={styles.teaser}>
<b>{title && `${title}${content ? ': ' : ''}`}</b>
{content}
</div>
</Link>
2024-04-12 17:47:30 +02:00
</div>
2024-06-08 11:27:29 +02:00
</div>
{hoveredCid === cid &&
showPortal &&
createPortal(
<div className={styles.postPreview} ref={refs.setFloating} style={floatingStyles}>
<span className={styles.postSubject}>{title}</span>
{' by '}
2024-06-08 11:32:25 +02:00
<span className={`${styles.postAuthor} ${(isCatalogPostAuthorMod || isRules || isDescription) && styles.capcode}`}>
2024-06-08 11:27:29 +02:00
{author?.displayName || _.capitalize(t('anonymous'))}
{isCatalogPostAuthorMod && <span className='capitalize'>{` ## Board ${catalogPostAuthorRole}`}</span>}
</span>
<span className={styles.postAgo}> {getFormattedTimeAgo(timestamp)}</span>
{replyCount > 0 && (
<div className={styles.postLast}>
Last reply by{' '}
<span className={`${styles.postAuthor} ${isLastReplyAuthorMod && styles.capcode}`}>
{lastReply?.author?.displayName || _.capitalize(t('anonymous'))}
{isLastReplyAuthorMod && ` ## Board ${lastReplyAuthorRole}`}
</span>
<span className={styles.postAgo}> {getFormattedTimeAgo(lastReply?.timestamp)}</span>
</div>
)}
</div>,
document.body,
)}
</>
2024-04-12 17:47:30 +02:00
);
2024-04-12 14:28:06 +02:00
};
interface CatalogRowProps {
2024-04-14 16:45:59 +02:00
index?: number;
2024-04-12 14:28:06 +02:00
row: Comment[];
}
2024-04-14 16:45:59 +02:00
const CatalogRow = ({ row }: CatalogRowProps) => {
return (
<div className={styles.row}>
{row.map((post, index) => (
2024-05-28 16:44:56 +02:00
<CatalogPost key={index} post={post} />
))}
</div>
);
2024-04-12 14:28:06 +02:00
};
export default CatalogRow;