Skip to content

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

feat(reading): expose EPUB headings in the persistent outline

XZH8263cddec8b4
diff --git a/web/components/reading/EpubDocumentView.tsx b/web/components/reading/EpubDocumentView.tsx
index efa6b04b0..61bb25d53 100644
--- a/web/components/reading/EpubDocumentView.tsx
+++ b/web/components/reading/EpubDocumentView.tsx
@@ -19,6 +19,7 @@ import {
resolveEpubPageTurnSwipe,
type EpubPageTurnDirection,
} from "@/lib/epub-page-turn";
+import { extractEpubHeadings, type ReaderHeading } from "@/lib/reading-outline";
import { cleanQuote } from "@/lib/reading-selection";
import type { JumpRequest, SelectionPayload } from "./PdfDocumentView";
@@ -102,6 +103,8 @@ export interface EpubDocumentViewProps {
onSelection: (payload: SelectionPayload | null) => void;
onAnnotationClick?: (annotation: AnnotationItem) => void;
onVisibleLocatorChange?: (locator: number) => void;
+ onHeadingsChange?: (headings: ReaderHeading[]) => void;
+ headingJump?: { id: string; nonce: number } | null;
onError?: (message: string) => void;
}
@@ -116,6 +119,8 @@ export function EpubDocumentView({
onSelection,
onAnnotationClick,
onVisibleLocatorChange,
+ onHeadingsChange,
+ headingJump,
onError,
}: EpubDocumentViewProps) {
const { t } = useTranslation();
@@ -128,6 +133,7 @@ export function EpubDocumentView({
const refsRef = useRef(unitRefs);
const annotationClickRef = useRef(onAnnotationClick);
const visibleChangeRef = useRef(onVisibleLocatorChange);
+ const headingsChangeRef = useRef(onHeadingsChange);
const errorRef = useRef(onError);
const locatorRef = useRef(1);
const [loading, setLoading] = useState(true);
@@ -142,6 +148,12 @@ export function EpubDocumentView({
useEffect(() => {
visibleChangeRef.current = onVisibleLocatorChange;
}, [onVisibleLocatorChange]);
+ useEffect(() => {
+ headingsChangeRef.current?.([]);
+ }, [materialId]);
+ useEffect(() => {
+ headingsChangeRef.current = onHeadingsChange;
+ }, [onHeadingsChange]);
useEffect(() => {
errorRef.current = onError;
}, [onError]);
@@ -229,6 +241,17 @@ export function EpubDocumentView({
const doc = contents.document;
if (!doc?.body || doc.body.dataset.dtReaderReady === "true") return;
doc.body.dataset.dtReaderReady = "true";
+ const href = (doc.location?.pathname ?? "").replace(/^\//, "");
+ const locator =
+ locatorForEpubHref(href, refsRef.current) || locatorRef.current;
+ const headingElements = Array.from(
+ doc.querySelectorAll<HTMLElement>("h1,h2,h3,h4,h5,h6"),
+ ).filter((element) => (element.textContent ?? "").trim());
+ const headings = extractEpubHeadings(headingElements, locator);
+ headingElements.forEach((element, index) => {
+ element.id = headings[index].id;
+ });
+ headingsChangeRef.current?.(headings);
let gesture: { x: number; y: number } | null = null;
doc.addEventListener(
"touchstart",
@@ -360,6 +383,17 @@ export function EpubDocumentView({
};
}, [materialId, unitCount, onSelection, t, turnPage]);
+ useEffect(() => {
+ if (!headingJump || !renditionRef.current || !bookRef.current) return;
+ const section = bookRef.current.spine.get(locatorRef.current - 1);
+ if (!section?.href) return;
+ void renditionRef.current
+ .display(`${section.href}#${headingJump.id}`)
+ .catch(() => {
+ // A damaged publisher anchor leaves the reader on the current page.
+ });
+ }, [headingJump]);
+
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsx
index 38cd051b0..8cfec4c66 100644
--- a/web/components/reading/ReaderPane.tsx
+++ b/web/components/reading/ReaderPane.tsx
@@ -541,6 +541,8 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
setActiveAnnotationId(annotation.annotation_id)
}
onVisibleLocatorChange={handleVisibleLocator}
+ onHeadingsChange={setPageHeadings}
+ headingJump={headingJump}
onError={setError}
/>
) : material.has_raw_view ? (
diff --git a/web/lib/reading-outline.ts b/web/lib/reading-outline.ts
index d16934801..3712af090 100644
--- a/web/lib/reading-outline.ts
+++ b/web/lib/reading-outline.ts
@@ -31,6 +31,32 @@ export function readerHeadingLine(line: string): ReaderHeading | null {
return { id: "", title, level: match[1].length };
}
+export interface EpubHeadingElement {
+ id?: string | null;
+ tagName: string;
+ textContent: string | null;
+}
+
+/** Extract EPUB headings while preserving publisher-provided anchors. */
+export function extractEpubHeadings(
+ elements: EpubHeadingElement[],
+ locator: number,
+): ReaderHeading[] {
+ const headings: ReaderHeading[] = [];
+ for (const element of elements) {
+ const match = /^h([1-6])$/i.exec(element.tagName);
+ if (!match) continue;
+ const title = (element.textContent ?? "").replace(/\s+/g, " ").trim();
+ if (!title) continue;
+ headings.push({
+ id: element.id?.trim() || headingAnchor(locator, headings.length),
+ title,
+ level: Number(match[1]),
+ });
+ }
+ return headings;
+}
+
/**
* Attach outline entries to source lines without changing a single character.
*
diff --git a/web/tests/epub-reader.audit.ts b/web/tests/epub-reader.audit.ts
index fb9005c4a..59ad20461 100644
--- a/web/tests/epub-reader.audit.ts
+++ b/web/tests/epub-reader.audit.ts
@@ -1,7 +1,7 @@
import { expect, test } from "@playwright/test";
import JSZip from "jszip";
-async function illustratedEpub(): Promise<Buffer> {
+async function illustratedEpub(options?: { longPage?: boolean }): Promise<Buffer> {
const zip = new JSZip();
zip.file("mimetype", "application/epub+zip", { compression: "STORE" });
zip.file(
@@ -18,7 +18,7 @@ async function illustratedEpub(): Promise<Buffer> {
);
zip.file(
"OPS/one.xhtml",
- "<html xmlns='http://www.w3.org/1999/xhtml'><head><title>Illustrated chapter</title></head><body><h1>Illustrated chapter</h1><p>This layout comes from the EPUB.</p><img alt='source illustration' src='dot.png'/></body></html>",
+ `<html xmlns='http://www.w3.org/1999/xhtml'><head><title>Illustrated chapter</title></head><body><h1 id='publisher-title'>Illustrated chapter</h1><h2>Source layout</h2>${options?.longPage ? "<div style='height: 2500px'></div>" : ""}<h3 id='late-detail'>Late detail</h3><p>This layout comes from the EPUB.</p><img alt='source illustration' src='dot.png'/></body></html>`,
);
zip.file(
"OPS/two.xhtml",
@@ -37,10 +37,62 @@ async function illustratedEpub(): Promise<Buffer> {
});
}
+test("EPUB headings feed and navigate the current-page outline", async ({
+ page,
+}, testInfo) => {
+ const filename = `epub-page-headings-${Date.now()}-${testInfo.project.name}.epub`;
+ await page.goto("/home?capability=immersive_reading");
+ const fileInput = page
+ .getByRole("button", { name: /Open a document to read/i })
+ .locator('input[type="file"]');
+ await fileInput.setInputFiles({
+ name: filename,
+ mimeType: "application/epub+zip",
+ buffer: await illustratedEpub({ longPage: true }),
+ });
+
+ const readerFrame = page.locator("iframe").contentFrame();
+ await expect(
+ readerFrame.getByRole("heading", { name: "Illustrated chapter" }),
+ ).toBeVisible();
+ if (testInfo.project.name === "epub-reader-webkit") {
+ await page.getByRole("button", { name: "Contents" }).click();
+ }
+ await page.getByRole("tab", { name: "On this page" }).click();
+ await expect(page.getByRole("button", { name: "Source layout" })).toBeVisible();
+ const lateDetail = readerFrame.getByRole("heading", { name: "Late detail" });
+ const readerBox = await page.locator("iframe").boundingBox();
+ const beforeJump = await lateDetail.boundingBox();
+ expect(beforeJump?.y).toBeGreaterThan((readerBox?.y ?? 0) + 100);
+ await page.getByRole("button", { name: "Late detail" }).click();
+ await expect(
+ lateDetail,
+ ).toBeVisible();
+ await expect
+ .poll(async () => (await lateDetail.boundingBox())?.x ?? Number.MAX_SAFE_INTEGER)
+ .toBeLessThan((beforeJump?.x ?? Number.MAX_SAFE_INTEGER) - 100);
+ const afterJump = await lateDetail.boundingBox();
+ expect(afterJump?.x).toBeLessThanOrEqual((readerBox?.x ?? 0) + 100);
+
+ await page.getByRole("tab", { name: "Document contents" }).click();
+ await page.getByRole("button", { name: "Second chapter" }).click();
+ await expect(
+ readerFrame.getByRole("heading", { name: "Second chapter" }),
+ ).toBeVisible();
+ await page.getByRole("button", { name: "Contents" }).click();
+ await page.getByRole("tab", { name: "On this page" }).click();
+ await expect(
+ page.getByRole("button", { name: "Source layout" }),
+ ).toBeHidden();
+ await expect(
+ page.getByRole("button", { name: "Second chapter" }),
+ ).toBeVisible();
+});
+
test("faithfully renders EPUB resources, navigates, and restores its CFI", async ({
page,
}, testInfo) => {
- const filename = `faithful-reader-${Date.now()}.epub`;
+ const filename = `faithful-reader-${Date.now()}-${testInfo.project.name}.epub`;
await page.goto("/home?capability=immersive_reading");
const fileInput = page
.getByRole("button", { name: /Open a document to read/i })
@@ -61,9 +113,7 @@ test("faithfully renders EPUB resources, navigates, and restores its CFI", async
testInfo.project.name === "epub-reader-webkit"
? () => page.getByRole("button", { name: "Next", exact: true }).click()
: async () => {
- await readerFrame
- .getByText("This layout comes from the EPUB.")
- .click();
+ await readerFrame.locator("body").click();
await page.keyboard.press("ArrowRight");
};
for (let attempt = 0; attempt < 4; attempt += 1) {
diff --git a/web/tests/reading-outline.test.ts b/web/tests/reading-outline.test.ts
index 546993cd6..98d6198d3 100644
--- a/web/tests/reading-outline.test.ts
+++ b/web/tests/reading-outline.test.ts
@@ -5,6 +5,7 @@ import path from "node:path";
import {
activeReaderHeading,
buildOutlineTree,
+ extractEpubHeadings,
extractReaderHeadings,
filterReaderHeadings,
filterOutlineNodes,
@@ -62,6 +63,31 @@ test("extracts Markdown headings and skips fenced code", () => {
]);
});
+test("extracts every EPUB heading level and preserves explicit anchors", () => {
+ const headings = extractEpubHeadings(
+ [
+ { id: "publisher-title", tagName: "h1", textContent: " Title " },
+ { tagName: "h2", textContent: "Section" },
+ { tagName: "H3", textContent: "Subsection" },
+ { tagName: "h4", textContent: "Detail" },
+ { tagName: "h5", textContent: "Fine detail" },
+ { tagName: "h6", textContent: "Notes" },
+ { tagName: "p", textContent: "Not a heading" },
+ { tagName: "h2", textContent: " " },
+ ],
+ 7,
+ );
+
+ assert.deepEqual(headings, [
+ { id: "publisher-title", title: "Title", level: 1 },
+ { id: "dt-reader-heading-7-2", title: "Section", level: 2 },
+ { id: "dt-reader-heading-7-3", title: "Subsection", level: 3 },
+ { id: "dt-reader-heading-7-4", title: "Detail", level: 4 },
+ { id: "dt-reader-heading-7-5", title: "Fine detail", level: 5 },
+ { id: "dt-reader-heading-7-6", title: "Notes", level: 6 },
+ ]);
+});
+
test("heading anchors preserve the exact source used by annotation selectors", () => {
const sourceText = " # Title ##\r\nBody\n```md\n# Code\n```\n## Next\n";
const headings = extractReaderHeadings([sourceText], 4);
@@ -99,6 +125,7 @@ test("reader outline is persistent, searchable, and wired to page headings", ()
const outline = source("components/reading/ReaderOutline.tsx");
const reader = source("components/reading/ReaderPane.tsx");
const textReader = source("components/reading/TextUnitView.tsx");
+ const epubReader = source("components/reading/EpubDocumentView.tsx");
assert.match(outline, /aria-label=\{t\("Contents"\)\}/);
assert.match(outline, /Filter contents/);
@@ -108,6 +135,10 @@ test("reader outline is persistent, searchable, and wired to page headings", ()
assert.match(reader, /dt\.reader\.outline\.\$\{material\.material_id\}/);
assert.match(reader, /event\.key\.toLowerCase\(\) === "b"/);
assert.match(reader, /onNavigateHeading/);
+ assert.match(epubReader, /h1,h2,h3,h4,h5,h6/);
+ assert.match(epubReader, /extractEpubHeadings/);
+ assert.match(epubReader, /section\.href\}#\$\{headingJump\.id\}/);
+ assert.match(reader, /onHeadingsChange=\{setPageHeadings\}/);
assert.match(textReader, /data-reader-heading-id/);
assert.match(textReader, /container\.scrollTo\(/);
assert.match(textReader, /elementRect\.top - containerRect\.top/);