Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(reading): preserve EPUB outline anchors

XZH95e913a78773
diff --git a/deeptutor/reading/extract.py b/deeptutor/reading/extract.py
index 28fe28e4b..e02b254ba 100644
--- a/deeptutor/reading/extract.py
+++ b/deeptutor/reading/extract.py
@@ -258,7 +258,14 @@ def _extract_epub(data: bytes, filename: str) -> Extraction:
for index, unit in enumerate(units, start=1)
)
outline = tuple(
- OutlineEntry(locator=row.locator, title=row.title, level=row.level) for row in navigation
+ OutlineEntry(
+ locator=row.locator,
+ title=row.title,
+ level=row.level,
+ source_href=row.source_href,
+ source_anchor=row.source_anchor,
+ )
+ for row in navigation
)
if not outline:
outline = tuple(
diff --git a/deeptutor/reading/models.py b/deeptutor/reading/models.py
index 9e2177074..f19fc453a 100644
--- a/deeptutor/reading/models.py
+++ b/deeptutor/reading/models.py
@@ -136,6 +136,8 @@ class OutlineEntry:
title: str
level: int = 1
synthesised: bool = False
+ source_href: str = ""
+ source_anchor: str = ""
def to_dict(self) -> dict[str, Any]:
return {
@@ -143,8 +145,21 @@ class OutlineEntry:
"title": self.title,
"level": self.level,
"synthesised": self.synthesised,
+ "source_href": self.source_href,
+ "source_anchor": self.source_anchor,
}
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> "OutlineEntry":
+ return cls(
+ locator=max(1, int(data["locator"])),
+ title=str(data.get("title") or ""),
+ level=max(1, int(data.get("level") or 1)),
+ synthesised=bool(data.get("synthesised")),
+ source_href=str(data.get("source_href") or ""),
+ source_anchor=str(data.get("source_anchor") or ""),
+ )
+
@dataclass(frozen=True, slots=True)
class UnitReference:
diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py
index bf1db9272..eab9cc713 100644
--- a/deeptutor/reading/store.py
+++ b/deeptutor/reading/store.py
@@ -919,16 +919,11 @@ class ReadingStore:
if not isinstance(row, dict):
continue
try:
- entries.append(
- OutlineEntry(
- locator=int(row["locator"]),
- title=str(row.get("title") or ""),
- level=max(1, int(row.get("level") or 1)),
- synthesised=bool(row.get("synthesised")),
- )
- )
+ entries.append(OutlineEntry.from_dict(row))
except (KeyError, TypeError, ValueError):
continue
+ if manifest.render_mode == "epub":
+ entries = self._upgrade_epub_outline(material_id, entries)
if manifest.render_mode == "pdf":
# Migrate legacy PDF imports in place at read time: older
# versions persisted one synthesised row per page. Returning
@@ -944,6 +939,61 @@ class ReadingStore:
)
return list(synthesise_outline(units))
+ def _upgrade_epub_outline(
+ self,
+ material_id: str,
+ entries: list[OutlineEntry],
+ ) -> list[OutlineEntry]:
+ """Restore publisher anchors in outlines written before they persisted.
+
+ Existing EPUB imports are content-addressed and idempotent, so their
+ extracted ``outline.json`` would otherwise keep the pre-anchor shape
+ forever. The raw package remains available; re-reading it once and
+ writing the enriched rows in place upgrades those books without
+ touching units, annotations, or reading positions.
+ """
+ if not entries or any(row.source_href for row in entries):
+ return entries
+ try:
+ raw_path = self.raw_path(material_id)
+ if raw_path is None:
+ return entries
+ from deeptutor.utils.document_extractor import (
+ DocumentExtractionError,
+ extract_epub_spine,
+ )
+
+ _, navigation = extract_epub_spine(raw_path.read_bytes(), raw_path.name)
+ if len(navigation) != len(entries) or any(
+ row.locator != entry.locator for row, entry in zip(navigation, entries, strict=True)
+ ):
+ return entries
+ upgraded = [
+ dataclass_replace(
+ entry,
+ locator=row.locator,
+ level=row.level,
+ source_href=row.source_href,
+ source_anchor=row.source_anchor,
+ )
+ for row, entry in zip(navigation, entries, strict=True)
+ ]
+ if upgraded == entries:
+ return entries
+ with self._locked(material_id):
+ _atomic_write(
+ self._dir(material_id) / OUTLINE_NAME,
+ json.dumps([entry.to_dict() for entry in upgraded], ensure_ascii=False),
+ )
+ return upgraded
+ except (OSError, ValueError, ReadingError, DocumentExtractionError):
+ logger.warning(
+ "Could not restore EPUB navigation anchors for %s",
+ material_id,
+ exc_info=True,
+ )
+ return entries
+
def iter_units(self, material_id: str) -> Iterator[tuple[int, str]]:
"""Stream every unit in order — for search and export."""
manifest = self.manifest(material_id)
diff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.py
index d2281b0c2..e31f7c3b8 100644
--- a/deeptutor/utils/document_extractor.py
+++ b/deeptutor/utils/document_extractor.py
@@ -191,6 +191,8 @@ class EpubOutlineItem:
locator: int
title: str
level: int = 1
+ source_href: str = ""
+ source_anchor: str = ""
def is_document_extension(filename: str) -> bool:
@@ -841,10 +843,15 @@ def _epub_package_navigation(
locator_by_member = {member: index for index, member in enumerate(spine_members, start=1)}
- def resolve_locator(href: str, base_member: str) -> int:
- path = unquote(href.split("#", 1)[0])
+ def resolve_target(href: str, base_member: str) -> tuple[int, str, str]:
+ raw_path, separator, raw_anchor = href.partition("#")
+ path = unquote(raw_path)
member = posixpath.normpath(posixpath.join(posixpath.dirname(base_member), path))
- return locator_by_member.get(member, 0)
+ return (
+ locator_by_member.get(member, 0),
+ member,
+ unquote(raw_anchor) if separator else "",
+ )
rows: list[EpubOutlineItem] = []
if nav_member:
@@ -875,9 +882,19 @@ def _epub_package_navigation(
)
href = str(link.get("href") or "") if link is not None else ""
title = _epub_element_text(link) if link is not None else ""
- locator = resolve_locator(href, nav_member) if href else 0
+ locator, source_href, source_anchor = (
+ resolve_target(href, nav_member) if href else (0, "", "")
+ )
if locator and title:
- rows.append(EpubOutlineItem(locator, title, max(1, level)))
+ rows.append(
+ EpubOutlineItem(
+ locator,
+ title,
+ max(1, level),
+ source_href,
+ source_anchor,
+ )
+ )
for item in child:
if _local_name(item.tag) == "ol":
walk_nav(item, level + 1)
@@ -905,9 +922,19 @@ def _epub_package_navigation(
)
title = _epub_element_text(label) if label is not None else ""
href = str(content.get("src") or "") if content is not None else ""
- locator = resolve_locator(href, ncx_member) if href else 0
+ locator, source_href, source_anchor = (
+ resolve_target(href, ncx_member) if href else (0, "", "")
+ )
if locator and title:
- rows.append(EpubOutlineItem(locator, title, max(1, level)))
+ rows.append(
+ EpubOutlineItem(
+ locator,
+ title,
+ max(1, level),
+ source_href,
+ source_anchor,
+ )
+ )
walk_ncx(point, level + 1)
nav_map = next(
diff --git a/tests/reading/test_engine.py b/tests/reading/test_engine.py
index dcfbf86f7..666dd0167 100644
--- a/tests/reading/test_engine.py
+++ b/tests/reading/test_engine.py
@@ -71,11 +71,11 @@ def _write_epub(path: Path) -> Path:
)
archive.writestr(
"OEBPS/nav.xhtml",
- """<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><body><nav epub:type="toc"><ol><li><a href="chapters/one.xhtml">Part One</a><ol><li><a href="chapters/two.xhtml">Second Chapter</a></li></ol></li></ol></nav></body></html>""",
+ """<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><body><nav epub:type="toc"><ol><li><a href="chapters/one.xhtml">Part One</a><ol><li><a href="chapters/one.xhtml#a1">First Topic</a></li><li><a href="chapters/one.xhtml#a2">Second Topic</a></li><li><a href="chapters/two.xhtml">Second Chapter</a></li></ol></li></ol></nav></body></html>""",
)
archive.writestr(
"OEBPS/chapters/one.xhtml",
- "<html xmlns='http://www.w3.org/1999/xhtml'><head><title>One</title></head><body><h1>First Chapter</h1><p>Alpha source text.</p><script>ignore me</script></body></html>",
+ "<html xmlns='http://www.w3.org/1999/xhtml'><head><title>One</title></head><body><h1>First Chapter</h1><h2 id='a1'>First Topic</h2><p>Alpha source text.</p><h2 id='a2'>Second Topic</h2><script>ignore me</script></body></html>",
)
archive.writestr(
"OEBPS/chapters/two.xhtml",
@@ -84,6 +84,28 @@ def _write_epub(path: Path) -> Path:
return path
+def _write_epub2(path: Path) -> Path:
+ with zipfile.ZipFile(path, "w") as archive:
+ archive.writestr("mimetype", "application/epub+zip")
+ archive.writestr(
+ "META-INF/container.xml",
+ """<?xml version="1.0"?><container xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>""",
+ )
+ archive.writestr(
+ "content.opf",
+ """<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="book"><manifest><item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine toc="ncx"><itemref idref="chapter"/></spine></package>""",
+ )
+ archive.writestr(
+ "toc.ncx",
+ """<?xml version="1.0"?><ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1"><navMap><navPoint id="chapter"><navLabel><text>Legacy Chapter</text></navLabel><content src="chapter.xhtml"/><navPoint id="section"><navLabel><text>Legacy Section</text></navLabel><content src="chapter.xhtml#legacy-section"/></navPoint></navPoint></navMap></ncx>""",
+ )
+ archive.writestr(
+ "chapter.xhtml",
+ "<html xmlns='http://www.w3.org/1999/xhtml'><body><h1>Legacy Chapter</h1><h2 id='legacy-section'>Legacy Section</h2><p>NCX text.</p></body></html>",
+ )
+ return path
+
+
def _wrap_epub_for_finder(path: Path) -> Path:
"""Model the package macOS Finder makes when it compresses an EPUB."""
data = path.read_bytes()
@@ -235,19 +257,66 @@ def test_epub_preserves_spine_units_source_hrefs_and_nested_outline(tmp_path: Pa
assert extraction.has_raw_view is False
assert extraction.unit == "chapter"
assert extraction.units == (
- "First Chapter\nAlpha source text.",
+ "First Chapter\nFirst Topic\nAlpha source text.\nSecond Topic",
"Second Chapter\nBeta source text.",
)
assert [ref.source_href for ref in extraction.unit_refs] == [
"OEBPS/chapters/one.xhtml",
"OEBPS/chapters/two.xhtml",
]
- assert [(row.locator, row.title, row.level) for row in extraction.outline] == [
- (1, "Part One", 1),
- (2, "Second Chapter", 2),
+ assert [
+ (
+ row.locator,
+ row.title,
+ row.level,
+ row.source_href,
+ row.source_anchor,
+ )
+ for row in extraction.outline
+ ] == [
+ (1, "Part One", 1, "OEBPS/chapters/one.xhtml", ""),
+ (1, "First Topic", 2, "OEBPS/chapters/one.xhtml", "a1"),
+ (1, "Second Topic", 2, "OEBPS/chapters/one.xhtml", "a2"),
+ (2, "Second Chapter", 2, "OEBPS/chapters/two.xhtml", ""),
]
+def test_epub2_ncx_preserves_heading_anchors(tmp_path: Path) -> None:
+ extraction = extract_material(_write_epub2(tmp_path / "legacy.epub"))
+
+ assert [
+ (row.locator, row.title, row.level, row.source_href, row.source_anchor)
+ for row in extraction.outline
+ ] == [
+ (1, "Legacy Chapter", 1, "chapter.xhtml", ""),
+ (1, "Legacy Section", 2, "chapter.xhtml", "legacy-section"),
+ ]
+
+
+def test_existing_epub_outline_is_upgraded_with_source_anchors(
+ store: ReadingStore, tmp_path: Path
+) -> None:
+ manifest = store.ingest(_write_epub(tmp_path / "book.epub"))
+ outline_path = store.root / manifest.source_hash / "outline.json"
+ legacy_rows = [
+ {
+ "locator": row.locator,
+ "title": row.title,
+ "level": row.level,
+ "synthesised": row.synthesised,
+ }
+ for row in store.outline(manifest.material_id)
+ ]
+ outline_path.write_text(json.dumps(legacy_rows), encoding="utf-8")
+
+ upgraded = store.outline(manifest.material_id)
+
+ assert upgraded[1].source_href == "OEBPS/chapters/one.xhtml"
+ assert upgraded[1].source_anchor == "a1"
+ assert upgraded[2].source_anchor == "a2"
+ assert all("source_anchor" in row for row in json.loads(outline_path.read_text()))
+
+
def test_pptx_slides_become_units_when_the_extractor_marks_them(tmp_path: Path) -> None:
pytest.importorskip("pptx")
from pptx import Presentation
diff --git a/web/components/reading/EpubDocumentView.tsx b/web/components/reading/EpubDocumentView.tsx
index 092e7b92a..e0f348b78 100644
--- a/web/components/reading/EpubDocumentView.tsx
+++ b/web/components/reading/EpubDocumentView.tsx
@@ -515,14 +515,14 @@ export function EpubDocumentView({
const section = bookRef.current.spine.get(
(headingJump.locator ?? locatorRef.current) - 1,
);
- const sourceHref = headingJump.sourceHref || section?.href;
+ const sourceHref = section?.href || headingJump.sourceHref;
if (!sourceHref) return;
void renditionRef.current
.display(`${sourceHref}#${headingJump.id}`)
.catch(() => {
// A damaged publisher anchor leaves the reader on the current page.
});
- }, [headingJump]);
+ }, [headingJump, loading]);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsx
index 1b41fb0ec..271e304d8 100644
--- a/web/components/reading/ReaderPane.tsx
+++ b/web/components/reading/ReaderPane.tsx
@@ -858,6 +858,17 @@ export function ReaderPane({
const showAnnotations = annotationPanel ?? annotations.length > 0;
const unitWord = material ? t(unitLabel(material.unit)) : "";
+ const isEpub = material?.render_mode === "epub";
+ const currentUnitTitle = isEpub
+ ? material?.unit_refs.find((row) => row.locator === currentLocator)?.title
+ : undefined;
+ const epubProgress = material
+ ? Math.round(
+ material.unit_count > 1
+ ? ((currentLocator - 1) / (material.unit_count - 1)) * 100
+ : 100,
+ )
+ : 0;
const bookmarkedHere = bookmarks.some(
(row) => row.locator === currentLocator,
);
@@ -972,11 +983,22 @@ export function ReaderPane({
code, not for a line of UI copy; tabular figures alone stop the
number from jittering as the learner scrolls. */}
<span className="hidden shrink-0 whitespace-nowrap px-1 text-[11.5px] tabular-nums text-[var(--muted-foreground)] md:inline">
- {t("{{unit}} {{n}} / {{total}}", {
- unit: unitWord,
- n: currentLocator,
- total: material.unit_count,
- })}
+ {isEpub ? (
+ <>
+ <span className="max-w-[180px] truncate">
+ {currentUnitTitle || material.title}
+ </span>
+ <span>
+ {` · ${Math.min(100, Math.max(0, epubProgress))}%`}
+ </span>
+ </>
+ ) : (
+ t("{{unit}} {{n}} / {{total}}", {
+ unit: unitWord,
+ n: currentLocator,
+ total: material.unit_count,
+ })
+ )}
</span>
{onToggleBookmark && (
<HeaderButton
diff --git a/web/components/reading/workspace/SourceNavigator.tsx b/web/components/reading/workspace/SourceNavigator.tsx
index 474a7ae2d..192bd8d2f 100644
--- a/web/components/reading/workspace/SourceNavigator.tsx
+++ b/web/components/reading/workspace/SourceNavigator.tsx
@@ -456,6 +456,8 @@ export function SourceNavigator({
activeRow={activeDocumentRow}
pageFallback={pageFallback}
collapsedNodes={search ? new Set() : collapsedNodes}
+ onNavigateHeading={onNavigateHeading}
+ showLocator={isPdf}
onToggle={(key) =>
setCollapsedNodes((current) => {
const next = new Set(current);
@@ -574,16 +576,20 @@ export function WorkspaceOutlineBranch({
activeRow,
pageFallback,
collapsedNodes,
+ onNavigateHeading,
onToggle,
onNavigate,
+ showLocator,
depth = 0,
}: {
nodes: OutlineNode[];
activeRow: OutlineRow | null;
pageFallback: boolean;
collapsedNodes: Set<string>;
+ onNavigateHeading: (heading: ReaderHeading) => void;
onToggle: (key: string) => void;
onNavigate: (locator: number) => void;
+ showLocator: boolean;
depth?: number;
}) {
const { t } = useTranslation();
@@ -593,6 +599,35 @@ export function WorkspaceOutlineBranch({
const key = `${node.row.locator}-${node.row.title}`;
const active = node.row === activeRow;
const collapsed = collapsedNodes.has(key);
+ const hasAnchor = Boolean(node.row.source_href && node.row.source_anchor);
+ const outlineButton = (
+ <button
+ type="button"
+ onClick={() => {
+ if (hasAnchor) {
+ onNavigateHeading({
+ id: node.row.source_anchor ?? "",
+ title: node.row.title,
+ level: node.row.level,
+ locator: node.row.locator,
+ sourceHref: node.row.source_href,
+ });
+ return;
+ }
+ onNavigate(node.row.locator);
+ }}
+ className="flex min-w-0 flex-1 items-baseline gap-2 px-2 py-1.5 text-left"
+ >
+ {showLocator && (
+ <span className="w-7 shrink-0 text-right text-[11px] tabular-nums text-[var(--muted-foreground)]">
+ {node.row.locator}
+ </span>
+ )}
+ <span className="line-clamp-3 min-w-0 text-[12px] leading-[1.5]">
+ {node.row.title}
+ </span>
+ </button>
+ );
return (
<li key={key} className="mb-0.5 min-w-0">
<div
@@ -603,32 +638,13 @@ export function WorkspaceOutlineBranch({
}`}
>
<span className="inline-flex min-w-0 flex-1 [&>span]:w-full [&>span>button]:w-full">
- <Tooltip label={t("p. {{page}}", { page: node.row.locator })}>
- <button
- type="button"
- onClick={() => onNavigate(node.row.locator)}
- className="flex min-w-0 flex-1 items-baseline gap-2 px-2 py-1.5 text-left"
- >
- {/* A table of contents is read by its titles, so the title
- carries the weight and the locator is the quiet column
- beside it — the other way round, 74 blue page numbers
- out-shouted the headings they were pointing at.
-
- It is also just the number. "p. 12" fits the 32px this
- column had, but every translation of it does not: in
- Chinese ("第 12 页") 65 of this document's 74 rows wrapped
- onto a second line, so the list had two different row
- heights and a ragged left edge for the titles. Right-
- aligned tabular digits are what a printed contents page
- does anyway, and no translation can outgrow them. */}
- <span className="w-7 shrink-0 text-right text-[11px] tabular-nums text-[var(--muted-foreground)]">
- {node.row.locator}
- </span>
- <span className="line-clamp-3 min-w-0 text-[12px] leading-[1.5]">
- {node.row.title}
- </span>
- </button>
- </Tooltip>
+ {showLocator ? (
+ <Tooltip label={t("p. {{page}}", { page: node.row.locator })}>
+ {outlineButton}
+ </Tooltip>
+ ) : (
+ outlineButton
+ )}
</span>
{node.children.length > 0 && (
<button
@@ -652,6 +668,8 @@ export function WorkspaceOutlineBranch({
collapsedNodes={collapsedNodes}
onToggle={onToggle}
onNavigate={onNavigate}
+ onNavigateHeading={onNavigateHeading}
+ showLocator={showLocator}
depth={depth + 1}
/>
)}
diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.ts
index 38b4e1bbc..24f0bb5cc 100644
--- a/web/lib/reading-api.ts
+++ b/web/lib/reading-api.ts
@@ -65,6 +65,8 @@ export interface OutlineRow {
title: string;
level: number;
synthesised: boolean;
+ source_href?: string;
+ source_anchor?: string;
}
export interface MaterialDetail extends MaterialInfo {
diff --git a/web/tests/epub-display-preferences.spec.tsx b/web/tests/epub-display-preferences.spec.tsx
index cdceac9af..d109e9151 100644
--- a/web/tests/epub-display-preferences.spec.tsx
+++ b/web/tests/epub-display-preferences.spec.tsx
@@ -111,6 +111,40 @@ it("opens EPUB in single-page mode and keeps the CFI when switching spreads", as
.toMatchObject({ spreadMode: "auto" });
});
+it("resolves outline anchors through epub.js spine-relative hrefs", async () => {
+ const props = {
+ materialId: "book",
+ unitCount: 1,
+ unitRefs: [],
+ annotations: [],
+ jump: null,
+ onSelection: () => undefined,
+ };
+ const { rerender } = render(<EpubDocumentView {...props} />);
+ await waitFor(() => expect(fixture.renderTo).toHaveBeenCalled());
+
+ rerender(
+ <EpubDocumentView
+ {...props}
+ headingJump={{
+ id: "publisher-anchor",
+ nonce: 1,
+ locator: 1,
+ sourceHref: "OEBPS/one.xhtml",
+ }}
+ />,
+ );
+
+ await waitFor(() =>
+ expect(fixture.rendition.display).toHaveBeenCalledWith(
+ "one.xhtml#publisher-anchor",
+ ),
+ );
+ expect(fixture.rendition.display).not.toHaveBeenCalledWith(
+ "OEBPS/one.xhtml#publisher-anchor",
+ );
+});
+
it("overrides a publisher's explicit paragraph and span ink and font", async () => {
publisherParagraph = document.createElement("p");
publisherParagraph.style.cssText =
diff --git a/web/tests/reading-outline-tracking.spec.tsx b/web/tests/reading-outline-tracking.spec.tsx
index 06f9d14c4..0b053bac1 100644
--- a/web/tests/reading-outline-tracking.spec.tsx
+++ b/web/tests/reading-outline-tracking.spec.tsx
@@ -12,7 +12,11 @@ const material = {
render_mode: "text",
unit: "section",
unit_count: 100,
- unit_refs: [],
+ unit_refs: [
+ { locator: 1, source_href: "chapter-1.xhtml", title: "Opening" },
+ { locator: 5, source_href: "chapter-5.xhtml", title: "Second chapter" },
+ { locator: 20, source_href: "chapter-20.xhtml", title: "Last chapter" },
+ ],
has_raw_view: false,
status: "ready",
source_kind: "upload",
@@ -51,6 +55,18 @@ vi.mock("@/components/reading/TextUnitView", () => ({
),
}));
+vi.mock("@/components/reading/EpubDocumentView", () => ({
+ EpubDocumentView: ({
+ onVisibleLocatorChange,
+ }: {
+ onVisibleLocatorChange?: (locator: number) => void;
+ }) => (
+ <button type="button" onClick={() => onVisibleLocatorChange?.(5)}>
+ turn epub to chapter 5
+ </button>
+ ),
+}));
+
describe("the reading outline", () => {
it("hears about a page turned in the document, not only a row clicked", async () => {
const onLocatorChange = vi.fn();
@@ -62,4 +78,16 @@ describe("the reading outline", () => {
// last put it, so the outline never left chapter one (#1447).
expect(onLocatorChange).toHaveBeenCalledWith(5);
});
+
+ it("labels an EPUB by its current chapter and progress, not spine page count", async () => {
+ material.render_mode = "epub";
+ material.unit_count = 20;
+ render(<ReaderPane onClose={vi.fn()} />);
+
+ fireEvent.click(await screen.findByText("turn epub to chapter 5"));
+
+ expect(screen.getByText("Second chapter")).toBeInTheDocument();
+ expect(screen.getByText(/21%/)).toBeInTheDocument();
+ expect(screen.queryByText("chapter 5 / 20")).not.toBeInTheDocument();
+ });
});
diff --git a/web/tests/reading-source-navigator.spec.tsx b/web/tests/reading-source-navigator.spec.tsx
index fff1936bd..f40524e33 100644
--- a/web/tests/reading-source-navigator.spec.tsx
+++ b/web/tests/reading-source-navigator.spec.tsx
@@ -59,9 +59,11 @@ const headings: ReaderHeading[] = [
function renderNavigator({
outlineRows = outline,
pageHeadings = [],
+ onNavigateHeading = vi.fn(),
}: {
outlineRows?: OutlineRow[]
pageHeadings?: ReaderHeading[]
+ onNavigateHeading?: (heading: ReaderHeading) => void
} = {}) {
const onSelectMaterial = vi.fn()
const onRemoveMaterial = vi.fn()
@@ -75,7 +77,7 @@ function renderNavigator({
outline={outlineRows}
pageHeadings={pageHeadings}
activeHeadingId={null}
- onNavigateHeading={vi.fn()}
+ onNavigateHeading={onNavigateHeading}
refs={refs}
transcript={[]}
transcriptUnavailable={false}
@@ -92,7 +94,7 @@ function renderNavigator({
onRemoveBookmark={vi.fn()}
/>
)
- return { onSelectMaterial, onRemoveMaterial }
+ return { onSelectMaterial, onRemoveMaterial, onNavigateHeading }
}
describe('reading source navigator', () => {
@@ -130,6 +132,50 @@ describe('reading source navigator', () => {
expect(screen.getByRole('button', { name: 'Local heading' })).toBeInTheDocument()
})
+ it('navigates EPUB outline anchors through their publisher fragments', async () => {
+ const user = userEvent.setup()
+ const onNavigateHeading = vi.fn()
+ renderNavigator({
+ onNavigateHeading,
+ outlineRows: [
+ {
+ locator: 1,
+ title: 'Alpha heading',
+ level: 2,
+ synthesised: false,
+ source_href: 'OEBPS/chapter.xhtml',
+ source_anchor: 'alpha',
+ },
+ {
+ locator: 1,
+ title: 'Second heading',
+ level: 2,
+ synthesised: false,
+ source_href: 'OEBPS/chapter.xhtml',
+ source_anchor: 'second',
+ },
+ ],
+ })
+
+ await user.click(screen.getByRole('button', { name: /Alpha heading/ }))
+ await user.click(screen.getByRole('button', { name: /Second heading/ }))
+
+ expect(onNavigateHeading).toHaveBeenNthCalledWith(1, {
+ id: 'alpha',
+ title: 'Alpha heading',
+ level: 2,
+ locator: 1,
+ sourceHref: 'OEBPS/chapter.xhtml',
+ })
+ expect(onNavigateHeading).toHaveBeenNthCalledWith(2, {
+ id: 'second',
+ title: 'Second heading',
+ level: 2,
+ locator: 1,
+ sourceHref: 'OEBPS/chapter.xhtml',
+ })
+ })
+
it('collapses and re-expands the active material', async () => {
const user = userEvent.setup()
renderNavigator()