From 511f81cfc7db86c6e4b49070c06ab1c981cc6ce0 Mon Sep 17 00:00:00 2001 From: Roland Date: Thu, 8 Oct 2026 17:50:58 -0600 Subject: [PATCH] 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 --- app/public/epub/epub.html | 30 +++++++- app/src/components/CbzViewer.js | 20 ++++- app/src/components/CbzViewer.test.js | 65 +++++++++++++++++ app/src/components/Docs.js | 29 ++++++-- app/src/components/Docs.test.js | 11 ++- app/src/components/FilePreview.js | 25 +++++-- app/src/hooks/useFileProgress.js | 65 +++++++++++++++++ app/src/hooks/useFileProgress.test.js | 101 +++++++++++++++++++++++++- 8 files changed, 328 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..bf7c1012 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,32 @@ 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. + function postLocation(location) { + if (window.parent === window || !location || !location.start) { + 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 +543,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..3f526751 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,18 @@ 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; const [rtl, setRtl] = useLocalStorage('cbzViewerRtl', false); const [fullscreen, setFullscreen] = useState(false); const [error, setError] = useState(null); @@ -42,7 +52,7 @@ export function CbzViewer({path}) { .sort(); const urls = images.map(member => getArchiveMemberUrl(path, member)); 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 +60,12 @@ export function CbzViewer({path}) { load(); }, [path]); + useEffect(() => { + if (pages && pages.length > 0) { + 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..faedf83b --- /dev/null +++ b/app/src/components/CbzViewer.test.js @@ -0,0 +1,65 @@ +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([]); + }); +}); 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