DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(reading): render EPUBs faithfully in ReaderPane
XZHe758af8f4832
diff --git a/web/components/reading/EpubDocumentView.tsx b/web/components/reading/EpubDocumentView.tsxnew file mode 100644index 000000000..8043bfaf6--- /dev/null+++ b/web/components/reading/EpubDocumentView.tsx@@ -0,0 +1,488 @@+"use client";++import { ChevronLeft, ChevronRight, Loader2 } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";++import { apiFetch } from "@/lib/api";+import {+ getReadingPosition,+ rawMaterialUrl,+ saveReadingPosition,+ type AnnotationItem,+ type UnitReference,+} from "@/lib/reading-api";+import {+ allowsEpubPageTurn,+ directionForEpubLayout,+ locatorForEpubHref,+ resolveEpubPageTurnSwipe,+ type EpubPageTurnDirection,+} from "@/lib/epub-page-turn";+import { cleanQuote } from "@/lib/reading-selection";+import type {+ JumpRequest,+ SelectionPayload,+} from "./PdfDocumentView";++type EpubLocation = {+ start?: { cfi?: string; href?: string; percentage?: number };+};++type EpubContents = {+ document?: Document;+ window?: Window;+};++type EpubAnnotationLayer = {+ highlight: (+ cfi: string,+ data?: Record<string, string>,+ callback?: () => void,+ className?: string,+ styles?: Record<string, string>,+ ) => void;+ remove: (cfi: string, type?: string) => void;+};++type EpubRendition = {+ display: (target?: string) => Promise<unknown>;+ next: () => Promise<unknown>;+ prev: () => Promise<unknown>;+ destroy: () => void;+ on: (event: string, callback: (...args: unknown[]) => void) => void;+ off: (event: string, callback: (...args: unknown[]) => void) => void;+ annotations: EpubAnnotationLayer;+ hooks: {+ content: {+ register: (callback: (contents: EpubContents) => void) => void;+ };+ };+ themes: {+ register: (name: string, rules: Record<string, Record<string, string>>) => void;+ select: (name: string) => void;+ };+};++type EpubSection = {+ href?: string;+ load: (loader: (path: string) => Promise<unknown>) => Promise<unknown>;+ find: (query: string) => Array<{ cfi: string }>;+};++type EpubBook = {+ open: (input: ArrayBuffer) => Promise<unknown>;+ ready: Promise<unknown>;+ package?: { metadata?: { direction?: string } };+ load: (path: string) => Promise<unknown>;+ spine: { get: (target: string | number) => EpubSection | undefined };+ locations?: { percentageFromCfi?: (cfi: string) => number };+ renderTo: (+ element: Element,+ options: Record<string, unknown>,+ ) => EpubRendition;+ destroy: () => void;+};++const HIGHLIGHT_COLORS: Record<string, string> = {+ yellow: "rgba(250, 220, 90, 0.55)",+ green: "rgba(140, 219, 148, 0.55)",+ blue: "rgba(122, 192, 250, 0.55)",+ pink: "rgba(250, 161, 199, 0.55)",+ purple: "rgba(199, 174, 250, 0.55)",+};++export interface EpubDocumentViewProps {+ materialId: string;+ unitCount: number;+ unitRefs: UnitReference[];+ annotations: AnnotationItem[];+ jump: JumpRequest | null;+ highlightedAnnotationId?: string | null;+ onSelection: (payload: SelectionPayload | null) => void;+ onAnnotationClick?: (annotation: AnnotationItem) => void;+ onVisibleLocatorChange?: (locator: number) => void;+ onError?: (message: string) => void;+}++/** Source-faithful, paginated EPUB renderer aligned to server locators. */+export function EpubDocumentView({+ materialId,+ unitCount,+ unitRefs,+ annotations,+ jump,+ highlightedAnnotationId,+ onSelection,+ onAnnotationClick,+ onVisibleLocatorChange,+ onError,+}: EpubDocumentViewProps) {+ const { t } = useTranslation();+ const hostRef = useRef<HTMLDivElement | null>(null);+ const bookRef = useRef<EpubBook | null>(null);+ const renditionRef = useRef<EpubRendition | null>(null);+ const isRtlRef = useRef(false);+ const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const renderedAnchorsRef = useRef<string[]>([]);+ const refsRef = useRef(unitRefs);+ const annotationClickRef = useRef(onAnnotationClick);+ const visibleChangeRef = useRef(onVisibleLocatorChange);+ const errorRef = useRef(onError);+ const locatorRef = useRef(1);+ const [loading, setLoading] = useState(true);+ const [loadError, setLoadError] = useState("");++ useEffect(() => {+ refsRef.current = unitRefs;+ }, [unitRefs]);+ useEffect(() => {+ annotationClickRef.current = onAnnotationClick;+ }, [onAnnotationClick]);+ useEffect(() => {+ visibleChangeRef.current = onVisibleLocatorChange;+ }, [onVisibleLocatorChange]);+ useEffect(() => {+ errorRef.current = onError;+ }, [onError]);++ const turnPage = useCallback((direction: EpubPageTurnDirection) => {+ const rendition = renditionRef.current;+ if (!rendition) return;+ const physical = directionForEpubLayout(direction, isRtlRef.current);+ void (physical === "next" ? rendition.next() : rendition.prev());+ }, []);++ useEffect(() => {+ const host = hostRef.current;+ if (!host) return;+ let cancelled = false;+ let rendition: EpubRendition | null = null;+ let book: EpubBook | null = null;++ const onRelocated = (raw: unknown) => {+ const location = raw as EpubLocation;+ const href = location.start?.href ?? "";+ const nextLocator = locatorForEpubHref(href, refsRef.current) || 1;+ const cfi = location.start?.cfi ?? "";+ const percentage = Math.min(+ 1,+ Math.max(+ 0,+ Number(+ location.start?.percentage ??+ book?.locations?.percentageFromCfi?.(cfi) ??+ (unitCount > 1 ? (nextLocator - 1) / (unitCount - 1) : 0),+ ),+ ),+ );+ locatorRef.current = nextLocator;+ visibleChangeRef.current?.(nextLocator);+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);+ saveTimerRef.current = setTimeout(() => {+ void saveReadingPosition(materialId, {+ locator: nextLocator,+ source_anchor: cfi,+ percentage,+ }).catch(() => {+ // Reading must continue when a background progress write fails.+ });+ }, 350);+ };++ const onSelected = (rawCfi: unknown, rawContents: unknown) => {+ const cfi = String(rawCfi || "");+ const contents = rawContents as EpubContents;+ const selection = contents.window?.getSelection?.();+ const quote = cleanQuote(selection?.toString() ?? "");+ if (!quote || !cfi) return;+ const rect = selection?.rangeCount+ ? selection.getRangeAt(0).getBoundingClientRect()+ : null;+ onSelection({+ locator: locatorForEpubHref(+ (contents.document?.location?.pathname ?? "").replace(/^\//, ""),+ refsRef.current,+ ) || locatorRef.current,+ quote,+ rects: [],+ sourceAnchor: cfi,+ anchor: rect+ ? { x: rect.left + rect.width / 2, y: rect.top }+ : { x: 0, y: 0 },+ });+ };++ const onRenditionKey = (rawEvent: unknown) => {+ const event = rawEvent as KeyboardEvent;+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;+ if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;+ if (!allowsEpubPageTurn(event.target)) return;+ event.preventDefault();+ turnPage(event.key === "ArrowLeft" ? "previous" : "next");+ };++ const installContentSafety = (rawContents: unknown) => {+ const contents = rawContents as EpubContents;+ const doc = contents.document;+ if (!doc?.body || doc.body.dataset.dtReaderReady === "true") return;+ doc.body.dataset.dtReaderReady = "true";+ let gesture: { x: number; y: number } | null = null;+ doc.addEventListener(+ "touchstart",+ (event) => {+ gesture = null;+ if (event.touches.length !== 1) return;+ const touch = event.touches[0];+ if (!allowsEpubPageTurn(touch.target)) return;+ gesture = { x: touch.clientX, y: touch.clientY };+ },+ { passive: true },+ );+ doc.addEventListener(+ "touchend",+ (event) => {+ if (!gesture || event.changedTouches.length !== 1) return;+ const start = gesture;+ gesture = null;+ if ((doc.getSelection?.()?.toString() ?? "").trim()) return;+ const touch = event.changedTouches[0];+ const direction = resolveEpubPageTurnSwipe(+ start.x,+ start.y,+ touch.clientX,+ touch.clientY,+ );+ if (!direction) return;+ event.preventDefault();+ turnPage(direction);+ },+ { passive: false },+ );+ doc.addEventListener("click", (event) => {+ const anchor = (event.target as Element | null)?.closest?.("a[href]");+ const href = anchor?.getAttribute("href") ?? "";+ if (!/^https?:\/\//i.test(href)) return;+ event.preventDefault();+ window.open(href, "_blank", "noopener,noreferrer");+ });+ };++ void (async () => {+ try {+ setLoading(true);+ setLoadError("");+ const [module, response, position] = await Promise.all([+ import("epubjs"),+ apiFetch(rawMaterialUrl(materialId), { cache: "no-store" }),+ getReadingPosition(materialId).catch(() => null),+ ]);+ if (!response.ok) throw new Error(t("Could not load this section."));+ const bytes = await response.arrayBuffer();+ if (cancelled) return;+ const createBook = module.default as unknown as (+ input?: ArrayBuffer,+ ) => EpubBook;+ // Calling epubjs with bytes in its constructor swallows open errors and+ // leaves `ready` pending forever. Open explicitly so damaged packages+ // reach the reader's error state instead of an endless skeleton.+ book = createBook();+ bookRef.current = book;+ await book.open(bytes);+ await book.ready;+ if (cancelled) return;+ isRtlRef.current = book.package?.metadata?.direction === "rtl";+ rendition = book.renderTo(host, {+ width: "100%",+ height: "100%",+ flow: "paginated",+ spread: "auto",+ allowScriptedContent: false,+ });+ renditionRef.current = rendition;+ rendition.themes.register("deeptutor", {+ "body, p, span, div": {+ "font-family":+ "ui-serif, Georgia, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', serif !important",+ },+ "body *": { "vertical-align": "baseline" },+ img: { "max-width": "100%", height: "auto" },+ });+ rendition.themes.select("deeptutor");+ rendition.on("relocated", onRelocated);+ rendition.on("selected", onSelected);+ rendition.on("keydown", onRenditionKey);+ rendition.hooks.content.register(installContentSafety);+ const fallbackHref =+ book.spine.get((position?.locator ?? 1) - 1)?.href ??+ refsRef.current.find(+ (ref) => ref.locator === (position?.locator ?? 1),+ )?.source_href;+ try {+ await rendition.display(position?.source_anchor || fallbackHref || undefined);+ } catch {+ await rendition.display(+ fallbackHref ??+ book.spine.get(0)?.href ??+ refsRef.current[0]?.source_href,+ );+ }+ if (!cancelled) setLoading(false);+ } catch (error) {+ if (cancelled) return;+ const message =+ error instanceof Error+ ? error.message+ : t("Could not load this section.");+ setLoadError(message);+ errorRef.current?.(message);+ setLoading(false);+ }+ })();++ return () => {+ cancelled = true;+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);+ if (rendition) {+ rendition.off("relocated", onRelocated);+ rendition.off("selected", onSelected);+ rendition.off("keydown", onRenditionKey);+ rendition.destroy();+ }+ book?.destroy();+ renditionRef.current = null;+ bookRef.current = null;+ host.replaceChildren();+ };+ }, [materialId, unitCount, onSelection, t, turnPage]);++ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;+ if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;+ if (!allowsEpubPageTurn(event.target)) return;+ event.preventDefault();+ turnPage(event.key === "ArrowLeft" ? "previous" : "next");+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [turnPage]);++ useEffect(() => {+ const rendition = renditionRef.current;+ const book = bookRef.current;+ if (!rendition || !book) return;+ let cancelled = false;+ for (const anchor of renderedAnchorsRef.current) {+ rendition.annotations.remove(anchor, "highlight");+ }+ renderedAnchorsRef.current = [];+ void (async () => {+ for (const annotation of annotations) {+ let anchor = annotation.source_anchor;+ if (!anchor && annotation.quote) {+ const section = book.spine.get(annotation.locator - 1);+ if (section) {+ try {+ await section.load(book.load.bind(book));+ const matches = section.find(annotation.quote);+ if (matches.length === 1) anchor = matches[0].cfi;+ } catch {+ // An ambiguous legacy quote stays in the list without fake ink.+ }+ }+ }+ if (!anchor || cancelled) continue;+ renderedAnchorsRef.current.push(anchor);+ rendition.annotations.highlight(+ anchor,+ { annotationId: annotation.annotation_id },+ () => annotationClickRef.current?.(annotation),+ `dt-epub-annotation-${annotation.annotation_id}`,+ {+ fill: HIGHLIGHT_COLORS[annotation.color] ?? HIGHLIGHT_COLORS.yellow,+ "fill-opacity":+ annotation.annotation_id === highlightedAnnotationId ? "0.8" : "0.55",+ },+ );+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [annotations, highlightedAnnotationId, unitRefs]);++ useEffect(() => {+ if (!jump || !renditionRef.current) return;+ const sectionTarget = bookRef.current?.spine.get(jump.locator - 1);+ const ref = unitRefs.find((row) => row.locator === jump.locator);+ const target = sectionTarget?.href ?? ref?.source_href;+ if (!target) return;+ void renditionRef.current.display(target).then(async () => {+ if (!jump.quote || !bookRef.current || !renditionRef.current) return;+ const section = bookRef.current.spine.get(jump.locator - 1);+ if (!section) return;+ try {+ await section.load(bookRef.current.load.bind(bookRef.current));+ const matches = section.find(jump.quote);+ if (matches.length !== 1) return;+ renditionRef.current.annotations.highlight(+ matches[0].cfi,+ {},+ undefined,+ "dt-epub-jump",+ { fill: "rgba(99, 102, 241, 0.35)" },+ );+ window.setTimeout(() => {+ renditionRef.current?.annotations.remove(matches[0].cfi, "highlight");+ }, 2200);+ } catch {+ // Reaching the requested locator is still useful if quote search fails.+ }+ });+ }, [jump, unitRefs]);++ return (+ <div className="relative h-full min-h-0 overflow-hidden bg-[var(--background)] pb-[env(safe-area-inset-bottom)]">+ <div+ ref={hostRef}+ className="h-full w-full"+ aria-label={t("Immersive reading")}+ />+ {loading && (+ <div className="absolute inset-0 flex items-center justify-center gap-2 bg-[var(--background)] text-xs text-[var(--muted-foreground)]">+ <Loader2 size={15} className="animate-spin" />+ {t("Opening document…")}+ </div>+ )}+ {!loading && loadError && (+ <div+ role="alert"+ className="absolute inset-0 grid place-items-center p-8 text-center text-sm text-[var(--destructive)]"+ >+ {loadError}+ </div>+ )}+ {!loadError && (+ <>+ <button+ type="button"+ onClick={() => turnPage("previous")}+ className="absolute left-2 top-1/2 inline-flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full border border-[var(--border)] bg-[var(--background)]/90 text-[var(--foreground)] shadow-sm backdrop-blur transition hover:bg-[var(--muted)]"+ aria-label={t("Previous")}+ >+ <ChevronLeft size={19} />+ </button>+ <button+ type="button"+ onClick={() => turnPage("next")}+ className="absolute right-2 top-1/2 inline-flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full border border-[var(--border)] bg-[var(--background)]/90 text-[var(--foreground)] shadow-sm backdrop-blur transition hover:bg-[var(--muted)]"+ aria-label={t("Next")}+ >+ <ChevronRight size={19} />+ </button>+ </>+ )}+ </div>+ );+}diff --git a/web/components/reading/PdfDocumentView.tsx b/web/components/reading/PdfDocumentView.tsxindex 921645484..3cfab5557 100644--- a/web/components/reading/PdfDocumentView.tsx+++ b/web/components/reading/PdfDocumentView.tsx@@ -23,6 +23,7 @@ export interface SelectionPayload {locator: number;quote: string;rects: NormalisedRect[];+ sourceAnchor?: string;/** Viewport coordinates of the selection, for popover placement. */anchor: { x: number; y: number };}diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsxindex ac8b8e58f..4b3f59cee 100644--- a/web/components/reading/ReaderPane.tsx+++ b/web/components/reading/ReaderPane.tsx@@ -26,6 +26,7 @@ import {} from "@/lib/reading-api";import { AnnotationList } from "./AnnotationList";import { AnnotationPopover } from "./AnnotationPopover";+import { EpubDocumentView } from "./EpubDocumentView";import { MaterialPicker } from "./MaterialPicker";import {PdfDocumentView,@@ -245,6 +246,7 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {quote: selection.quote,note,rects: selection.rects,+ source_anchor: selection.sourceAnchor ?? "",},{annotation_id: temporaryId,@@ -254,6 +256,7 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {quote: selection.quote,note,rects: selection.rects,+ source_anchor: selection.sourceAnchor ?? "",author: "user",created_at: now,updated_at: now,@@ -440,6 +443,21 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {<MaterialPickeronOpen={(candidate) => void openMaterial(candidate)}/>+ ) : material.render_mode === "epub" ? (+ <EpubDocumentView+ materialId={material.material_id}+ unitCount={material.unit_count}+ unitRefs={material.unit_refs}+ annotations={annotations}+ jump={jump}+ highlightedAnnotationId={activeAnnotationId}+ onSelection={setSelection}+ onAnnotationClick={(annotation) =>+ setActiveAnnotationId(annotation.annotation_id)+ }+ onVisibleLocatorChange={handleVisibleLocator}+ onError={setError}+ />) : material.has_raw_view ? (<PdfDocumentViewmaterialId={material.material_id}diff --git a/web/lib/epub-page-turn.ts b/web/lib/epub-page-turn.tsnew file mode 100644index 000000000..4f8b89be8--- /dev/null+++ b/web/lib/epub-page-turn.ts@@ -0,0 +1,70 @@+export type EpubPageTurnDirection = "previous" | "next";++export const EPUB_PAGE_TURN_MIN_DRAG_PX = 48;+export const EPUB_PAGE_TURN_HORIZONTAL_RATIO = 1.25;++const INTERACTIVE_SELECTOR = [+ "a",+ "button",+ "input",+ "textarea",+ "select",+ "video",+ "iframe",+ "svg",+ "pre",+ "[contenteditable='true']",+ "[data-reader-no-page-turn]",+].join(",");++export function allowsEpubPageTurn(target: EventTarget | null): boolean {+ const element = target as Element | null;+ if (!element || typeof element.closest !== "function") return false;+ return !element.closest(INTERACTIVE_SELECTOR);+}++export function resolveEpubPageTurnSwipe(+ startX: number,+ startY: number,+ endX: number,+ endY: number,+): EpubPageTurnDirection | null {+ const dx = endX - startX;+ const dy = endY - startY;+ if (Math.abs(dx) < EPUB_PAGE_TURN_MIN_DRAG_PX) return null;+ if (Math.abs(dx) <= Math.abs(dy) * EPUB_PAGE_TURN_HORIZONTAL_RATIO)+ return null;+ return dx < 0 ? "next" : "previous";+}++export function directionForEpubLayout(+ direction: EpubPageTurnDirection,+ isRtl: boolean,+): EpubPageTurnDirection {+ if (!isRtl) return direction;+ return direction === "next" ? "previous" : "next";+}++export function hrefKey(href: string): string {+ const withoutFragment = (href || "").split("#", 1)[0];+ try {+ return decodeURIComponent(withoutFragment).replace(/^\.\//, "");+ } catch {+ return withoutFragment.replace(/^\.\//, "");+ }+}++export function locatorForEpubHref(+ href: string,+ refs: Array<{ locator: number; source_href: string }>,+): number {+ const wanted = hrefKey(href);+ const exact = refs.find((ref) => hrefKey(ref.source_href) === wanted);+ if (exact) return exact.locator;+ const suffix = refs.find(+ (ref) =>+ hrefKey(ref.source_href).endsWith(`/${wanted}`) ||+ wanted.endsWith(`/${hrefKey(ref.source_href)}`),+ );+ return suffix?.locator ?? 0;+}diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.tsindex faa18ccee..aba46c40b 100644--- a/web/lib/reading-api.ts+++ b/web/lib/reading-api.ts@@ -11,6 +11,7 @@ import { apiFetch, apiUrl } from "@/lib/api";export type UnitKind = "page" | "chapter" | "slide" | "section";export type AnnotationKind = "highlight" | "underline" | "note";export type ExportFormat = "auto" | "pdf" | "markdown";+export type RenderMode = "text" | "pdf" | "epub";/** Palette offered by the annotation toolbar; mirrored server-side. */export const ANNOTATION_COLORS = [@@ -34,6 +35,7 @@ export interface MaterialInfo {created_at: number;/** True when the original bytes can be rendered faithfully (PDF today). */has_raw_view: boolean;+ render_mode: RenderMode;annotation_count: number;}@@ -47,6 +49,13 @@ export interface OutlineRow {export interface MaterialDetail extends MaterialInfo {outline: OutlineRow[];outline_text: string;+ unit_refs: UnitReference[];+}++export interface UnitReference {+ locator: number;+ source_href: string;+ title: string;}/**@@ -67,6 +76,7 @@ export interface AnnotationItem {quote: string;note: string;rects: NormalisedRect[];+ source_anchor: string;/** "user" or "assistant" — the model can annotate too. */author: string;created_at: number;@@ -81,6 +91,14 @@ export interface AnnotationDraft {quote?: string;note?: string;rects?: NormalisedRect[];+ source_anchor?: string;+}++export interface ReadingPosition {+ locator: number;+ source_anchor: string;+ percentage: number;+ updated_at: number;}export interface SupportedFormats {@@ -154,6 +172,29 @@ export function rawMaterialUrl(materialId: string): string {return apiUrl(`${BASE}/materials/${materialId}/raw`);}+export async function getReadingPosition(+ materialId: string,+): Promise<ReadingPosition> {+ return unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}/position`), {+ cache: "no-store",+ }),+ );+}++export async function saveReadingPosition(+ materialId: string,+ position: Pick<ReadingPosition, "locator" | "source_anchor" | "percentage">,+): Promise<ReadingPosition> {+ return unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}/position`), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(position),+ }),+ );+}+export async function listAnnotations(materialId: string,): Promise<AnnotationItem[]> {diff --git a/web/package-lock.json b/web/package-lock.jsonindex 956753632..2d112a520 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -12,6 +12,7 @@"clsx": "^2.1.1","cytoscape": "^3.33.1","docx-preview": "^0.3.7",+ "epubjs": "^0.3.93","exceljs": "^4.4.0","framer-motion": "^12.24.0","html2canvas": "^1.4.1",@@ -1994,6 +1995,16 @@"integrity": "sha512-HMwFiRujE5PjrgwHQ25+bsLJgowjGjm5Z8FVSf0N6PwgJrwxH0QxzHYDcKsTfV3wva0vzrpqMTJS2jXPr5BMEQ==","license": "MIT"},+ "node_modules/@types/localforage": {+ "version": "0.0.34",+ "resolved": "https://registry.npmjs.org/@types/localforage/-/localforage-0.0.34.tgz",+ "integrity": "sha512-tJxahnjm9dEI1X+hQSC5f2BSd/coZaqbIl1m3TCl0q9SVuC52XcXfV0XmoCU1+PmjyucuVITwoTnN8OlTbEXXA==",+ "deprecated": "This is a stub types definition for localforage (https://github.com/localForage/localForage). localforage provides its own type definitions, so you don't need @types/localforage installed!",+ "license": "MIT",+ "dependencies": {+ "localforage": "*"+ }+ },"node_modules/@types/mdast": {"version": "4.0.4","resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",@@ -2634,6 +2645,15 @@"d3-transition": "^3.0.1"}},+ "node_modules/@xmldom/xmldom": {+ "version": "0.9.12",+ "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz",+ "integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==",+ "license": "MIT",+ "engines": {+ "node": ">=14.6"+ }+ },"node_modules/acorn": {"version": "8.15.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",@@ -3642,7 +3662,6 @@"integrity": "sha512-c3Q2VVkGAUyupsjRnaNX6u8Dq2vAdzm9iuPj5FW0fRxzlxgq9Q39MDq10IvmQSpLgHQNyQzQmOo6bgGHmH3NNg==","hasInstallScript": true,"license": "MIT",- "optional": true,"funding": {"type": "opencollective","url": "https://opencollective.com/core-js"@@ -3779,6 +3798,19 @@"integrity": "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==","license": "MIT"},+ "node_modules/d": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/d/-/d-1.0.2.tgz",+ "integrity": "sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==",+ "license": "ISC",+ "dependencies": {+ "es5-ext": "^0.10.64",+ "type": "^2.7.2"+ },+ "engines": {+ "node": ">=0.12"+ }+ },"node_modules/d3": {"version": "7.9.0","resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz",@@ -4551,6 +4583,23 @@"url": "https://github.com/fb55/entities?sponsor=1"}},+ "node_modules/epubjs": {+ "version": "0.3.93",+ "resolved": "https://registry.npmjs.org/epubjs/-/epubjs-0.3.93.tgz",+ "integrity": "sha512-c06pNSdBxcXv3dZSbXAVLE1/pmleRhOT6mXNZo6INKmvuKpYB65MwU/lO7830czCtjIiK9i+KR+3S+p0wtljrw==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "@types/localforage": "0.0.34",+ "@xmldom/xmldom": "^0.7.5",+ "core-js": "^3.18.3",+ "event-emitter": "^0.3.5",+ "jszip": "^3.7.1",+ "localforage": "^1.10.0",+ "lodash": "^4.17.21",+ "marks-pane": "^1.0.9",+ "path-webpack": "0.0.3"+ }+ },"node_modules/es-abstract": {"version": "1.24.1","resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.1.tgz",@@ -4728,6 +4777,46 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/es5-ext": {+ "version": "0.10.64",+ "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.64.tgz",+ "integrity": "sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==",+ "hasInstallScript": true,+ "license": "ISC",+ "dependencies": {+ "es6-iterator": "^2.0.3",+ "es6-symbol": "^3.1.3",+ "esniff": "^2.0.1",+ "next-tick": "^1.1.0"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/es6-iterator": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz",+ "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==",+ "license": "MIT",+ "dependencies": {+ "d": "1",+ "es5-ext": "^0.10.35",+ "es6-symbol": "^3.1.1"+ }+ },+ "node_modules/es6-symbol": {+ "version": "3.1.4",+ "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.4.tgz",+ "integrity": "sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==",+ "license": "ISC",+ "dependencies": {+ "d": "^1.0.2",+ "ext": "^1.7.0"+ },+ "engines": {+ "node": ">=0.12"+ }+ },"node_modules/escalade": {"version": "3.2.0","resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",@@ -5111,6 +5200,21 @@"url": "https://opencollective.com/eslint"}},+ "node_modules/esniff": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/esniff/-/esniff-2.0.1.tgz",+ "integrity": "sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==",+ "license": "ISC",+ "dependencies": {+ "d": "^1.0.1",+ "es5-ext": "^0.10.62",+ "event-emitter": "^0.3.5",+ "type": "^2.7.2"+ },+ "engines": {+ "node": ">=0.10"+ }+ },"node_modules/espree": {"version": "10.4.0","resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",@@ -5185,6 +5289,16 @@"node": ">=0.10.0"}},+ "node_modules/event-emitter": {+ "version": "0.3.5",+ "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz",+ "integrity": "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==",+ "license": "MIT",+ "dependencies": {+ "d": "1",+ "es5-ext": "~0.10.14"+ }+ },"node_modules/exceljs": {"version": "4.4.0","resolved": "https://registry.npmjs.org/exceljs/-/exceljs-4.4.0.tgz",@@ -5215,6 +5329,15 @@"uuid": "dist/bin/uuid"}},+ "node_modules/ext": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz",+ "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==",+ "license": "ISC",+ "dependencies": {+ "type": "^2.7.2"+ }+ },"node_modules/extend": {"version": "3.0.2","resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",@@ -5470,6 +5593,7 @@"version": "2.3.2","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz","integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "dev": true,"hasInstallScript": true,"license": "MIT","optional": true,@@ -7116,6 +7240,24 @@"integrity": "sha512-3mk/Zag0+IJxeDrxSgaDPy4zZ3w05PRZeJNnlWhzFz5OkX49J4krc+A8X2d2M69vGMBEX0uyl8M+W+8gH+kBqQ==","license": "ISC"},+ "node_modules/localforage": {+ "version": "1.10.0",+ "resolved": "https://registry.npmjs.org/localforage/-/localforage-1.10.0.tgz",+ "integrity": "sha512-14/H1aX7hzBBmmh7sGPd+AOMkkIrHM3Z1PAyGgZigA1H1p5O5ANnMyWzvpAETtG68/dC4pC0ncy3+PPGzXZHPg==",+ "license": "Apache-2.0",+ "dependencies": {+ "lie": "3.1.1"+ }+ },+ "node_modules/localforage/node_modules/lie": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/lie/-/lie-3.1.1.tgz",+ "integrity": "sha512-RiNhHysUjhrDQntfYSfY4MU24coXXdEOgw9WGcKHNeEwffDYbF//u87M1EWaMGzuFoSbqW0C9C6lEEhDOAswfw==",+ "license": "MIT",+ "dependencies": {+ "immediate": "~3.0.5"+ }+ },"node_modules/locate-path": {"version": "6.0.0","resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",@@ -7132,6 +7274,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/lodash": {+ "version": "4.18.1",+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",+ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",+ "license": "MIT"+ },"node_modules/lodash-es": {"version": "4.18.1","resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz",@@ -7302,6 +7450,12 @@"node": ">= 20"}},+ "node_modules/marks-pane": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/marks-pane/-/marks-pane-1.0.9.tgz",+ "integrity": "sha512-Ahs4oeG90tbdPWwAJkAAoHg2lRR8lAs9mZXETNPO9hYg3AkjUJBKi1NQ4aaIQZVGrig7c/3NUV1jANl8rFTeMg==",+ "license": "MIT"+ },"node_modules/math-intrinsics": {"version": "1.1.0","resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",@@ -8420,6 +8574,12 @@}}},+ "node_modules/next-tick": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz",+ "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==",+ "license": "ISC"+ },"node_modules/next/node_modules/postcss": {"version": "8.4.31","resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",@@ -8778,6 +8938,12 @@"dev": true,"license": "MIT"},+ "node_modules/path-webpack": {+ "version": "0.0.3",+ "resolved": "https://registry.npmjs.org/path-webpack/-/path-webpack-0.0.3.tgz",+ "integrity": "sha512-AmeDxedoo5svf7aB3FYqSAKqMxys014lVKBzy1o/5vv9CtU7U4wgGWL1dA2o6MOzcD53ScN4Jmiq6VbtLz1vIQ==",+ "license": "MIT"+ },"node_modules/pathe": {"version": "2.0.3","resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",@@ -10608,6 +10774,12 @@"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==","license": "0BSD"},+ "node_modules/type": {+ "version": "2.7.3",+ "resolved": "https://registry.npmjs.org/type/-/type-2.7.3.tgz",+ "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==",+ "license": "ISC"+ },"node_modules/type-check": {"version": "0.4.0","resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",diff --git a/web/package.json b/web/package.jsonindex e163b4464..34ccc8e2f 100644--- a/web/package.json+++ b/web/package.json@@ -25,6 +25,7 @@"clsx": "^2.1.1","cytoscape": "^3.33.1","docx-preview": "^0.3.7",+ "epubjs": "^0.3.93","exceljs": "^4.4.0","framer-motion": "^12.24.0","html2canvas": "^1.4.1",@@ -46,6 +47,11 @@"remark-math": "^6.0.0","tailwind-merge": "^3.4.0"},+ "overrides": {+ "epubjs": {+ "@xmldom/xmldom": "^0.9.12"+ }+ },"devDependencies": {"@playwright/test": "^1.53.2","@types/node": "^25",diff --git a/web/playwright.config.ts b/web/playwright.config.tsindex d77bf44ec..ef63eeaad 100644--- a/web/playwright.config.ts+++ b/web/playwright.config.ts@@ -21,7 +21,18 @@ export default defineConfig({{name: "ui-audit",testMatch: "**/*.audit.ts",+ testIgnore: "**/epub-reader.audit.ts",use: { ...devices["Desktop Chrome"] },},+ {+ name: "epub-reader-chromium",+ testMatch: "**/epub-reader.audit.ts",+ use: { ...devices["Desktop Chrome"] },+ },+ {+ name: "epub-reader-webkit",+ testMatch: "**/epub-reader.audit.ts",+ use: { ...devices["iPhone 13"] },+ },],});diff --git a/web/tests/epub-page-turn.test.ts b/web/tests/epub-page-turn.test.tsnew file mode 100644index 000000000..330390e09--- /dev/null+++ b/web/tests/epub-page-turn.test.ts@@ -0,0 +1,33 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ directionForEpubLayout,+ hrefKey,+ locatorForEpubHref,+ resolveEpubPageTurnSwipe,+} from "../lib/epub-page-turn";++test("horizontal swipes turn pages but vertical scrolls do not", () => {+ assert.equal(resolveEpubPageTurnSwipe(200, 100, 100, 105), "next");+ assert.equal(resolveEpubPageTurnSwipe(100, 100, 200, 105), "previous");+ assert.equal(resolveEpubPageTurnSwipe(100, 100, 140, 100), null);+ assert.equal(resolveEpubPageTurnSwipe(100, 100, 160, 180), null);+});++test("RTL reverses physical rendition direction", () => {+ assert.equal(directionForEpubLayout("next", false), "next");+ assert.equal(directionForEpubLayout("next", true), "previous");+ assert.equal(directionForEpubLayout("previous", true), "next");+});++test("source hrefs map to the server locator despite encoding and base paths", () => {+ const refs = [+ { locator: 1, source_href: "OEBPS/chapters/one.xhtml" },+ { locator: 2, source_href: "OEBPS/chapters/two%20words.xhtml" },+ ];+ assert.equal(locatorForEpubHref("OEBPS/chapters/one.xhtml#p1", refs), 1);+ assert.equal(locatorForEpubHref("chapters/two words.xhtml", refs), 2);+ assert.equal(locatorForEpubHref("missing.xhtml", refs), 0);+ assert.equal(hrefKey("./chapter.xhtml#here"), "chapter.xhtml");+});diff --git a/web/tests/epub-reader.audit.ts b/web/tests/epub-reader.audit.tsnew file mode 100644index 000000000..739ae8661--- /dev/null+++ b/web/tests/epub-reader.audit.ts@@ -0,0 +1,93 @@+import { expect, test } from "@playwright/test";+import JSZip from "jszip";++async function illustratedEpub(): Promise<Buffer> {+ const zip = new JSZip();+ zip.file("mimetype", "application/epub+zip", { compression: "STORE" });+ zip.file(+ "META-INF/container.xml",+ "<?xml version='1.0'?><container xmlns='urn:oasis:names:tc:opendocument:xmlns:container'><rootfiles><rootfile full-path='OPS/book.opf' media-type='application/oebps-package+xml'/></rootfiles></container>",+ );+ zip.file(+ "OPS/book.opf",+ "<?xml version='1.0'?><package xmlns='http://www.idpf.org/2007/opf' xmlns:dc='http://purl.org/dc/elements/1.1/' version='3.0' unique-identifier='book-id'><metadata><dc:identifier id='book-id'>urn:uuid:deeptutor-reader-test</dc:identifier><dc:title>Faithful reader</dc:title><dc:language>en</dc:language></metadata><manifest><item id='nav' href='nav.xhtml' media-type='application/xhtml+xml' properties='nav'/><item id='one' href='one.xhtml' media-type='application/xhtml+xml'/><item id='two' href='two.xhtml' media-type='application/xhtml+xml'/><item id='dot' href='dot.png' media-type='image/png'/></manifest><spine><itemref idref='one'/><itemref idref='two'/></spine></package>",+ );+ zip.file(+ "OPS/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='one.xhtml'>Illustrated chapter</a></li><li><a href='two.xhtml'>Second chapter</a></li></ol></nav></body></html>",+ );+ 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>",+ );+ zip.file(+ "OPS/two.xhtml",+ "<html xmlns='http://www.w3.org/1999/xhtml'><head><title>Second chapter</title></head><body><h1>Second chapter</h1><p>Keyboard navigation reached the second spine item.</p></body></html>",+ );+ zip.file(+ "OPS/dot.png",+ Buffer.from(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",+ "base64",+ ),+ );+ return zip.generateAsync({ type: "nodebuffer", mimeType: "application/epub+zip" });+}++test("faithfully renders EPUB resources, navigates, and restores its CFI", async ({+ page,+}, testInfo) => {+ const filename = `faithful-reader-${Date.now()}.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 expect(fileInput).toBeAttached();+ await fileInput.setInputFiles({+ name: filename,+ mimeType: "application/epub+zip",+ buffer: await illustratedEpub(),+ });+ const readerFrame = page.locator("iframe").contentFrame();+ await expect(+ readerFrame.getByRole("heading", { name: "Illustrated chapter" }),+ ).toBeVisible();+ await expect(readerFrame.getByAltText("source illustration")).toBeVisible();++ const turnForward =+ 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 page.keyboard.press("ArrowRight");+ };+ for (let attempt = 0; attempt < 4; attempt += 1) {+ await turnForward();+ if (+ await readerFrame.getByRole("heading", { name: "Second chapter" }).isVisible()+ )+ break;+ await page.waitForTimeout(150);+ }+ await expect(readerFrame.getByRole("heading", { name: "Second chapter" })).toBeVisible();+ await expect+ .poll(async () => {+ const response = await page.request.get("/api/v1/reading/materials");+ const rows = (await response.json()) as Array<{+ material_id: string;+ filename: string;+ }>;+ const material = rows.find((row) => row.filename === filename);+ if (!material) return 0;+ const position = await page.request.get(+ `/api/v1/reading/materials/${material.material_id}/position`,+ );+ return ((await position.json()) as { locator: number }).locator;+ })+ .toBe(2);++ await page.reload();+ await page.getByRole("button", { name: new RegExp(filename, "i") }).click();+ const restoredFrame = page.locator("iframe").contentFrame();+ await expect(restoredFrame.getByRole("heading", { name: "Second chapter" })).toBeVisible();+});