fix(feeds): force infinite scroll on multiboards and canonicalize page URLs

This commit is contained in:
plebeius
2026-02-22 14:24:45 +08:00
parent 445b271982
commit 71fdbef1ea
42 changed files with 231 additions and 69 deletions
@@ -416,7 +416,9 @@ export const MobileBoardButtons = () => {
const { filteredCount, searchText } = useCatalogFiltersStore();
const enableInfiniteScroll = useFeedViewSettingsStore((state) => state.enableInfiniteScroll);
const showBottomButton = (isInCatalogView || isInPostView || isInPendingPostPage) && !enableInfiniteScroll;
const isMultiboard = isInAllView || isInSubscriptionsView || isInModView;
const effectiveInfiniteScroll = isMultiboard || enableInfiniteScroll;
const showBottomButton = (isInCatalogView || isInPostView || isInPendingPostPage) && !effectiveInfiniteScroll;
// Check if we should show the vote button (only for directory boards)
const directories = useDirectories();
@@ -539,7 +541,9 @@ export const DesktopBoardButtons = () => {
const { filteredCount, searchText } = useCatalogFiltersStore();
const enableInfiniteScroll = useFeedViewSettingsStore((state) => state.enableInfiniteScroll);
const showBottomButton = (isInCatalogView || isInPostView || isInPendingPostPage) && !enableInfiniteScroll;
const isMultiboard = isInAllView || isInSubscriptionsView || isInModView;
const effectiveInfiniteScroll = isMultiboard || enableInfiniteScroll;
const showBottomButton = (isInCatalogView || isInPostView || isInPendingPostPage) && !effectiveInfiniteScroll;
// Check if we should show the vote button (only for directory boards)
const directories = useDirectories();
@@ -72,6 +72,11 @@ describe('InterfaceSettings', () => {
setItemSpy.mockRestore();
});
it('renders enable_infinite_scroll_tip under the infinite scroll checkbox', () => {
render(createElement(InterfaceSettings));
expect(container.textContent).toMatch(/enable_infinite_scroll_tip/i);
});
it('renders enable_infinite_scroll checkbox unchecked by default', () => {
render(createElement(InterfaceSettings));
const label = Array.from(container.querySelectorAll('label')).find((l) => l.textContent?.toLowerCase().includes('enable_infinite_scroll'));
@@ -153,6 +153,7 @@ const InterfaceSettings = () => {
<input type='checkbox' checked={enableInfiniteScroll} onChange={(e) => setEnableInfiniteScroll(e.target.checked)} />
{capitalize(t('enable_infinite_scroll'))}
</label>
<div className={styles.settingTip}>{capitalize(t('enable_infinite_scroll_tip'))}</div>
</div>
</div>
);
@@ -0,0 +1,29 @@
import { describe, it, expect } from 'vitest';
import { normalizeMultiboardFeedPath } from '../route-utils';
describe('normalizeMultiboardFeedPath', () => {
it('normalizes /all/3 -> /all', () => {
expect(normalizeMultiboardFeedPath('/all/3')).toBe('/all');
});
it('normalizes /all/1w/3 -> /all/1w', () => {
expect(normalizeMultiboardFeedPath('/all/1w/3')).toBe('/all/1w');
});
it('normalizes /subs/2/settings -> /subs/settings', () => {
expect(normalizeMultiboardFeedPath('/subs/2/settings')).toBe('/subs/settings');
});
it('normalizes /mod/catalog/4 -> /mod/catalog', () => {
expect(normalizeMultiboardFeedPath('/mod/catalog/4')).toBe('/mod/catalog');
});
it('leaves non-multiboard paths unchanged', () => {
expect(normalizeMultiboardFeedPath('/biz')).toBe('/biz');
expect(normalizeMultiboardFeedPath('/biz/3')).toBe('/biz/3');
expect(normalizeMultiboardFeedPath('/biz/1w/2')).toBe('/biz/1w/2');
expect(normalizeMultiboardFeedPath('/biz/catalog/4')).toBe('/biz/catalog/4');
expect(normalizeMultiboardFeedPath('/pending/0')).toBe('/pending/0');
expect(normalizeMultiboardFeedPath('/')).toBe('/');
});
});
+37
View File
@@ -150,6 +150,43 @@ export const BOARD_PAGE_REGEX = /^([1-9]|10)$/;
export const isBoardFeedPageNumber = (segment: string): boolean => BOARD_PAGE_REGEX.test(segment);
/** Internal: check if segment is a multiboard root (all, subs, mod) */
function isMultiboardRoot(segment: string): boolean {
return segment === 'all' || segment === 'subs' || segment === 'mod';
}
/** Internal: check if pathname is a multiboard feed path (starts with /all, /subs, or /mod) */
function isMultiboardFeedPath(pathname: string): boolean {
const trimmed = pathname.replace(/\/$/, '');
const segments = trimmed.split('/').filter(Boolean);
return segments.length > 0 && isMultiboardRoot(segments[0]);
}
/**
* Normalize multiboard feed paths by removing trailing page-number segments (110),
* while preserving /settings and valid time-filter segments.
* Non-multiboard paths are returned unchanged.
*/
export const normalizeMultiboardFeedPath = (pathname: string): string => {
let path = pathname.replace(/\/$/, '');
if (!isMultiboardFeedPath(path)) {
return pathname;
}
const hasSettings = path.endsWith('/settings');
if (hasSettings) {
path = path.replace(/\/settings$/, '');
}
const segments = path.split('/').filter(Boolean);
if (segments.length > 1 && isBoardFeedPageNumber(segments[segments.length - 1])) {
const newPath = '/' + segments.slice(0, -1).join('/');
return hasSettings ? newPath + '/settings' : newPath;
}
return hasSettings ? path + '/settings' : path;
};
/** Strip trailing page number (110) from path for feed cache key */
export const stripPageFromFeedPath = (path: string): string => {
const segments = path.split('/').filter(Boolean);
+28 -16
View File
@@ -16,7 +16,7 @@ import useSortingStore from '../../stores/use-sorting-store';
import useFeedViewSettingsStore from '../../stores/use-feed-view-settings-store';
import { useBoardFeedPageSize } from '../../hooks/use-board-feed-page-size';
import { getPageSlice } from '../../lib/utils/board-feed-pagination';
import { getPageFromFeedPath, getSubplebbitAddress, isDirectoryBoard, stripPageFromFeedPath } from '../../lib/utils/route-utils';
import { getPageFromFeedPath, getSubplebbitAddress, isDirectoryBoard, normalizeMultiboardFeedPath, stripPageFromFeedPath } from '../../lib/utils/route-utils';
import ErrorDisplay from '../../components/error-display/error-display';
import LoadingEllipsis from '../../components/loading-ellipsis';
import BoardPagination from '../../components/board-pagination';
@@ -209,6 +209,8 @@ const Board = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp, t
const timeFilterSeconds = timeFilterNameFromCache ? timeFilterNameToSeconds(timeFilterNameFromCache) : timeFilterSecondsFromHook;
const enableInfiniteScroll = useFeedViewSettingsStore((state) => state.enableInfiniteScroll);
const isForcedInfiniteScroll = isInAllView || isInSubscriptionsView || isInModView;
const effectiveInfiniteScroll = enableInfiniteScroll || isForcedInfiniteScroll;
const community = useDirectoryByAddress(isInAllView || isInSubscriptionsView || isInModView ? undefined : subplebbitAddress);
const { guiPostsPerPage, maxGuiPages, paginationFeedPostsPerPage, infiniteFeedPostsPerPage } = useBoardFeedPageSize(community);
@@ -216,13 +218,13 @@ const Board = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp, t
() => ({
subplebbitAddresses,
sortType,
postsPerPage: enableInfiniteScroll ? infiniteFeedPostsPerPage : paginationFeedPostsPerPage,
postsPerPage: effectiveInfiniteScroll ? infiniteFeedPostsPerPage : paginationFeedPostsPerPage,
...(isInAllView || isInSubscriptionsView || isInModView ? { newerThan: timeFilterSeconds } : {}),
}),
[
subplebbitAddresses,
sortType,
enableInfiniteScroll,
effectiveInfiniteScroll,
infiniteFeedPostsPerPage,
paginationFeedPostsPerPage,
isInAllView,
@@ -235,7 +237,7 @@ const Board = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp, t
const { feed, hasMore, loadMore, reset, subplebbitAddressesWithNewerPosts } = useFeed(feedOptions);
const { accountComments } = useAccountComments();
const feedContextKey = `${isInAllView ? 'all' : isInSubscriptionsView ? 'subs' : isInModView ? 'mod' : (subplebbitAddress ?? 'board')}-${sortType}-${timeFilterSeconds}-${viewType ?? 'board'}-${enableInfiniteScroll}`;
const feedContextKey = `${isInAllView ? 'all' : isInSubscriptionsView ? 'subs' : isInModView ? 'mod' : (subplebbitAddress ?? 'board')}-${sortType}-${timeFilterSeconds}-${viewType ?? 'board'}-${effectiveInfiniteScroll}`;
const pathWithoutSettings = location.pathname.replace(/\/settings$/, '');
const currentPage = getPageFromFeedPath(pathWithoutSettings);
const paginationBasePath = stripPageFromFeedPath(pathWithoutSettings);
@@ -279,30 +281,40 @@ const Board = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp, t
}, [feed, filteredComments]);
const cappedFeed = useMemo(
() => (enableInfiniteScroll ? combinedFeed : combinedFeed.slice(0, guiPostsPerPage * maxGuiPages)),
[enableInfiniteScroll, combinedFeed, guiPostsPerPage, maxGuiPages],
() => (effectiveInfiniteScroll ? combinedFeed : combinedFeed.slice(0, guiPostsPerPage * maxGuiPages)),
[effectiveInfiniteScroll, combinedFeed, guiPostsPerPage, maxGuiPages],
);
const totalPages = useMemo(() => Math.min(maxGuiPages, Math.ceil(cappedFeed.length / guiPostsPerPage) || 1), [cappedFeed.length, guiPostsPerPage, maxGuiPages]);
const currentPageFeed = useMemo(
() => (enableInfiniteScroll ? [] : getPageSlice(cappedFeed, currentPage, guiPostsPerPage, maxGuiPages)),
[enableInfiniteScroll, cappedFeed, currentPage, guiPostsPerPage, maxGuiPages],
() => (effectiveInfiniteScroll ? [] : getPageSlice(cappedFeed, currentPage, guiPostsPerPage, maxGuiPages)),
[effectiveInfiniteScroll, cappedFeed, currentPage, guiPostsPerPage, maxGuiPages],
);
const navigate = useNavigate();
// Redirect multiboard paths with page-number segments to normalized path (infinite-scroll only)
useEffect(() => {
if (!enableInfiniteScroll && currentPage > totalPages && totalPages > 0) {
if (!isForcedInfiniteScroll) return;
const normalized = normalizeMultiboardFeedPath(location.pathname);
if (normalized !== location.pathname) {
navigate(normalized, { replace: true });
}
}, [isForcedInfiniteScroll, location.pathname, navigate]);
useEffect(() => {
if (!effectiveInfiniteScroll && currentPage > totalPages && totalPages > 0) {
const targetPage = totalPages;
const targetPath = targetPage === 1 ? paginationBasePath : `${paginationBasePath}/${targetPage}`;
navigate(targetPage === 1 ? paginationBasePath : `${paginationBasePath}/${targetPage}`, { replace: true });
navigate(targetPath, { replace: true });
}
}, [enableInfiniteScroll, currentPage, totalPages, paginationBasePath, navigate]);
}, [effectiveInfiniteScroll, currentPage, totalPages, paginationBasePath, navigate]);
// Scroll to top instantly when page changes in pagination mode
useEffect(() => {
if (!enableInfiniteScroll) {
if (!effectiveInfiniteScroll) {
window.scrollTo({ top: 0, left: 0, behavior: 'instant' });
}
}, [enableInfiniteScroll, currentPage]);
}, [effectiveInfiniteScroll, currentPage]);
useEffect(() => {
if (filteredComments.length > 0 && !resetTriggeredRef.current) {
@@ -383,7 +395,7 @@ const Board = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp, t
subplebbitState={subplebbitState}
subscriptionsLength={subscriptions?.length || 0}
accountSubplebbitAddressesLength={accountSubplebbitAddresses?.length || 0}
showLoadingEllipsis={enableInfiniteScroll || combinedFeed.length === 0}
showLoadingEllipsis={effectiveInfiniteScroll || combinedFeed.length === 0}
/>
),
}),
@@ -406,7 +418,7 @@ const Board = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp, t
subplebbitState,
subscriptions?.length,
accountSubplebbitAddresses?.length,
enableInfiniteScroll,
effectiveInfiniteScroll,
combinedFeed.length,
],
);
@@ -474,7 +486,7 @@ const Board = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp, t
</div>
)}
{/* Infinite mode: Virtuoso when hasMore, else plain list */}
{enableInfiniteScroll ? (
{effectiveInfiniteScroll ? (
hasMore ? (
<Virtuoso
increaseViewportBy={{ bottom: 1200, top: 1200 }}
+55 -16
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import { Link, useLocation, useNavigationType, useParams } from 'react-router-dom';
import { Link, useLocation, useNavigate, useNavigationType, useParams } from 'react-router-dom';
import { Trans, useTranslation } from 'react-i18next';
import { Comment, useAccount, useFeed, useSubplebbit, useAccountComments } from '@plebbit/plebbit-react-hooks';
import { Virtuoso, VirtuosoHandle, StateSnapshot } from 'react-virtuoso';
@@ -16,7 +16,7 @@ import useFeedResetStore from '../../stores/use-feed-reset-store';
import useFeedViewSettingsStore from '../../stores/use-feed-view-settings-store';
import useSortingStore from '../../stores/use-sorting-store';
import useCatalogFiltersStore from '../../stores/use-catalog-filters-store';
import { getSubplebbitAddress, isDirectoryBoard } from '../../lib/utils/route-utils';
import { getSubplebbitAddress, isDirectoryBoard, normalizeMultiboardFeedPath } from '../../lib/utils/route-utils';
import CatalogRow from '../../components/catalog-row';
import LoadingEllipsis from '../../components/loading-ellipsis';
import ErrorDisplay from '../../components/error-display/error-display';
@@ -34,6 +34,7 @@ interface CatalogFooterProps {
onNewerPostsClick: () => void;
isInAllView: boolean;
isInSubscriptionsView: boolean;
isInModView: boolean;
showMorePostsSuggestion: boolean;
weeklyFeedLength: number;
monthlyFeedLength: number;
@@ -56,6 +57,7 @@ const CatalogFooter = ({
onNewerPostsClick,
isInAllView,
isInSubscriptionsView,
isInModView,
showMorePostsSuggestion,
weeklyFeedLength,
monthlyFeedLength,
@@ -91,7 +93,7 @@ const CatalogFooter = ({
/>
</div>
) : (
(isInAllView || isInSubscriptionsView) &&
(isInAllView || isInSubscriptionsView || isInModView) &&
showMorePostsSuggestion &&
(monthlyFeedLength > feedLength || yearlyFeedLength > monthlyFeedLength) &&
(weeklyFeedLength > feedLength ? (
@@ -100,7 +102,11 @@ const CatalogFooter = ({
i18nKey='more_threads_last_week'
values={{ currentTimeFilterName, count: feedLength }}
components={{
1: <Link to={(isInAllView ? '/all/catalog' : isInSubscriptionsView ? '/subs/catalog' : `/${boardPath}/catalog`) + '/1w'} />,
1: (
<Link
to={(isInAllView ? '/all/catalog' : isInSubscriptionsView ? '/subs/catalog' : isInModView ? '/mod/catalog' : `/${boardPath}/catalog`) + '/1w'}
/>
),
}}
/>
</div>
@@ -110,7 +116,11 @@ const CatalogFooter = ({
i18nKey='more_threads_last_month'
values={{ currentTimeFilterName, count: feedLength }}
components={{
1: <Link to={(isInAllView ? '/all/catalog' : isInSubscriptionsView ? '/subs/catalog' : `/${boardPath}/catalog`) + '/1m'} />,
1: (
<Link
to={(isInAllView ? '/all/catalog' : isInSubscriptionsView ? '/subs/catalog' : isInModView ? '/mod/catalog' : `/${boardPath}/catalog`) + '/1m'}
/>
),
}}
/>
</div>
@@ -120,7 +130,11 @@ const CatalogFooter = ({
i18nKey='more_threads_last_year'
values={{ currentTimeFilterName, count: feedLength }}
components={{
1: <Link to={(isInAllView ? '/all/catalog' : isInSubscriptionsView ? '/subs/catalog' : `/${boardPath}/catalog`) + '/1y'} />,
1: (
<Link
to={(isInAllView ? '/all/catalog' : isInSubscriptionsView ? '/subs/catalog' : isInModView ? '/mod/catalog' : `/${boardPath}/catalog`) + '/1y'}
/>
),
}}
/>
</div>
@@ -282,10 +296,16 @@ export interface CatalogProps {
const Catalog = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp, timeFilterNameFromCache, isVisible = true }: CatalogProps) => {
const { t } = useTranslation();
const location = useLocation();
const navigate = useNavigate();
const params = useParams();
const isInAllView = viewType ? viewType === 'all' : false;
const isInSubscriptionsView = viewType ? viewType === 'subs' : false;
const isInModView = viewType ? viewType === 'mod' : false;
const enableInfiniteScroll = useFeedViewSettingsStore((state) => state.enableInfiniteScroll);
const isForcedInfiniteScroll = isInAllView || isInSubscriptionsView || isInModView;
const effectiveInfiniteScroll = enableInfiniteScroll || isForcedInfiniteScroll;
const directories = useDirectories();
const resolvedAddressFromUrl = useResolvedSubplebbitAddress();
@@ -320,10 +340,18 @@ const Catalog = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp,
const columnCount = Math.floor(useWindowWidth() / columnWidth);
const postsPerPage = columnCount <= 2 ? 10 : columnCount === 3 ? 15 : columnCount === 4 ? 20 : 25;
const enableInfiniteScroll = useFeedViewSettingsStore((state) => state.enableInfiniteScroll);
const community = useDirectoryByAddress(isInAllView || isInSubscriptionsView ? undefined : subplebbitAddress);
const community = useDirectoryByAddress(isInAllView || isInSubscriptionsView || isInModView ? undefined : subplebbitAddress);
const { guiPostsPerPage: boardPostsPerPage, maxGuiPages, paginationFeedPostsPerPage, infiniteFeedPostsPerPage } = useBoardFeedPageSize(community);
// Canonical redirect for multiboard catalog paths with numeric page segment (e.g. /all/catalog/1w/5 -> /all/catalog/1w)
useEffect(() => {
if (!(isInAllView || isInSubscriptionsView || isInModView)) return;
const canonical = normalizeMultiboardFeedPath(location.pathname);
if (location.pathname !== canonical) {
navigate(canonical, { replace: true });
}
}, [isInAllView, isInSubscriptionsView, isInModView, location.pathname, navigate]);
const { timeFilterSeconds: timeFilterSecondsFromHook, timeFilterName: timeFilterNameFromHook } = useTimeFilter();
const { sortType } = useSortingStore();
const timeFilterName = timeFilterNameFromCache || timeFilterNameFromHook;
@@ -344,7 +372,13 @@ const Catalog = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp,
const feedOptions = useMemo(() => {
const catalogPostsPerPage =
isInAllView || isInSubscriptionsView ? (enableInfiniteScroll ? 10 : 100) : enableInfiniteScroll ? infiniteFeedPostsPerPage : paginationFeedPostsPerPage;
isInAllView || isInSubscriptionsView || isInModView
? effectiveInfiniteScroll
? 10
: 100
: effectiveInfiniteScroll
? infiniteFeedPostsPerPage
: paginationFeedPostsPerPage;
const options: any = {
subplebbitAddresses,
@@ -353,7 +387,7 @@ const Catalog = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp,
filter: createCombinedFilter(filterItems, searchText, subplebbitAddress || 'all', handleFilterMatch),
};
if (isInAllView || isInSubscriptionsView) {
if (isInAllView || isInSubscriptionsView || isInModView) {
options.newerThan = timeFilterSeconds;
}
@@ -363,7 +397,8 @@ const Catalog = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp,
sortType,
isInAllView,
isInSubscriptionsView,
enableInfiniteScroll,
isInModView,
effectiveInfiniteScroll,
infiniteFeedPostsPerPage,
paginationFeedPostsPerPage,
timeFilterSeconds,
@@ -420,8 +455,8 @@ const Catalog = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp,
}, [feed, filteredComments]);
const cappedFeed = useMemo(
() => (enableInfiniteScroll ? combinedFeed : combinedFeed.slice(0, boardPostsPerPage * maxGuiPages)),
[enableInfiniteScroll, combinedFeed, boardPostsPerPage, maxGuiPages],
() => (effectiveInfiniteScroll ? combinedFeed : combinedFeed.slice(0, boardPostsPerPage * maxGuiPages)),
[effectiveInfiniteScroll, combinedFeed, boardPostsPerPage, maxGuiPages],
);
useEffect(() => {
@@ -499,13 +534,14 @@ const Catalog = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp,
onNewerPostsClick={handleNewerPostsButtonClick}
isInAllView={isInAllView}
isInSubscriptionsView={isInSubscriptionsView}
isInModView={isInModView}
showMorePostsSuggestion={showMorePostsSuggestion}
weeklyFeedLength={weeklyFeedLength}
monthlyFeedLength={monthlyFeedLength}
yearlyFeedLength={yearlyFeedLength}
boardPath={boardPath}
currentTimeFilterName={currentTimeFilterName}
showLoadingEllipsis={enableInfiniteScroll}
showLoadingEllipsis={effectiveInfiniteScroll}
/>
),
}),
@@ -518,13 +554,14 @@ const Catalog = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp,
handleNewerPostsButtonClick,
isInAllView,
isInSubscriptionsView,
isInModView,
showMorePostsSuggestion,
weeklyFeedLength,
monthlyFeedLength,
yearlyFeedLength,
boardPath,
currentTimeFilterName,
enableInfiniteScroll,
effectiveInfiniteScroll,
],
);
@@ -650,7 +687,7 @@ const Catalog = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp,
<div className={styles.catalog}>
{processedFeed?.length !== 0 ? (
<>
{enableInfiniteScroll ? (
{effectiveInfiniteScroll ? (
hasMore ? (
<Virtuoso
increaseViewportBy={{ bottom: 1200, top: 1200 }}
@@ -678,6 +715,7 @@ const Catalog = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp,
onNewerPostsClick={handleNewerPostsButtonClick}
isInAllView={isInAllView}
isInSubscriptionsView={isInSubscriptionsView}
isInModView={isInModView}
showMorePostsSuggestion={showMorePostsSuggestion}
weeklyFeedLength={weeklyFeedLength}
monthlyFeedLength={monthlyFeedLength}
@@ -702,6 +740,7 @@ const Catalog = ({ feedCacheKey, viewType, boardIdentifier: boardIdentifierProp,
onNewerPostsClick={handleNewerPostsButtonClick}
isInAllView={isInAllView}
isInSubscriptionsView={isInSubscriptionsView}
isInModView={isInModView}
showMorePostsSuggestion={showMorePostsSuggestion}
weeklyFeedLength={weeklyFeedLength}
monthlyFeedLength={monthlyFeedLength}