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 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-10-08 17:50:58 -06:00
parent 1ad451cddf
commit 511f81cfc7
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
8 changed files with 328 additions and 18 deletions

View file

@ -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) {

View file

@ -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]);

View file

@ -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(
<CbzViewer path={PATH} progressPath={PATH} fileGroup={fileGroup}/>);
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(<CbzViewer path={PATH} progressPath={PATH} fileGroup={fileGroup}/>);
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(<CbzViewer path={PATH} fileGroup={fileGroup}/>);
expect(await screen.findByText('1 / 4')).toBeInTheDocument();
await act(async () => fireEvent.click(screen.getByLabelText('Next page')));
unmount();
expect(saves()).toEqual([]);
});
});

View file

@ -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 <iframe
ref={iframeRef}
src={src}
title={title}
style={{width: '100%', height: '80vh', border: '1px solid var(--border)'}}
/>
}
function DocPage() {
const {fileGroupId} = useParams();
const navigate = useNavigate();
@ -245,6 +263,8 @@ function DocPage() {
? `/media/${encodeMediaPath(activePath)}${pageParam ? `#page=${encodeURIComponent(pageParam)}` : ''}`
: null;
const embedUrl = isEpub ? viewerUrl : pdfSrc;
// Progress belongs to the FileGroup; another format of the same book (a PDF beside the EPUB) is not tracked.
const trackedPath = String(activePath) === String(docFile.primary_path) ? docFile.primary_path : null;
const handleDelete = async (force = false) => {
if (doc && doc.id) {
@ -354,7 +374,7 @@ function DocPage() {
return <>
<div className='wrolpi-button-row'><BackButton/></div>
{isCbz && activePath && <CbzViewer path={activePath}/>}
{isCbz && activePath && <CbzViewer path={activePath} progressPath={trackedPath} fileGroup={docFile}/>}
{canEmbed && embedUrl && !isCbz && <div style={{marginBottom: '1em'}}>
{/*
@ -364,11 +384,8 @@ function DocPage() {
* re-gates rather than inheriting the last one's reveal.
*/}
<MediaGate key={activePath} gated={isPdf && mediaFilterEnabled}>
<iframe
src={embedUrl}
title={docFile.title || docFile.name}
style={{width: '100%', height: '80vh', border: '1px solid var(--border)'}}
/>
<DocViewerFrame url={embedUrl} epubProgressPath={isEpub ? trackedPath : null} fileGroup={docFile}
deepLinked={!!locParam} title={docFile.title || docFile.name}/>
</MediaGate>
</div>}

View file

@ -19,10 +19,15 @@ const source = fs.readFileSync(path.join(__dirname, 'Docs.js'), 'utf8');
describe('DocPage embed gating (source contract)', () => {
it('wraps the embedded viewer in a MediaGate', () => {
// The iframe must not be reachable without passing through the gate.
const embed = source.match(/<MediaGate[^>]*>\s*<iframe/);
// The iframe must not be reachable without passing through the gate. The gate's only child is the
// viewer frame, and the frame is just the iframe.
const embed = source.match(/<MediaGate[^>]*>\s*<DocViewerFrame/);
expect(embed).not.toBeNull();
const frame = source.match(/function DocViewerFrame[\s\S]*?\n}\n/);
expect(frame).not.toBeNull();
expect(frame[0]).toMatch(/return <iframe/);
expect(source.match(/<iframe/g)).toHaveLength(1);
});
it('gates on the live filter state, not on the theme name', () => {

View file

@ -8,7 +8,7 @@ import {CbzViewer} from "./CbzViewer";
import {StlViewer} from "react-stl-viewer";
import {Button, ButtonGroup, Header, Icon, IconButton, MediaGate, Menu, Modal, toast} from "./ui";
import {useOneQuery} from "../hooks/customHooks";
import {useMediaProgress} from "../hooks/useFileProgress";
import {useEpubProgress, useMediaProgress} from "../hooks/useFileProgress";
import {ShareButton} from "./Share";
import {AddToPlaylistButton} from "./AddToPlaylist";
import {pathDirectory} from "./FileBrowser";
@ -102,7 +102,7 @@ function getEpubViewerURL(previewFile) {
* A component rather than part of `getIframePreviewModal` because it reads the theme: the
* modal builders are plain functions called from an event handler, where hooks cannot run.
*/
export function IframePreview({url, gatePdf}) {
export function IframePreview({url, gatePdf, iframeRef}) {
const {isDark, mediaFilterEnabled} = React.useContext(ThemeContext);
/*
@ -118,7 +118,7 @@ export function IframePreview({url, gatePdf}) {
*/
return <MediaGate key={url} gated={!!gatePdf && !!mediaFilterEnabled}>
<div className='preview-fit'>
<iframe title='textModal' src={url}
<iframe title='textModal' src={url} ref={iframeRef}
style={{
height: '100%', width: '100%', border: 'none',
// A same-origin document has no styles of its own; it renders with the
@ -139,6 +139,19 @@ function getIframePreviewModal(previewFile, url, {gatePdf = false} = {}) {
</Modal.Content>
}
/** The EPUB viewer, opened where the user left off. */
function EpubPreview({previewFile}) {
const path = previewFile.primary_path ?? previewFile.path;
const {iframeRef, resumeCfi} = useEpubProgress(path, previewFile);
let url = getEpubViewerURL(previewFile);
if (resumeCfi) {
url = `${url}&cfi=${encodeURIComponent(resumeCfi)}`;
}
return <Modal.Content>
<IframePreview url={url} iframeRef={iframeRef}/>
</Modal.Content>
}
function getImagePreviewModal(previewFile) {
const path = previewFile.primary_path ?? previewFile.path;
const url = getMediaPathURL(previewFile);
@ -627,7 +640,7 @@ export function FilePreviewProvider({children}) {
setModalContent(getAudioPreviewModal(previewFile), url, downloadURL, path, taggable);
} else if (mimetype.startsWith('application/epub')) {
const viewerURL = getEpubViewerURL(previewFile);
setModalContent(getIframePreviewModal(previewFile, viewerURL), viewerURL, downloadURL, path, taggable);
setModalContent(<EpubPreview previewFile={previewFile}/>, viewerURL, downloadURL, path, taggable);
} else if (mimetype.startsWith('application/pdf')) {
setModalContent(getIframePreviewModal(previewFile, null, {gatePdf: true}), url, downloadURL, path, taggable);
} else if (mimetype.startsWith('image/')) {
@ -649,7 +662,9 @@ export function FilePreviewProvider({children}) {
<OpenInSlicerButton previewFile={previewFile}/>);
} else if (mimetype.includes('cbz') || mimetype.includes('cbr') || mimetype.includes('comicbook+zip') || mimetype.includes('comicbook-rar')
|| lowerPath.endsWith('.cbz') || lowerPath.endsWith('.cbr') || lowerPath.endsWith('.cbt') || lowerPath.endsWith('.cb7')) {
setModalContent(<Modal.Content><CbzViewer path={path}/></Modal.Content>, null, downloadURL, path, taggable);
setModalContent(<Modal.Content>
<CbzViewer path={path} progressPath={path} fileGroup={previewFile}/>
</Modal.Content>, null, downloadURL, path, taggable);
} else if (isSupportedArchive(mimetype, lowerPath)) {
setModalContent(<ArchivePreviewContent previewFile={previewFile}/>, null, downloadURL, path, taggable);
} else {

View file

@ -198,3 +198,68 @@ export function useMediaProgress(path, fileGroup, {startSeconds = null, enabled
return {onLoadedMetadata, onTimeUpdate, onPause, onEnded};
}
/**
* Where to resume `path`, decided once when it is opened. Saves made while it is open do not move it,
* so a viewer whose URL holds the start (the EPUB viewer) is not reloaded as the user reads.
*/
export function useResumePosition(path, fileGroup) {
const resumeRef = React.useRef({path: null, position: null});
if (path && fileGroup && resumeRef.current.path !== path) {
resumeRef.current = {path, position: getResumePosition(path, fileGroup)};
}
return path && resumeRef.current.path === path ? resumeRef.current.position : null;
}
/**
* Track and resume the EPUB viewer (public/epub/epub.html), which posts its location to this window.
*
* @returns {{iframeRef, resumeCfi}} Put `iframeRef` on the viewer's <iframe>, and pass `resumeCfi` to it as `cfi`.
*/
export function useEpubProgress(path, fileGroup, {enabled = true} = {}) {
const trackedPath = enabled ? path : null;
const {report} = useFileProgress(trackedPath);
const resume = useResumePosition(trackedPath, fileGroup);
const iframeRef = React.useRef(null);
React.useEffect(() => {
if (!trackedPath) {
return;
}
const onMessage = (event) => {
// Only our own viewer, in this iframe.
if (event.origin !== window.location.origin || !iframeRef.current
|| event.source !== iframeRef.current.contentWindow) {
return;
}
const {type, cfi, progress} = event.data || {};
if (type !== 'wrolpi:epub-location' || typeof cfi !== 'string' || typeof progress !== 'number') {
return;
}
report({progress, position: {kind: 'epub', cfi}});
};
window.addEventListener('message', onMessage);
return () => window.removeEventListener('message', onMessage);
}, [trackedPath, report]);
return {iframeRef, resumeCfi: resume && resume.kind === 'epub' ? resume.cfi : null};
}
/**
* Track and resume a paged viewer (comic books).
*
* @returns {{initialPage, onPageChange}} The 0-based page to open at, and a callback for each page shown.
*/
export function usePageProgress(path, fileGroup, {enabled = true} = {}) {
const trackedPath = enabled ? path : null;
const {report} = useFileProgress(trackedPath);
const resume = useResumePosition(trackedPath, fileGroup);
const onPageChange = React.useCallback((page, pageCount) => {
if (pageCount > 0) {
report({progress: (page + 1) / pageCount, position: {kind: 'page', page}});
}
}, [report]);
return {initialPage: resume && resume.kind === 'page' ? resume.page : 0, onPageChange};
}

View file

@ -1,6 +1,8 @@
import React from 'react';
import {act, render, renderHook} from '@testing-library/react';
import {getResumePosition, useFileProgress, useMediaProgress} from './useFileProgress';
import {
getResumePosition, useEpubProgress, useFileProgress, useMediaProgress, usePageProgress, useResumePosition,
} from './useFileProgress';
import {ViewProgress} from '../components/Common';
const PATH = 'videos/movie.mp4';
@ -210,3 +212,100 @@ describe('ViewProgress', () => {
expect(bar.firstChild).toHaveStyle({width: '40%'});
});
});
describe('useResumePosition', () => {
test('is decided once per file, so later saves do not move the viewer', () => {
const fileGroup = {progress: 0.5, position: {kind: 'epub', cfi: 'epubcfi(/6/4)', updated_at: 1000}};
const {result, rerender} = renderHook(({path, fileGroup}) => useResumePosition(path, fileGroup),
{initialProps: {path: PATH, fileGroup}});
expect(result.current.cfi).toBe('epubcfi(/6/4)');
// The user reads on; this tab saves a newer position.
window.sessionStorage.setItem(CACHE_KEY, JSON.stringify(
{progress: 0.6, position: {kind: 'epub', cfi: 'epubcfi(/6/8)'}, updated_at: 2000}));
rerender({path: PATH, fileGroup: {...fileGroup}});
expect(result.current.cfi).toBe('epubcfi(/6/4)');
// Another file is decided afresh.
rerender({path: 'books/other.epub', fileGroup: {progress: 0.3, position: {kind: 'epub', cfi: 'epubcfi(/6/2)'}}});
expect(result.current.cfi).toBe('epubcfi(/6/2)');
});
});
describe('useEpubProgress', () => {
const fileGroup = {progress: 0.5, position: {kind: 'epub', cfi: 'epubcfi(/6/4)', updated_at: 1000}};
/** Render the hook with an iframe whose window posts the messages. */
const renderEpub = (options) => {
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const hook = renderHook(() => {
const result = useEpubProgress(PATH, fileGroup, options);
result.iframeRef.current = iframe;
return result;
});
const post = (data, {source = iframe.contentWindow, origin = window.location.origin} = {}) =>
act(() => window.dispatchEvent(new MessageEvent('message', {data, source, origin})));
return {...hook, post};
};
test('resumes at the saved CFI', () => {
const {result} = renderEpub();
expect(result.current.resumeCfi).toBe('epubcfi(/6/4)');
});
test('saves where the viewer says the reader is', () => {
const {post, unmount} = renderEpub();
post({type: 'wrolpi:epub-location', cfi: 'epubcfi(/6/10)', progress: 0.45});
unmount();
expect(sent()).toEqual([expect.objectContaining({
file: PATH, progress: 0.45, final: true,
position: {kind: 'epub', cfi: 'epubcfi(/6/10)', updated_at: expect.any(Number)},
})]);
});
test.each([
['another window', {source: window}],
['another origin', {origin: 'https://example.com'}],
])('ignores a message from %s', (_, from) => {
const {post, unmount} = renderEpub();
post({type: 'wrolpi:epub-location', cfi: 'epubcfi(/6/10)', progress: 0.45}, from);
unmount();
expect(sent()).toEqual([]);
});
test('ignores a malformed message', () => {
const {post, unmount} = renderEpub();
post({type: 'wrolpi:epub-location', cfi: 42, progress: 0.45});
post({type: 'something-else', cfi: 'epubcfi(/6/10)', progress: 0.45});
unmount();
expect(sent()).toEqual([]);
});
test('does nothing when not enabled', () => {
const {result, post, unmount} = renderEpub({enabled: false});
expect(result.current.resumeCfi).toBeNull();
post({type: 'wrolpi:epub-location', cfi: 'epubcfi(/6/10)', progress: 0.45});
unmount();
expect(sent()).toEqual([]);
});
});
describe('usePageProgress', () => {
test('opens at the saved page and saves each page shown', () => {
const fileGroup = {progress: 0.3, position: {kind: 'page', page: 5, updated_at: 1000}};
const {result, unmount} = renderHook(() => usePageProgress(PATH, fileGroup));
expect(result.current.initialPage).toBe(5);
act(() => result.current.onPageChange(9, 20));
unmount();
expect(sent()).toEqual([expect.objectContaining({
progress: 0.5, final: true, position: expect.objectContaining({kind: 'page', page: 9}),
})]);
});
test('a new comic opens at the first page', () => {
const {result} = renderHook(() => usePageProgress(PATH, {progress: null, position: null}));
expect(result.current.initialPage).toBe(0);
});
});