import { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { Link, useLocation, useParams } from 'react-router-dom';
import { useFloating, offset, size, autoUpdate, Placement } from '@floating-ui/react';
import { Comment } from '@plebbit/plebbit-react-hooks';
import Plebbit from '@plebbit/plebbit-js';
import { shouldShowSnow } from '../../lib/snow';
import { getHasThumbnail } from '../../lib/utils/media-utils';
import { getFormattedTimeAgo } from '../../lib/utils/time-utils';
import { isAllView, isSubscriptionsView } from '../../lib/utils/view-utils';
import { useDefaultSubplebbits } from '../../hooks/use-default-subplebbits';
import { getBoardPath } from '../../lib/utils/route-utils';
import useCatalogFiltersStore from '../../stores/use-catalog-filters-store';
import useCatalogStyleStore from '../../stores/use-catalog-style-store';
import useEditCommentPrivileges from '../../hooks/use-author-privileges';
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 useWindowWidth from '../../hooks/use-window-width';
import useReplies from '../../hooks/use-replies';
import { ContentPreview } from '../../views/home/popular-threads-box';
import PostMenuDesktop from '../post-desktop/post-menu-desktop';
import styles from './catalog-row.module.css';
import _ from 'lodash';
import { selectPostMenuProps } from '../../lib/utils/post-menu-props';
interface CatalogPostMediaProps {
cid: string;
commentMediaInfo: any;
isOutOfFeed?: boolean;
linkWidth?: number;
linkHeight?: number;
}
export const CatalogPostMedia = ({ cid, commentMediaInfo, linkWidth, linkHeight }: CatalogPostMediaProps) => {
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' };
const { imageSize } = useCatalogStyleStore();
let displayWidth, displayHeight;
const maxThumbnailSize = imageSize === 'Large' ? 250 : 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') {
displayWidth = 'unset';
displayHeight = 'unset';
}
const maxWidth = imageSize === 'Large' ? '250px' : '150px';
const maxHeight = imageSize === 'Large' ? '250px' : '150px';
const CSSProperties = {
'--width': displayWidth,
'--height': displayHeight,
'--maxWidth': maxWidth,
'--maxHeight': maxHeight,
} as React.CSSProperties;
let thumbnailComponent: React.ReactNode = null;
if (type === 'gif' && gifFrameUrl && !hasError) {
thumbnailComponent =
;
} else if (type === 'image' && !hasError) {
thumbnailComponent =
;
} else if (type === 'video' && !hasError) {
thumbnailComponent = thumbnail ? (
) : (
// show first frame of the video, as a workaround for Safari not loading thumbnails
);
} else if (type === 'webpage' && !hasError) {
thumbnailComponent =
;
} else if (type === 'iframe' && iframeThumbnail && !hasError) {
thumbnailComponent =
;
} else if (type === 'audio') {
thumbnailComponent = ;
}
const matchedFilterColor = useCatalogFiltersStore((state) => state.matchedFilters.get(cid || ''));
return (
{!isLoaded && !hasError && type !== 'video' && type !== 'audio' &&
}
{hasError ?

: thumbnailComponent}
);
};
const CatalogPost = ({ post }: { post: Comment }) => {
const { t } = useTranslation();
const { author, cid, content, link, linkHeight, linkWidth, locked, pinned, replyCount, spoiler, subplebbitAddress, timestamp, title, thumbnailUrl } = post || {};
const linkCount = useCountLinksInReplies(post);
const commentMediaInfo = useCommentMediaInfo(link, thumbnailUrl, linkWidth, linkHeight);
const hasThumbnail = getHasThumbnail(commentMediaInfo, link);
const { hidden } = useHide({ cid });
const location = useLocation();
const params = useParams();
const isInAllView = isAllView(location.pathname);
const isInSubscriptionsView = isSubscriptionsView(location.pathname, params);
const defaultSubplebbits = useDefaultSubplebbits();
const boardPath = subplebbitAddress ? getBoardPath(subplebbitAddress, defaultSubplebbits) : '';
const postMenuProps = useMemo(() => selectPostMenuProps(post), [post]);
const postLink = boardPath ? `/${boardPath}/thread/${cid}` : `/thread/${cid}`;
const threadIcons = (
{pinned && }
{locked && }
);
const [hoveredCid, setHoveredCid] = useState(null);
const [showPortal, setShowPortal] = useState(false);
const placementRef = useRef('right-start');
const timeoutRef = useRef(null);
const windowWidth = useWindowWidth();
const { refs, floatingStyles, update } = useFloating({
open: showPortal,
placement: placementRef.current,
middleware: [
offset({ mainAxis: 5 }),
size({
apply({ elements }) {
const referenceElement = refs.reference.current;
if (referenceElement) {
const availableWidthToTheRight = windowWidth - (referenceElement.getBoundingClientRect().left + referenceElement.getBoundingClientRect().width);
const availableWidthToTheLeft = referenceElement.getBoundingClientRect().left;
const minWidth = windowWidth * 0.25;
if (availableWidthToTheRight >= minWidth) {
placementRef.current = 'right-start';
elements.floating.style.maxWidth = `${availableWidthToTheRight - 40}px`;
} else if (availableWidthToTheLeft >= minWidth) {
placementRef.current = 'left-start';
elements.floating.style.maxWidth = `${availableWidthToTheLeft - 25}px`;
} else if (availableWidthToTheRight > availableWidthToTheLeft) {
placementRef.current = 'right-start';
elements.floating.style.maxWidth = `${availableWidthToTheRight - 40}px`;
} else {
placementRef.current = 'left-start';
elements.floating.style.maxWidth = `${availableWidthToTheLeft - 25}px`;
}
}
},
}),
],
whileElementsMounted: autoUpdate,
});
useEffect(() => {
update();
}, [update, windowWidth]);
const replies = useReplies(post);
const lastReply = replies.length > 0 ? replies[replies.length - 1] : null;
const { isCommentAuthorMod: isCatalogPostAuthorMod, commentAuthorRole: catalogPostAuthorRole } = useEditCommentPrivileges({
commentAuthorAddress: author?.address,
subplebbitAddress,
});
const { isCommentAuthorMod: isLastReplyAuthorMod, commentAuthorRole: lastReplyAuthorRole } = useEditCommentPrivileges({
commentAuthorAddress: lastReply?.author?.address,
subplebbitAddress,
});
const postContent = (
{hidden ? (
({t('hidden')})
) : (
<>
{title && (
{title}
{content ? ': ' : ''}
)}
{content && }
>
)}
);
const { imageSize, showOPComment } = useCatalogStyleStore();
const maxWidth = imageSize === 'Large' ? '250px' : '150px';
const maxHeight = imageSize === 'Large' ? '250px' : '150px';
const CSSProperties = {
'--maxWidth': maxWidth,
'--maxHeight': maxHeight,
} as React.CSSProperties;
const isTextOnlyThread = !hasThumbnail;
return (
<>
setHoveredCid(cid)} onMouseLeave={() => setHoveredCid(null)}>
{hidden ? (
) : hasThumbnail ? (
<>
{shouldShowSnow() && hasThumbnail &&

}
(timeoutRef.current = setTimeout(() => setShowPortal(true), 250))}
onMouseLeave={() => {
setShowPortal(false);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
}}
>
{threadIcons}
{spoiler ? (

) : (
)}
>
) : (
threadIcons
)}
R:
{replyCount || '0'}
{linkCount > 0 && (
{' '}
/ L: {linkCount}
)}
{(showOPComment || isTextOnlyThread) && (hasThumbnail ? postContent : {postContent})}
{hoveredCid === cid &&
showPortal &&
createPortal(
{title ? (
<>
{title}
{t('by')}
>
) : (
t('posted_by')
)}{' '}
{author?.displayName || _.capitalize(t('anonymous'))}
{isCatalogPostAuthorMod && {` ## Board ${catalogPostAuthorRole}`}}
{(isInAllView || isInSubscriptionsView) && subplebbitAddress && ` to p/${Plebbit.getShortAddress(subplebbitAddress)}`}
{getFormattedTimeAgo(timestamp)}
{replyCount > 0 && (
{t('last_reply_by')}{' '}
{lastReply?.author?.displayName || _.capitalize(t('anonymous'))}
{isLastReplyAuthorMod && ` ## Board ${lastReplyAuthorRole}`}
{getFormattedTimeAgo(lastReply?.timestamp)}
)}
,
document.body,
)}
>
);
};
interface CatalogRowProps {
index?: number;
row: Comment[];
}
const CatalogRow = ({ row }: CatalogRowProps) => {
return (
{row.map((post, index) => (
))}
);
};
export default CatalogRow;