mirror of
https://github.com/readest/readest.git
synced 2026-11-29 19:02:28 +00:00
fix(opds): keep the feed scroll position after opening a book (#6683)
Opening a publication switches the OPDS page to the detail view and unmounts FeedView, so coming back always started the grid at the top. The publications grid now saves its scroll offset, keyed by the feed URL, and applies it once the remounted grid has measured its first items. The offset is only restored onto the same entries it was saved from, and the scroll event fired while the scroller is torn down is not recorded. VirtuosoGrid has no getState() handle, and restoreStateFrom on a fresh grid never lays out its items, so the offset is restored with scrollTo instead. Signed-off-by: Gaurav Jadhav <gaurav.vjadhav01@gmail.com>
This commit is contained in:
parent
e969cc54f3
commit
a39f46daf9
3 changed files with 170 additions and 7 deletions
|
|
@ -0,0 +1,93 @@
|
|||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { cleanup, fireEvent, render, waitFor } from '@testing-library/react';
|
||||
import type { OPDSFeed, OPDSPublication } from '@/types/opds';
|
||||
import { FeedView } from '@/app/opds/components/FeedView';
|
||||
|
||||
vi.mock('@/hooks/useTranslation', () => ({
|
||||
useTranslation: () => (s: string) => s,
|
||||
}));
|
||||
vi.mock('@/components/CachedImage', () => ({
|
||||
CachedImage: () => <div />,
|
||||
}));
|
||||
await import('@/styles/globals.css');
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const WAIT = { timeout: 5000 };
|
||||
|
||||
const feedOf = (count: number): OPDSFeed => ({
|
||||
metadata: { title: 'Catalog' },
|
||||
links: [],
|
||||
publications: Array.from(
|
||||
{ length: count },
|
||||
(_, index): OPDSPublication => ({
|
||||
metadata: { id: `urn:book:${index}`, title: `Book ${index}` },
|
||||
links: [],
|
||||
images: [],
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const renderFeed = (feed: OPDSFeed, scrollKey?: string) =>
|
||||
render(
|
||||
<div style={{ width: 900, height: 600 }}>
|
||||
<FeedView
|
||||
feed={feed}
|
||||
baseURL='https://opds.example.com/opds'
|
||||
resolveURL={(href, base) => new URL(href, base).toString()}
|
||||
onNavigate={vi.fn()}
|
||||
onPublicationSelect={vi.fn()}
|
||||
onGenerateCachedImageUrl={vi.fn(async (url: string) => url)}
|
||||
isOPDSCatalog={() => true}
|
||||
scrollKey={scrollKey}
|
||||
/>
|
||||
</div>,
|
||||
);
|
||||
|
||||
const scrollerOf = (root: HTMLElement) =>
|
||||
root.querySelector<HTMLElement>('[data-virtuoso-scroller]')!;
|
||||
|
||||
const firstVisible = (root: HTMLElement) => {
|
||||
const top = scrollerOf(root).getBoundingClientRect().top;
|
||||
const card = Array.from(root.querySelectorAll<HTMLElement>('[data-index]')).find(
|
||||
(el) => el.getBoundingClientRect().bottom > top,
|
||||
);
|
||||
return card?.textContent?.match(/Book \d+/)?.[0];
|
||||
};
|
||||
|
||||
describe('OPDS feed scroll position in Chromium', () => {
|
||||
it('returns to the same place after the feed remounts (opening a book and coming back)', async () => {
|
||||
const first = renderFeed(feedOf(400), 'https://opds.example.com/opds/all');
|
||||
const scroller = scrollerOf(first.container);
|
||||
await waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(5000), WAIT);
|
||||
scroller.scrollTop = 4000;
|
||||
fireEvent.scroll(scroller);
|
||||
await waitFor(() => expect(firstVisible(first.container)).not.toMatch(/^Book [0-9]$/), WAIT);
|
||||
const scrollTop = scroller.scrollTop;
|
||||
const book = firstVisible(first.container);
|
||||
expect(scrollTop).toBeGreaterThan(0);
|
||||
first.unmount();
|
||||
|
||||
const second = renderFeed(feedOf(400), 'https://opds.example.com/opds/all');
|
||||
await waitFor(() => expect(scrollerOf(second.container).scrollTop).toBe(scrollTop), WAIT);
|
||||
await waitFor(() => expect(firstVisible(second.container)).toBe(book), WAIT);
|
||||
second.unmount();
|
||||
|
||||
// A different feed has its own position: it starts at the top.
|
||||
const other = renderFeed(feedOf(400), 'https://opds.example.com/opds/other');
|
||||
await waitFor(
|
||||
() => expect(scrollerOf(other.container).scrollHeight).toBeGreaterThan(5000),
|
||||
WAIT,
|
||||
);
|
||||
expect(scrollerOf(other.container).scrollTop).toBe(0);
|
||||
other.unmount();
|
||||
|
||||
// Same key but different entries: the saved offset no longer applies.
|
||||
const changed = renderFeed(feedOf(250), 'https://opds.example.com/opds/all');
|
||||
await waitFor(
|
||||
() => expect(scrollerOf(changed.container).scrollHeight).toBeGreaterThan(3000),
|
||||
WAIT,
|
||||
);
|
||||
expect(scrollerOf(changed.container).scrollTop).toBe(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
'use client';
|
||||
|
||||
import { useMemo, useCallback } from 'react';
|
||||
import { VirtuosoGrid } from 'react-virtuoso';
|
||||
import { useMemo, useCallback, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { VirtuosoGrid, type GridStateSnapshot, type VirtuosoGridHandle } from 'react-virtuoso';
|
||||
import { IoAdd, IoChevronBack, IoChevronForward, IoFilter } from 'react-icons/io5';
|
||||
import { useTranslation } from '@/hooks/useTranslation';
|
||||
import { OPDSFeed, OPDSGenericLink } from '@/types/opds';
|
||||
import { OPDSFeed, OPDSGenericLink, OPDSPublication } from '@/types/opds';
|
||||
import { PublicationCard } from './PublicationCard';
|
||||
import { NavigationCard } from './NavigationCard';
|
||||
import { GroupCarousel } from './GroupCarousel';
|
||||
|
|
@ -19,12 +19,80 @@ interface FeedViewProps {
|
|||
onGenerateCachedImageUrl: (url: string, cacheVersion?: string) => Promise<string>;
|
||||
isOPDSCatalog: (type?: string) => boolean;
|
||||
onAddCatalog?: () => void;
|
||||
/** Identifies the feed; its scroll position survives remounts (open a book, come back). */
|
||||
scrollKey?: string;
|
||||
}
|
||||
|
||||
const gridClassName = 'grid grid-cols-3 gap-4 px-4 sm:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6';
|
||||
const navigationClassName =
|
||||
'grid grid-cols-2 gap-4 px-4 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 max-[450px]:grid-cols-1';
|
||||
|
||||
// Module-scoped so the position outlives FeedView while a publication is open.
|
||||
// It is only restored onto the same entries it was saved from.
|
||||
const savedScrollTops = new Map<string, { entryKeys: string; scrollTop: number }>();
|
||||
|
||||
interface PublicationsGridProps {
|
||||
publications: OPDSPublication[];
|
||||
scrollKey?: string;
|
||||
itemContent: (index: number) => ReactNode;
|
||||
}
|
||||
|
||||
function PublicationsGrid({ publications, scrollKey, itemContent }: PublicationsGridProps) {
|
||||
const grid = useRef<VirtuosoGridHandle>(null);
|
||||
const entryKeys = useMemo(
|
||||
() => publications.map((pub) => pub.metadata.id ?? pub.metadata.title ?? '').join('\n'),
|
||||
[publications],
|
||||
);
|
||||
const [restoreTop] = useState(() => {
|
||||
const saved = scrollKey === undefined ? undefined : savedScrollTops.get(scrollKey);
|
||||
return saved?.entryKeys === entryKeys ? saved.scrollTop : 0;
|
||||
});
|
||||
// Tracking starts once the saved offset is applied, and stops on unmount:
|
||||
// removing the scroller from the DOM fires a last scroll at offset 0, and the
|
||||
// grid reports 0 before it has laid out, neither of which is a real position.
|
||||
const latest = useRef({ scrollKey, entryKeys, tracking: false });
|
||||
useLayoutEffect(() => {
|
||||
latest.current.scrollKey = scrollKey;
|
||||
latest.current.entryKeys = entryKeys;
|
||||
});
|
||||
useLayoutEffect(() => {
|
||||
const current = latest.current;
|
||||
return () => {
|
||||
current.tracking = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// VirtuosoGrid cannot restore a snapshot onto a list it has not laid out yet,
|
||||
// so the offset is applied once the first items are measured.
|
||||
const handleReadyStateChanged = useCallback(
|
||||
(ready: boolean) => {
|
||||
if (!ready || latest.current.tracking) return;
|
||||
if (restoreTop > 0) grid.current?.scrollTo({ top: restoreTop });
|
||||
latest.current.tracking = true;
|
||||
},
|
||||
[restoreTop],
|
||||
);
|
||||
|
||||
const handleStateChanged = useCallback((state: GridStateSnapshot) => {
|
||||
const { scrollKey, entryKeys, tracking } = latest.current;
|
||||
if (tracking && scrollKey !== undefined) {
|
||||
savedScrollTops.set(scrollKey, { entryKeys, scrollTop: state.scrollTop });
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<VirtuosoGrid
|
||||
ref={grid}
|
||||
style={{ height: '100%' }}
|
||||
totalCount={publications.length}
|
||||
listClassName={gridClassName}
|
||||
itemContent={itemContent}
|
||||
readyStateChanged={handleReadyStateChanged}
|
||||
stateChanged={handleStateChanged}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function FeedView({
|
||||
feed,
|
||||
baseURL,
|
||||
|
|
@ -33,6 +101,7 @@ export function FeedView({
|
|||
onPublicationSelect,
|
||||
onGenerateCachedImageUrl,
|
||||
onAddCatalog,
|
||||
scrollKey,
|
||||
}: FeedViewProps) {
|
||||
const _ = useTranslation();
|
||||
const linksByRel = useMemo(() => groupByArray(feed.links, (link) => link.rel), [feed.links]);
|
||||
|
|
@ -167,10 +236,10 @@ export function FeedView({
|
|||
{/* Publications Grid - Takes remaining space */}
|
||||
{feed.publications && feed.publications.length > 0 && (
|
||||
<section className='opds-publications min-h-0 flex-1'>
|
||||
<VirtuosoGrid
|
||||
style={{ height: '100%' }}
|
||||
totalCount={feed.publications.length}
|
||||
listClassName={gridClassName}
|
||||
<PublicationsGrid
|
||||
key={scrollKey}
|
||||
publications={feed.publications}
|
||||
scrollKey={scrollKey}
|
||||
itemContent={itemContent}
|
||||
/>
|
||||
</section>
|
||||
|
|
|
|||
|
|
@ -1191,6 +1191,7 @@ export default function BrowserPage() {
|
|||
onGenerateCachedImageUrl={handleGenerateCachedImageUrl}
|
||||
isOPDSCatalog={isOPDSCatalog}
|
||||
onAddCatalog={handleOpenAddCatalog}
|
||||
scrollKey={state.currentURL}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue