From 3c362799b5b2b0b4808475b648ef2b44d055caf5 Mon Sep 17 00:00:00 2001 From: lrnselfreliance <33263708+lrnselfreliance@users.noreply.github.com> Date: Thu, 8 Oct 2026 18:19:51 -0600 Subject: [PATCH] Resume EPUBs and comic books where the reader left off (#798) * Resume EPUBs and comic books where the reader left off The EPUB viewer (epub.html) accepts `?cfi=` and posts its location and progress to the page that embeds it on every page turn. Progress comes from the chapter and the page within it, rather than book.locations.generate(), which stalls a Raspberry Pi on a large book. A search result's `loc` still wins over the saved position. The comic viewer opens at the saved page and saves each page shown. Both resume on the doc page and in the file preview. The resume point is decided once per opened file, so saves made while reading do not change the EPUB viewer's URL and reload it. The doc page tracks only the FileGroup's primary file; another format beside it is not tracked. Co-Authored-By: Claude Opus 5.5 * EPUB/comic progress: never save a place the server would discard The server treats a position at the start (the cover, under 1%) as not started, and replaces the saved place with progress 0. Both viewers reported the place they opened on, so opening a finished book un-finished it, and peeking at the cover erased the reader's page. - The comic viewer does not save the page it opens on, nor the cover; a peek at the cover keeps the last page saved. - The EPUB viewer posts nothing at the start of the book. - Progress before the end is kept between 1% and 94% (resumableProgress), so early pages of a long book and the last pages before the end keep their position. Only the last page (comics) or the end (EPUB) is finished. - Non-finite EPUB progress is ignored. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- app/public/epub/epub.html | 31 ++++++- app/src/components/CbzViewer.js | 28 +++++- app/src/components/CbzViewer.test.js | 84 ++++++++++++++++++ app/src/components/Docs.js | 29 ++++-- app/src/components/Docs.test.js | 11 ++- app/src/components/FilePreview.js | 25 ++++-- app/src/hooks/useFileProgress.js | 81 +++++++++++++++++ app/src/hooks/useFileProgress.test.js | 122 +++++++++++++++++++++++++- 8 files changed, 393 insertions(+), 18 deletions(-) create mode 100644 app/src/components/CbzViewer.test.js diff --git a/app/public/epub/epub.html b/app/public/epub/epub.html index 3a1ab60e..73f1289a 100644 --- a/app/public/epub/epub.html +++ b/app/public/epub/epub.html @@ -242,6 +242,8 @@ either expressed or implied, of the FreeBSD Project. --> // Optional search term passed in from a search-result deep link. If present we'll // search the spine item at `loc` and jump to + highlight the first match. let searchQuery = (params && params.get("q")) ? params.get("q") : null; + // Where the reader left off (an EPUB CFI). A search result's `loc` wins over it. + let startCfi = (params && params.get("cfi")) ? params.get("cfi") : null; let book = ePub(url); let rendition = book.renderTo("viewer", { @@ -250,7 +252,33 @@ either expressed or implied, of the FreeBSD Project. --> height: "100%" }); - rendition.display(currentSectionIndex); + rendition.display(currentSectionIndex !== undefined ? currentSectionIndex : (startCfi || undefined)); + + // How far through the book `location` is, from its chapter and its page within that chapter. Cheaper + // than `book.locations.generate()`, which stalls a Raspberry Pi on a large book. + function readingProgress(location) { + if (location.atEnd) { + return 1; + } + const start = location.start; + const sections = book.spine.length || 1; + const displayed = start.displayed || {page: 1, total: 1}; + const withinSection = (displayed.page - 1) / Math.max(displayed.total, 1); + return Math.min((start.index + withinSection) / sections, 1); + } + + // Tell the WROLPi page that embeds this viewer where the reader is, so it can save their place. Nothing is + // posted at the start of the book: that is where a finished book opens, and saving it would un-finish it. + function postLocation(location) { + if (window.parent === window || !location || !location.start || location.atStart) { + return; + } + window.parent.postMessage({ + type: "wrolpi:epub-location", + cfi: location.start.cfi, + progress: readingProgress(location), + }, window.location.origin); + } // --- In-book search --------------------------------------------------- // State is module-level so the toolbar buttons can drive it. `hits` is the @@ -516,6 +544,7 @@ either expressed or implied, of the FreeBSD Project. --> prev.style.visibility = "visible"; } + postLocation(location); }); rendition.on("layout", function (layout) { diff --git a/app/src/components/CbzViewer.js b/app/src/components/CbzViewer.js index 9e3feaa4..3b3da07d 100644 --- a/app/src/components/CbzViewer.js +++ b/app/src/components/CbzViewer.js @@ -3,6 +3,7 @@ import {IconArrowLeft, IconArrowRight} from '@tabler/icons-react'; import {getArchiveContents, getArchiveMemberUrl} from '../api'; import {IconButton, Label, Loading, Message} from './ui'; import {useLocalStorage} from './Common'; +import {usePageProgress} from '../hooks/useFileProgress'; const IMAGE_EXTENSIONS = /\.(jpe?g|png|gif|webp|bmp|tiff?)$/i; @@ -22,9 +23,20 @@ function flattenEntries(entries, prefix = '') { return paths; } -export function CbzViewer({path}) { +/** + * @param path The comic book file. + * @param progressPath The FileGroup's primary path, to resume and save the reader's page; omit to not track it. + * @param fileGroup The FileGroup JSON, which holds the saved page. + */ +export function CbzViewer({path, progressPath = null, fileGroup = null}) { const [pages, setPages] = useState(null); const [currentPage, setCurrentPage] = useState(0); + const {initialPage, onPageChange} = usePageProgress(progressPath, fileGroup, {enabled: !!progressPath}); + // Read when the pages load; a later save must not move the reader. + const initialPageRef = useRef(initialPage); + initialPageRef.current = initialPage; + // The page shown on opening is where the reader already is (or the cover of a finished comic); it is not saved. + const justOpenedRef = useRef(true); const [rtl, setRtl] = useLocalStorage('cbzViewerRtl', false); const [fullscreen, setFullscreen] = useState(false); const [error, setError] = useState(null); @@ -41,8 +53,9 @@ export function CbzViewer({path}) { .filter(name => IMAGE_EXTENSIONS.test(name)) .sort(); const urls = images.map(member => getArchiveMemberUrl(path, member)); + justOpenedRef.current = true; setPages(urls); - setCurrentPage(0); + setCurrentPage(Math.min(initialPageRef.current, Math.max(urls.length - 1, 0))); } catch (e) { setError(e.message || 'Could not read archive contents.'); } @@ -50,6 +63,17 @@ export function CbzViewer({path}) { load(); }, [path]); + useEffect(() => { + if (!pages || pages.length === 0) { + return; + } + if (justOpenedRef.current) { + justOpenedRef.current = false; + return; + } + onPageChange(currentPage, pages.length); + }, [currentPage, pages, onPageChange]); + const goNext = useCallback(() => { setCurrentPage(p => Math.min(p + 1, (pages?.length || 1) - 1)); }, [pages]); diff --git a/app/src/components/CbzViewer.test.js b/app/src/components/CbzViewer.test.js new file mode 100644 index 00000000..61ba6576 --- /dev/null +++ b/app/src/components/CbzViewer.test.js @@ -0,0 +1,84 @@ +import React from 'react'; +import {act, fireEvent, screen} from '@testing-library/react'; +import {renderWithProviders} from '../test-utils'; +import {CbzViewer} from './CbzViewer'; +import {getArchiveContents} from '../api'; + +jest.mock('../api', () => ({ + ...jest.requireActual('../api'), + getArchiveContents: jest.fn(), + getArchiveMemberUrl: (path, member) => `/member/${member}`, +})); + +const PATH = 'comics/issue.cbz'; +const PAGES = ['01.jpg', '02.jpg', '03.jpg', '04.jpg']; + +const {fetch: realFetch} = global; +const realSendBeacon = navigator.sendBeacon; + +beforeEach(() => { + window.sessionStorage.clear(); + getArchiveContents.mockResolvedValue({entries: PAGES.map(name => ({name, path: name, is_dir: false}))}); + navigator.sendBeacon = jest.fn(() => false); + global.fetch = jest.fn(() => Promise.resolve({ok: true})); +}); + +afterEach(() => { + global.fetch = realFetch; + navigator.sendBeacon = realSendBeacon; +}); + +const saves = () => global.fetch.mock.calls.map(([, init]) => JSON.parse(init.body)); + +describe('CbzViewer progress', () => { + test('opens at the saved page, and saves the page the reader leaves on', async () => { + const fileGroup = {progress: 0.75, position: {kind: 'page', page: 2, updated_at: 1000}}; + const {unmount} = renderWithProviders( + ); + + expect(await screen.findByText('3 / 4')).toBeInTheDocument(); + expect(screen.getByAltText('Page 3')).toHaveAttribute('src', '/member/03.jpg'); + + fireEvent.click(screen.getByLabelText('Next page')); + expect(screen.getByText('4 / 4')).toBeInTheDocument(); + + unmount(); + expect(saves()).toEqual([expect.objectContaining({ + file: PATH, progress: 1, final: true, position: expect.objectContaining({kind: 'page', page: 3}), + })]); + }); + + test('a saved page past the end opens the last page', async () => { + const fileGroup = {progress: 0.5, position: {kind: 'page', page: 40, updated_at: 1000}}; + renderWithProviders(); + expect(await screen.findByText('4 / 4')).toBeInTheDocument(); + }); + + test('without a progress path it opens at the first page and saves nothing', async () => { + const fileGroup = {progress: 0.75, position: {kind: 'page', page: 2, updated_at: 1000}}; + const {unmount} = renderWithProviders(); + expect(await screen.findByText('1 / 4')).toBeInTheDocument(); + await act(async () => fireEvent.click(screen.getByLabelText('Next page'))); + unmount(); + expect(saves()).toEqual([]); + }); + + test('opening a comic saves nothing, so a finished comic stays finished', async () => { + const fileGroup = {progress: 1, position: null, viewed: new Date(9000).toISOString()}; + const {unmount} = renderWithProviders(); + expect(await screen.findByText('1 / 4')).toBeInTheDocument(); + unmount(); + expect(saves()).toEqual([]); + }); + + test('peeking at the cover keeps the reader\'s place', async () => { + const fileGroup = {progress: 0.75, position: {kind: 'page', page: 2, updated_at: 1000}}; + const {unmount} = renderWithProviders(); + expect(await screen.findByText('3 / 4')).toBeInTheDocument(); + fireEvent.click(screen.getByLabelText('Previous page')); + fireEvent.click(screen.getByLabelText('Previous page')); + expect(screen.getByText('1 / 4')).toBeInTheDocument(); + unmount(); + expect(saves()).toEqual([expect.objectContaining({position: expect.objectContaining({page: 1})})]); + }); +}); diff --git a/app/src/components/Docs.js b/app/src/components/Docs.js index f63de41f..f0331929 100644 --- a/app/src/components/Docs.js +++ b/app/src/components/Docs.js @@ -38,6 +38,7 @@ import {toast} from "./ui"; import {CollectionTable} from "./collections/CollectionTable"; import {AddToPlaylistButton} from "./AddToPlaylist"; import {CbzViewer} from "./CbzViewer"; +import {useEpubProgress} from "../hooks/useFileProgress"; import _ from "lodash"; function DocsPage() { @@ -165,6 +166,23 @@ function DocsPage() { ; } +/** + * The embedded viewer (the EPUB viewer, or the browser's PDF viewer). An EPUB opens where the user left off, + * unless a search result says where (`deepLinked`), and saves their place as they read. + * + * @param epubProgressPath The FileGroup's primary path when an EPUB is shown and tracked, otherwise null. + */ +function DocViewerFrame({url, epubProgressPath, fileGroup, deepLinked, title}) { + const {iframeRef, resumeCfi} = useEpubProgress(epubProgressPath, fileGroup, {enabled: !!epubProgressPath}); + const src = resumeCfi && !deepLinked ? `${url}&cfi=${encodeURIComponent(resumeCfi)}` : url; + return