Files
5chan/src/views/board/board.tsx
T

315 lines
12 KiB
TypeScript
Raw Normal View History

import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useLocation, useParams } from 'react-router-dom';
import { Comment, useAccount, useAccountComments, useAccountSubplebbits, useBlock, useFeed, useSubplebbit } from '@plebbit/plebbit-react-hooks';
2024-03-22 15:31:02 +01:00
import { Virtuoso, VirtuosoHandle, StateSnapshot } from 'react-virtuoso';
import { Trans, useTranslation } from 'react-i18next';
2024-04-13 20:44:54 +02:00
import styles from './board.module.css';
2025-02-20 15:34:30 +01:00
import { shouldShowSnow } from '../../lib/snow';
import { getCommentMediaInfo, getHasThumbnail } from '../../lib/utils/media-utils';
import { isAllView, isSubscriptionsView, isModView } from '../../lib/utils/view-utils';
2024-05-17 14:54:41 +02:00
import { useDefaultSubplebbitAddresses } from '../../hooks/use-default-subplebbits';
import { useResolvedSubplebbitAddress, useBoardPath } from '../../hooks/use-resolved-subplebbit-address';
2025-02-28 23:36:33 +01:00
import { useFeedStateString } from '../../hooks/use-state-string';
import useTimeFilter from '../../hooks/use-time-filter';
2025-02-20 15:34:30 +01:00
import useInterfaceSettingsStore from '../../stores/use-interface-settings-store';
import useFeedResetStore from '../../stores/use-feed-reset-store';
import useSortingStore from '../../stores/use-sorting-store';
import ErrorDisplay from '../../components/error-display/error-display';
2024-03-22 15:31:02 +01:00
import LoadingEllipsis from '../../components/loading-ellipsis';
import SubplebbitDescription from '../../components/subplebbit-description';
import SubplebbitRules from '../../components/subplebbit-rules';
import { Post } from '../post';
2024-03-22 15:31:02 +01:00
const lastVirtuosoStates: { [key: string]: StateSnapshot } = {};
2024-03-17 21:47:16 +01:00
const createThreadsWithoutImagesFilter = () => ({
filter: (comment: Comment) => {
const { link, linkHeight, linkWidth, thumbnailUrl } = comment || {};
if (!getHasThumbnail(getCommentMediaInfo(link, thumbnailUrl, linkWidth, linkHeight), link)) {
return false;
}
return true;
},
key: 'threads-with-images-only',
});
const Board = () => {
2024-03-22 15:31:02 +01:00
const { t } = useTranslation();
2024-05-09 16:04:24 +02:00
const location = useLocation();
const subplebbitAddress = useResolvedSubplebbitAddress();
const boardPath = useBoardPath(subplebbitAddress);
const { hideThreadsWithoutImages } = useInterfaceSettingsStore();
2024-05-17 14:54:41 +02:00
2024-10-29 17:40:09 +01:00
const isInAllView = isAllView(location.pathname);
2024-05-17 14:54:41 +02:00
const defaultSubplebbitAddresses = useDefaultSubplebbitAddresses();
const account = useAccount();
const subscriptions = account?.subscriptions;
const isInSubscriptionsView = isSubscriptionsView(location.pathname, useParams());
2024-05-17 14:54:41 +02:00
const isInModView = isModView(location.pathname);
const { accountSubplebbits } = useAccountSubplebbits();
const accountSubplebbitAddresses = Object.keys(accountSubplebbits);
2024-05-17 14:54:41 +02:00
const subplebbitAddresses = useMemo(() => {
if (isInAllView) {
return defaultSubplebbitAddresses;
}
if (isInSubscriptionsView) {
return subscriptions || [];
}
if (isInModView) {
return accountSubplebbitAddresses;
}
2024-05-17 14:54:41 +02:00
return [subplebbitAddress];
}, [isInAllView, isInSubscriptionsView, isInModView, subplebbitAddress, defaultSubplebbitAddresses, subscriptions, accountSubplebbitAddresses]);
2024-05-17 14:54:41 +02:00
const { sortType } = useSortingStore();
const { timeFilterSeconds, timeFilterName } = useTimeFilter();
2025-02-26 23:10:55 +01:00
const feedOptions = {
subplebbitAddresses,
sortType,
postsPerPage: isInAllView || isInSubscriptionsView || isInModView ? 5 : 25,
...(isInAllView || isInSubscriptionsView || isInModView ? { newerThan: timeFilterSeconds } : {}),
filter: hideThreadsWithoutImages ? createThreadsWithoutImagesFilter() : undefined,
2025-02-26 23:10:55 +01:00
};
const { feed, hasMore, loadMore, reset, subplebbitAddressesWithNewerPosts } = useFeed(feedOptions);
const { accountComments } = useAccountComments();
const resetTriggeredRef = useRef(false);
const setResetFunction = useFeedResetStore((state) => state.setResetFunction);
useEffect(() => {
setResetFunction(reset);
}, [reset, setResetFunction, feed]);
// show account comments instantly in the feed once published (cid defined), instead of waiting for the feed to update
const filteredComments = useMemo(
() =>
accountComments.filter((comment) => {
const { cid, deleted, link, linkHeight, linkWidth, postCid, removed, state, thumbnailUrl, timestamp } = comment || {};
return (
!deleted &&
!removed &&
timestamp > Date.now() / 1000 - 60 * 60 &&
state === 'succeeded' &&
cid &&
(hideThreadsWithoutImages ? getHasThumbnail(getCommentMediaInfo(link, thumbnailUrl, linkWidth, linkHeight), comment?.link) : true) &&
cid === postCid &&
comment?.subplebbitAddress === subplebbitAddress &&
!feed.some((post) => post.cid === cid)
);
}),
2024-09-15 21:38:16 +02:00
[accountComments, subplebbitAddress, feed, hideThreadsWithoutImages],
);
// show newest account comment at the top of the feed but after pinned posts
const combinedFeed = useMemo(() => {
const newFeed = [...feed];
const lastPinnedIndex = newFeed.map((post) => post.pinned).lastIndexOf(true);
if (filteredComments.length > 0) {
newFeed.splice(lastPinnedIndex + 1, 0, ...filteredComments);
}
return newFeed;
}, [feed, filteredComments]);
useEffect(() => {
if (filteredComments.length > 0 && !resetTriggeredRef.current) {
reset();
resetTriggeredRef.current = true;
}
}, [filteredComments, reset]);
2024-04-01 14:24:10 +02:00
const subplebbit = useSubplebbit({ subplebbitAddress });
const { createdAt, description, error, rules, shortAddress, state, suggested } = subplebbit || {};
const title = isInAllView ? t('all') : isInSubscriptionsView ? t('subscriptions') : isInModView ? t('mod') : subplebbit?.title;
2024-04-08 12:33:59 +02:00
const { blocked, unblock } = useBlock({ address: subplebbitAddress });
2024-03-22 15:31:02 +01:00
const handleNewerPostsButtonClick = () => {
window.scrollTo({ top: 0, left: 0 });
setTimeout(() => {
reset();
}, 300);
};
// suggest the user to change time filter if there aren't enough posts
const { feed: weeklyFeed } = useFeed({
subplebbitAddresses,
sortType,
newerThan: 60 * 60 * 24 * 7,
filter: hideThreadsWithoutImages ? createThreadsWithoutImagesFilter() : undefined,
});
const { feed: monthlyFeed } = useFeed({
subplebbitAddresses,
sortType,
newerThan: 60 * 60 * 24 * 30,
filter: hideThreadsWithoutImages ? createThreadsWithoutImagesFilter() : undefined,
});
2025-02-20 13:54:55 +01:00
const feedLength = feed.length;
const weeklyFeedLength = weeklyFeed.length;
const monthlyFeedLength = monthlyFeed.length;
const hasFeedLoaded = !!feed;
const loadingStateString =
2025-02-20 15:34:30 +01:00
useFeedStateString(subplebbitAddresses) ||
(!hasFeedLoaded || (feedLength === 0 && !(weeklyFeedLength > feedLength || monthlyFeedLength > feedLength)) ? t('loading_feed') : t('looking_for_more_posts'));
2025-02-20 13:54:55 +01:00
const [showMorePostsSuggestion, setShowMorePostsSuggestion] = useState(false);
useEffect(() => {
const timer = setTimeout(() => {
setShowMorePostsSuggestion(true);
}, 5000);
return () => clearTimeout(timer);
}, []);
const params = useParams();
const currentTimeFilterName = params?.timeFilterName || timeFilterName;
2024-03-22 15:31:02 +01:00
const Footer = () => {
let footerContent;
if (combinedFeed.length === 0) {
2024-12-21 00:55:18 +01:00
footerContent = t('no_threads');
}
if (hasMore || (subplebbitAddresses && subplebbitAddresses.length === 0)) {
footerContent = (
<>
{subplebbitAddressesWithNewerPosts.length > 0 ? (
<div className={styles.morePostsSuggestion}>
<Trans
2024-12-21 00:55:18 +01:00
i18nKey='newer_threads_available'
components={{
2024-10-15 13:10:47 +02:00
1: <span className={styles.newerPostsButton} onClick={handleNewerPostsButtonClick} />,
}}
/>
</div>
) : (
(isInAllView || isInSubscriptionsView || isInModView) &&
showMorePostsSuggestion &&
monthlyFeed.length > feed.length &&
(weeklyFeed.length > feed.length ? (
<div className={styles.morePostsSuggestion}>
<Trans
2024-12-21 00:55:18 +01:00
i18nKey='more_threads_last_week'
2025-02-20 13:54:55 +01:00
values={{ currentTimeFilterName, count: feed.length }}
components={{
1: <Link to={(isInAllView ? '/all' : isInSubscriptionsView ? '/subscriptions' : isInModView ? '/mod' : `/${boardPath}`) + '/1w'} />,
}}
/>
</div>
) : (
<div className={styles.morePostsSuggestion}>
<Trans
2024-12-21 00:55:18 +01:00
i18nKey='more_threads_last_month'
2025-02-20 13:54:55 +01:00
values={{ currentTimeFilterName, count: feed.length }}
components={{
1: <Link to={(isInAllView ? '/all' : isInSubscriptionsView ? '/subscriptions' : isInModView ? '/mod' : `/${boardPath}`) + '/1m'} />,
}}
/>
</div>
))
)}
</>
);
}
return (
<div className={styles.footer}>
{footerContent}
<div>
{state === 'failed' ? (
<span className='red'>{state}</span>
) : isInSubscriptionsView && subscriptions?.length === 0 ? (
<span className='red'>{t('not_subscribed_to_any_board')}</span>
) : isInModView && accountSubplebbitAddresses?.length === 0 ? (
<span className='red'>{t('not_mod_of_any_board')}</span>
) : blocked ? (
<span className='red'>{t('you_have_blocked_this_board')}</span>
) : (
hasMore && <LoadingEllipsis string={loadingStateString} />
)}
{blocked && (
<>
&nbsp;&nbsp;[
<span
className={styles.button}
onClick={() => {
unblock();
reset();
}}
>
2025-02-11 12:27:03 +01:00
{t('unblock')}
</span>
]
</>
)}
</div>
</div>
);
2024-03-22 15:31:02 +01:00
};
// save the last Virtuoso state to restore it when navigating back
const virtuosoRef = useRef<VirtuosoHandle | null>(null);
useEffect(() => {
const setLastVirtuosoState = () => {
virtuosoRef.current?.getState((snapshot: StateSnapshot) => {
if (snapshot?.ranges?.length) {
lastVirtuosoStates[sortType + timeFilterSeconds] = snapshot;
2024-03-22 15:31:02 +01:00
}
});
};
window.addEventListener('scroll', setLastVirtuosoState);
return () => window.removeEventListener('scroll', setLastVirtuosoState);
}, [sortType, timeFilterSeconds]);
2024-03-22 15:31:02 +01:00
const lastVirtuosoState = lastVirtuosoStates?.[sortType + timeFilterSeconds];
2024-04-01 14:24:10 +02:00
useEffect(() => {
2024-06-28 17:14:57 +02:00
const boardTitle = title ? title : shortAddress || subplebbitAddress;
2025-10-17 23:30:35 +02:00
document.title = boardTitle + ' - 5chan';
2024-06-03 13:53:12 +02:00
}, [title, shortAddress, subplebbitAddress]);
2024-04-01 14:24:10 +02:00
const shouldShowErrorToUser = error?.message && feed.length === 0;
2024-03-22 15:31:02 +01:00
return (
2024-12-24 17:13:12 +01:00
<>
{shouldShowSnow() && <hr />}
<div className={`${styles.content} ${shouldShowSnow() ? styles.garland : ''}`}>
{((description && description.length > 0) || isInAllView) && (
<SubplebbitDescription
avatarUrl={suggested?.avatarUrl}
subplebbitAddress={subplebbitAddress}
createdAt={createdAt}
description={description}
replyCount={isInAllView ? 0 : rules?.length > 0 ? 1 : 0}
shortAddress={shortAddress}
title={title}
/>
)}
{shouldShowErrorToUser && (
<div className={styles.error}>
<ErrorDisplay error={error} />
</div>
)}
2024-12-24 17:13:12 +01:00
{rules && !description && rules.length > 0 && <SubplebbitRules subplebbitAddress={subplebbitAddress} createdAt={createdAt} rules={rules} />}
2025-02-20 15:51:29 +01:00
<Virtuoso
increaseViewportBy={{ bottom: 1200, top: 1200 }}
totalCount={combinedFeed.length}
data={combinedFeed}
2025-03-05 12:01:48 +01:00
itemContent={(index, post) => <Post index={index} post={post} />}
2025-02-20 15:51:29 +01:00
useWindowScroll={true}
components={{ Footer }}
endReached={loadMore}
ref={virtuosoRef}
restoreStateFrom={lastVirtuosoState}
initialScrollTop={lastVirtuosoState?.scrollTop}
/>
2024-12-24 17:13:12 +01:00
</div>
</>
2024-03-22 15:31:02 +01:00
);
2024-03-17 21:47:16 +01:00
};
export default Board;