mirror of
https://github.com/readest/readest.git
synced 2026-11-29 19:02:28 +00:00
fix(library): keep the shelf scroll position after opening a book (#6642)
* fix(library): keep the shelf scroll position after opening a book Opening a book navigates to the reader and unmounts the library, so coming back always started the list or grid at the top. The stream now saves the virtual list's state (measured row sizes + scroll offset) when scrolling stops, keyed by the library URL, and restores it when it mounts again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(library): save the shelf position on unmount and only restore onto the same rows Review follow-up. Save the Virtuoso snapshot in a layout cleanup when the stream unmounts, so a book tapped before a scroll settles still records the position, and keep each snapshot with the row keys that produced it: the measured sizes are per row index, so they are only restored onto the same rows. The last measured width seeds the first render, so a remounted grid starts with the column count it had when the snapshot was taken. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: bump foliate-js to 08db610 (readest/foliate-js#125) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2055027f57
commit
d69176a7ad
4 changed files with 102 additions and 4 deletions
|
|
@ -560,6 +560,56 @@ describe('mixed bookshelf stream in Chromium', () => {
|
|||
});
|
||||
}
|
||||
}
|
||||
it('returns to the same place after the library remounts (opening a book and coming back)', async () => {
|
||||
const shelves = (count: number) => [
|
||||
section('reading', 'carousel', 12),
|
||||
section('books', 'list', count),
|
||||
section('more', 'grid', 60),
|
||||
];
|
||||
const stream = (count = 300) => (
|
||||
<div style={{ width: 900, height: 600 }}>
|
||||
<BookshelfStream
|
||||
sections={shelves(count)}
|
||||
autoColumns
|
||||
fixedColumns={3}
|
||||
renderItem={renderItem}
|
||||
scrollKey='group=a'
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
const scrollerOf = (root: HTMLElement) =>
|
||||
root.querySelector<HTMLElement>('[data-virtuoso-scroller]')!;
|
||||
const firstVisible = (root: HTMLElement) => {
|
||||
const top = scrollerOf(root).getBoundingClientRect().top;
|
||||
return Array.from(root.querySelectorAll<HTMLElement>('[data-book]')).find(
|
||||
(el) => el.getBoundingClientRect().bottom > top,
|
||||
);
|
||||
};
|
||||
const visibleId = (root: HTMLElement) => {
|
||||
const el = firstVisible(root);
|
||||
return el && `${el.dataset['section']}:${el.dataset['book']}`;
|
||||
};
|
||||
const first = render(stream());
|
||||
const scroller = scrollerOf(first.container);
|
||||
await waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(8000));
|
||||
scroller.scrollTop = 6000;
|
||||
fireEvent.scroll(scroller);
|
||||
await waitFor(() => expect(visibleId(first.container)).toMatch(/^books:\d{2,}$/));
|
||||
// Unmount right away, as when a book is tapped before the scroll settles.
|
||||
const scrollTop = scroller.scrollTop;
|
||||
const book = visibleId(first.container);
|
||||
first.unmount();
|
||||
|
||||
const second = render(stream());
|
||||
await waitFor(() => expect(scrollerOf(second.container).scrollTop).toBe(scrollTop));
|
||||
expect(visibleId(second.container)).toBe(book);
|
||||
second.unmount();
|
||||
|
||||
// Different rows: the saved row sizes no longer apply, so start at the top.
|
||||
const changed = render(stream(250));
|
||||
await waitFor(() => expect(visibleId(changed.container)).toBe('reading:0'));
|
||||
expect(scrollerOf(changed.container).scrollTop).toBe(0);
|
||||
});
|
||||
it('keeps very large carousels horizontally virtualized and scrollable', async () => {
|
||||
document.documentElement.setAttribute('data-eink', 'true');
|
||||
const { container, getByRole } = render(
|
||||
|
|
|
|||
|
|
@ -985,6 +985,7 @@ const Bookshelf: React.FC<BookshelfProps> = ({
|
|||
// WebKit when a search was cleared.
|
||||
<div className='min-h-0 flex-1'>
|
||||
<BookshelfStream
|
||||
scrollKey={searchParams?.toString() ?? ''}
|
||||
pageNavigation={!!settings.globalViewSettings?.isEink}
|
||||
hidePageButtons={settings.hideBookshelfPageButtons}
|
||||
navigationBottomInset={
|
||||
|
|
|
|||
|
|
@ -1,8 +1,22 @@
|
|||
import clsx from 'clsx';
|
||||
import { LibraryPageDurationsContext } from '@/hooks/useMedianPageDurationSecs';
|
||||
import { HideBookCoversContext } from '@/components/BookCover';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { Virtuoso, type Components, type ItemProps } from 'react-virtuoso';
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import {
|
||||
Virtuoso,
|
||||
type Components,
|
||||
type ItemProps,
|
||||
type StateSnapshot,
|
||||
type VirtuosoHandle,
|
||||
} from 'react-virtuoso';
|
||||
import { MdChevronLeft, MdChevronRight } from 'react-icons/md';
|
||||
import type { Book, BooksGroup } from '@/types/book';
|
||||
import type { BookshelfDefinition } from '@/types/bookshelf';
|
||||
|
|
@ -34,7 +48,16 @@ interface StreamProps {
|
|||
/** Drop the e-ink Previous/Next buttons; keys still page. */
|
||||
hidePageButtons?: boolean;
|
||||
navigationBottomInset?: number;
|
||||
/** Identifies the shelf view; its scroll state survives remounts (open a book, come back). */
|
||||
scrollKey?: string;
|
||||
}
|
||||
// Module-scoped so the position outlives the library page while the reader is open.
|
||||
// Virtuoso's measured sizes are per row index, so a snapshot is kept with the
|
||||
// rows that produced it and only restored onto the same rows.
|
||||
const savedScrollStates = new Map<string, { rowKeys: string; state: StateSnapshot }>();
|
||||
// Seeds the first render after a remount, so the grid starts with the column
|
||||
// count (and rows) it had when the snapshot was taken.
|
||||
let lastStreamWidth = 0;
|
||||
type StreamRow = {
|
||||
key: string;
|
||||
section: ShelfSection;
|
||||
|
|
@ -267,10 +290,12 @@ export default function BookshelfStream({
|
|||
pageNavigation = false,
|
||||
hidePageButtons = false,
|
||||
navigationBottomInset = 0,
|
||||
scrollKey,
|
||||
}: StreamProps) {
|
||||
const _ = useTranslation();
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const [width, setWidth] = useState(0);
|
||||
const virtuoso = useRef<VirtuosoHandle>(null);
|
||||
const [width, setWidth] = useState(lastStreamWidth);
|
||||
const [height, setHeight] = useState(0);
|
||||
const [scroller, setScroller] = useState<HTMLElement | null>(null);
|
||||
const handleScrollerRef = useCallback(
|
||||
|
|
@ -287,6 +312,7 @@ export default function BookshelfStream({
|
|||
const element = root.current;
|
||||
if (!element) return;
|
||||
const measure = () => {
|
||||
lastStreamWidth = element.clientWidth;
|
||||
setWidth(element.clientWidth);
|
||||
setHeight(element.clientHeight);
|
||||
};
|
||||
|
|
@ -301,6 +327,25 @@ export default function BookshelfStream({
|
|||
() => buildBookshelfRows(sections, columns, includeImport),
|
||||
[sections, columns, includeImport],
|
||||
);
|
||||
const rowKeys = useMemo(() => rows.map((row) => row.key).join('\n'), [rows]);
|
||||
const [restoreState] = useState(() => {
|
||||
const saved = scrollKey === undefined ? undefined : savedScrollStates.get(scrollKey);
|
||||
return saved?.rowKeys === rowKeys ? saved.state : undefined;
|
||||
});
|
||||
const latest = useRef({ scrollKey, rowKeys });
|
||||
useLayoutEffect(() => {
|
||||
latest.current = { scrollKey, rowKeys };
|
||||
});
|
||||
// Save on unmount (opening a book leaves the library), even mid-scroll. A
|
||||
// layout cleanup runs before Virtuoso's own handle is torn down.
|
||||
useLayoutEffect(
|
||||
() => () => {
|
||||
const { scrollKey, rowKeys } = latest.current;
|
||||
if (scrollKey === undefined) return;
|
||||
virtuoso.current?.getState((state) => savedScrollStates.set(scrollKey, { rowKeys, state }));
|
||||
},
|
||||
[],
|
||||
);
|
||||
// Virtuoso mounts its footer before it has measured the viewport and placed
|
||||
// any row, which flashed the import action at the top of the page on every
|
||||
// library load. Hold it back until these rows are on screen (or there are
|
||||
|
|
@ -321,6 +366,8 @@ export default function BookshelfStream({
|
|||
{/* Hide native scrollbars before the deferred overlay initializes. */}
|
||||
<div className='min-h-0 flex-1' data-overlayscrollbars-initialize=''>
|
||||
<Virtuoso
|
||||
ref={virtuoso}
|
||||
restoreStateFrom={restoreState}
|
||||
style={scale !== 1 ? { overflowX: 'hidden' } : undefined}
|
||||
data={rows}
|
||||
overscan={pageNavigation ? Math.max(400, height) : 400}
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
Subproject commit bb2b1da7e350d30fc59736fdf203ccb8461daa41
|
||||
Subproject commit 08db61054bd5bc21f244c6ad128f103b6427b03c
|
||||
Loading…
Add table
Add a link
Reference in a new issue