DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(reading): enforce EPUB display preferences across content (#1447)
Bingxi Zhao (Frank)92486051952e
diff --git a/web/components/reading/EpubDocumentView.tsx b/web/components/reading/EpubDocumentView.tsxindex 45f314ede..ffc433c68 100644--- a/web/components/reading/EpubDocumentView.tsx+++ b/web/components/reading/EpubDocumentView.tsx@@ -67,14 +67,10 @@ type EpubRendition = {};};themes: {- register: (- name: string,- rules: Record<string, Record<string, string>>,- ) => void;+ registerCss: (name: string, css: string) => void;select: (name: string) => void;fontSize: (size: string) => void;override: (name: string, value: string, priority?: boolean) => void;- removeOverride: (name: string) => void;};};@@ -110,14 +106,29 @@ function applyEpubDisplayPreferences(rendition: EpubRendition,preferences: ReaderDisplayPreferences,) {- rendition.themes.fontSize(`${preferences.fontSize}px`);- rendition.themes.override(- "font-family",- preferences.serif- ? "ui-serif, Georgia, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', serif"- : "ui-sans-serif, system-ui, -apple-system, 'PingFang SC', sans-serif",- true,+ const fontFamily = preferences.serif+ ? "ui-serif, Georgia, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', serif"+ : "ui-sans-serif, system-ui, -apple-system, 'PingFang SC', sans-serif";+ const paper =+ preferences.readerTheme === "sepia"+ ? { background: "#f4ecd8", color: "#473c2c" }+ : preferences.readerTheme === "night"+ ? { background: "#16181d", color: "#e8e5df" }+ : null;++ // The theme stylesheet is replaced on each preference change. EPUB+ // publishers often set font and ink directly on paragraphs or spans; a+ // body-only epub.js override cannot beat those declarations (#1447).+ rendition.themes.registerCss(+ "deeptutor",+ `body { font-family: ${fontFamily} !important; font-size: ${preferences.fontSize}px !important; ${paper ? `background-color: ${paper.background} !important; color: ${paper.color} !important;` : ""} }+ body :is(p, span, div, li, blockquote) { font-family: ${fontFamily} !important; font-size: inherit !important; ${paper ? `color: ${paper.color} !important;` : ""} }+ body :is(h1, h2, h3, h4, h5, h6) { font-family: ${fontFamily} !important; ${paper ? `color: ${paper.color} !important;` : ""} }+ body * { vertical-align: baseline; }+ img { max-width: 100% !important; max-height: 85vh !important; height: auto !important; object-fit: contain !important; }`,);+ rendition.themes.select("deeptutor");+ rendition.themes.fontSize(`${preferences.fontSize}px`);// epub.js sets column-width but leaves column-count automatic. A wide pane// can fit a third visible column after the sidebar collapses (#1447).rendition.themes.override(@@ -125,19 +136,6 @@ function applyEpubDisplayPreferences(preferences.spreadMode === "none" ? "1" : "2",true,);- const paper =- preferences.readerTheme === "sepia"- ? { background: "#f4ecd8", color: "#473c2c" }- : preferences.readerTheme === "night"- ? { background: "#16181d", color: "#e8e5df" }- : null;- if (paper) {- rendition.themes.override("background-color", paper.background, true);- rendition.themes.override("color", paper.color, true);- } else {- rendition.themes.removeOverride("background-color");- rendition.themes.removeOverride("color");- }}export interface EpubDocumentViewProps {@@ -436,16 +434,6 @@ export function EpubDocumentView({});renditionRef.current = rendition;activeSpreadRef.current = preferencesRef.current.spreadMode;- rendition.themes.register("deeptutor", {- "body *": { "vertical-align": "baseline" },- img: {- "max-width": "100%",- "max-height": "85vh",- height: "auto",- "object-fit": "contain",- },- });- rendition.themes.select("deeptutor");applyEpubDisplayPreferences(rendition, preferencesRef.current);rendition.on("relocated", onRelocated);rendition.on("selected", onSelected);@@ -484,6 +472,8 @@ export function EpubDocumentView({cancelled = true;if (saveTimerRef.current) clearTimeout(saveTimerRef.current);if (relayoutTimerRef.current) clearTimeout(relayoutTimerRef.current);+ relayoutTimerRef.current = null;+ relayoutAnchorRef.current = undefined;if (rendition) {rendition.off("relocated", onRelocated);rendition.off("selected", onSelected);diff --git a/web/tests/epub-display-preferences.spec.tsx b/web/tests/epub-display-preferences.spec.tsxindex b1763217a..64d5e73b5 100644--- a/web/tests/epub-display-preferences.spec.tsx+++ b/web/tests/epub-display-preferences.spec.tsx@@ -1,5 +1,5 @@import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { beforeEach, expect, it, vi } from "vitest";+import { afterEach, beforeEach, expect, it, vi } from "vitest";import { initI18n } from "@/i18n/init";@@ -7,7 +7,7 @@ initI18n("en");const fixture = vi.hoisted(() => {const rendition = {- display: vi.fn(async () => undefined),+ display: vi.fn(async (_target?: string) => undefined),currentLocation: vi.fn(() => ({ start: { cfi: "epubcfi(/6/2)" } })),next: vi.fn(async () => undefined),prev: vi.fn(async () => undefined),@@ -19,11 +19,10 @@ const fixture = vi.hoisted(() => {annotations: { highlight: vi.fn(), remove: vi.fn() },hooks: { content: { register: vi.fn() } },themes: {- register: vi.fn(),+ registerCss: vi.fn(),select: vi.fn(),fontSize: vi.fn(),override: vi.fn(),- removeOverride: vi.fn(),},};return {@@ -54,7 +53,14 @@ vi.mock("@/lib/reading-api", () => ({import { EpubDocumentView } from "@/components/reading/EpubDocumentView";+let publisherParagraph: HTMLParagraphElement | null = null;+let themeStyle: HTMLStyleElement | null = null;+beforeEach(() => {+ fixture.rendition.currentLocation.mockReturnValue({+ start: { cfi: "epubcfi(/6/2)" },+ });+ fixture.rendition.themes.registerCss.mockReset();vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({x: 0,y: 0,@@ -68,6 +74,13 @@ beforeEach(() => {});});+afterEach(() => {+ publisherParagraph?.remove();+ themeStyle?.remove();+ publisherParagraph = null;+ themeStyle = null;+});+it("opens EPUB in single-page mode and keeps the CFI when switching spreads", async () => {render(<EpubDocumentView@@ -97,7 +110,18 @@ it("opens EPUB in single-page mode and keeps the CFI when switching spreads", as.toMatchObject({ spreadMode: "auto" });});-it("applies saved typography and theme to EPUB content", async () => {+it("overrides a publisher's explicit paragraph and span ink and font", async () => {+ publisherParagraph = document.createElement("p");+ publisherParagraph.style.cssText =+ "font-family: monospace; font-size: 11px; color: #000";+ publisherParagraph.innerHTML =+ '<span style="font-family: monospace; font-size: 11px; color: #000">Publisher text</span>';+ document.body.appendChild(publisherParagraph);+ themeStyle = document.createElement("style");+ document.head.appendChild(themeStyle);+ fixture.rendition.themes.registerCss.mockImplementation((_name, css) => {+ themeStyle!.textContent = css;+ });localStorage.setItem("dt.reader.textPreferences",JSON.stringify({ fontSize: 23, serif: false, readerTheme: "night", spreadMode: "auto" }),@@ -119,18 +143,57 @@ it("applies saved typography and theme to EPUB content", async () => {expect.objectContaining({ spread: "auto" }),),);- expect(fixture.rendition.themes.fontSize).toHaveBeenCalledWith("23px");- expect(fixture.rendition.themes.override).toHaveBeenCalledWith(- "background-color",- "#16181d",- true,+ const publisherSpan = publisherParagraph.querySelector("span")!;+ await waitFor(() =>+ expect(getComputedStyle(publisherSpan).color).toBe("rgb(232, 229, 223)"),);+ expect(getComputedStyle(publisherParagraph).fontFamily).toContain("ui-sans-serif");+ expect(getComputedStyle(publisherSpan).fontFamily).toContain("ui-sans-serif");+ expect(getComputedStyle(publisherSpan).fontSize).toBe("23px");+ expect(fixture.rendition.themes.fontSize).toHaveBeenCalledWith("23px");fireEvent.click(screen.getByRole("button", { name: "Reset reading display" }));await waitFor(() =>- expect(fixture.rendition.themes.removeOverride).toHaveBeenCalledWith(- "background-color",- ),+ expect(getComputedStyle(publisherSpan).color).toBe("rgb(0, 0, 0)"),);expect(JSON.parse(localStorage.getItem("dt.reader.textPreferences") || "{}")).toMatchObject({ fontSize: 17, readerTheme: "auto", spreadMode: "none" });});++it("drops a previous book's pending CFI before the next book relayout", async () => {+ const onSelection = () => undefined;+ const props = {+ unitCount: 1,+ unitRefs: [],+ annotations: [],+ jump: null,+ onSelection,+ };+ fixture.rendition.currentLocation.mockReturnValue({+ start: { cfi: "epubcfi(/6/old-book)" },+ });+ const { rerender } = render(+ <EpubDocumentView materialId="old-book" {...props} />,+ );+ await waitFor(() => expect(fixture.renderTo).toHaveBeenCalledTimes(1));+ fireEvent.click(screen.getByRole("button", { name: "Switch to two-page spread" }));+ await waitFor(() => expect(fixture.rendition.spread).toHaveBeenCalledWith("auto"));+ const oldCfiDisplays = fixture.rendition.display.mock.calls.filter(+ ([cfi]) => cfi === "epubcfi(/6/old-book)",+ ).length;++ fixture.rendition.currentLocation.mockReturnValue({+ start: { cfi: "epubcfi(/6/new-book)" },+ });+ rerender(<EpubDocumentView materialId="new-book" {...props} />);+ await waitFor(() => expect(fixture.renderTo).toHaveBeenCalledTimes(2));+ await waitFor(() =>+ expect(fixture.rendition.display).toHaveBeenLastCalledWith(+ "epubcfi(/6/new-book)",+ ),+ );+ expect(+ fixture.rendition.display.mock.calls.filter(+ ([cfi]) => cfi === "epubcfi(/6/old-book)",+ ),+ ).toHaveLength(oldCfiDisplays);+});