Skip to content

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

fix(book): read long chapters sequentially before turning pages

XZHc59b9547d726
diff --git a/web/app/(workspace)/book/components/PageReader.tsx b/web/app/(workspace)/book/components/PageReader.tsx
index adf3d8d76..3767b87bf 100644
--- a/web/app/(workspace)/book/components/PageReader.tsx
+++ b/web/app/(workspace)/book/components/PageReader.tsx
@@ -15,6 +15,13 @@ import {
} from "lucide-react";
import { useTranslation } from "react-i18next";
import type { Block, BlockType, Page, QuizAttempt } from "@/lib/book-types";
+import {
+ SCROLL_EDGE_TOLERANCE_PX,
+ chapterReadingPercent,
+ sequentialReadTarget,
+ type ChapterScrollPlacement,
+ type SequentialReadDirection,
+} from "@/lib/book-reader-navigation";
import BlockRenderer from "./blocks/BlockRenderer";
import type { QuizAttemptArgs } from "./blocks/QuizBlock";
import PageOutlineNav from "./PageOutlineNav";
@@ -103,6 +110,11 @@ export default function PageReader({
const [scrollContainer, setScrollContainer] = useState<HTMLDivElement | null>(
null,
);
+ const [readingPercent, setReadingPercent] = useState(0);
+ const [chapterHasScroll, setChapterHasScroll] = useState(false);
+ const pendingScrollPlacementRef = useRef<ChapterScrollPlacement>("start");
+ const pendingScrollPlacementPageIdRef = useRef<string | null>(null);
+ const lastSeenPageIdRef = useRef<string | null>(null);
// ── Collapsible header ──────────────────────────────────────────────
// Default expanded; collapse on user-initiated scroll-down past threshold;
@@ -118,12 +130,87 @@ export default function PageReader({
lastScrollTopRef.current = 0;
}, [page?.id]);
+ const updateReadingProgress = useCallback(() => {
+ if (!scrollContainer) {
+ setReadingPercent(0);
+ setChapterHasScroll(false);
+ return;
+ }
+
+ setReadingPercent(
+ chapterReadingPercent({
+ scrollTop: scrollContainer.scrollTop,
+ scrollHeight: scrollContainer.scrollHeight,
+ clientHeight: scrollContainer.clientHeight,
+ }),
+ );
+ setChapterHasScroll(
+ scrollContainer.scrollHeight - scrollContainer.clientHeight >
+ SCROLL_EDGE_TOLERANCE_PX,
+ );
+ }, [scrollContainer]);
+
+ // Chapter summaries hydrate blocks asynchronously. A requested "end"
+ // placement must therefore follow the target page id and wait for its real
+ // content instead of using the old or empty content height.
+ useEffect(() => {
+ if (!scrollContainer || !page) return;
+
+ const isNewPage = lastSeenPageIdRef.current !== page.id;
+ lastSeenPageIdRef.current = page.id;
+ const requestedPageId = pendingScrollPlacementPageIdRef.current;
+ const pendingMatchesPage = requestedPageId === page.id;
+ const placement = pendingMatchesPage
+ ? pendingScrollPlacementRef.current
+ : "start";
+ if (!pendingMatchesPage) {
+ pendingScrollPlacementRef.current = "start";
+ pendingScrollPlacementPageIdRef.current = null;
+ }
+
+ // Content refreshes for the current chapter must never move an active
+ // reader. Only a page transition or an explicit pending placement may.
+ if (!isNewPage && !pendingMatchesPage) return;
+
+ const waitingForContent =
+ page.blocks.length === 0 && (loading || (page.block_count ?? 0) > 0);
+ // "Start" is safe on an empty summary and keeps its old scroll position
+ // from surviving into the hydrated chapter. "End" must wait for content.
+ if (waitingForContent && placement === "end") return;
+
+ pendingScrollPlacementRef.current = "start";
+ pendingScrollPlacementPageIdRef.current = null;
+ const pendingFrames: number[] = [];
+ pendingFrames.push(
+ window.requestAnimationFrame(() => {
+ pendingFrames.push(
+ window.requestAnimationFrame(() => {
+ scrollContainer.scrollTop =
+ placement === "end" ? scrollContainer.scrollHeight : 0;
+ updateReadingProgress();
+ }),
+ );
+ }),
+ );
+
+ return () => {
+ for (const frame of pendingFrames) {
+ window.cancelAnimationFrame(frame);
+ }
+ };
+ }, [scrollContainer, page, loading, updateReadingProgress]);
+
+ useEffect(() => {
+ updateReadingProgress();
+ }, [updateReadingProgress, page?.id, page?.blocks.length, loading]);
+
useEffect(() => {
if (!scrollContainer) return;
const handler = () => {
const top = scrollContainer.scrollTop;
const last = lastScrollTopRef.current;
lastScrollTopRef.current = top;
+ updateReadingProgress();
// Snap back to expanded when user scrolls all the way to the top,
// even if they previously toggled manually.
if (top <= 8) {
@@ -139,7 +226,7 @@ export default function PageReader({
};
scrollContainer.addEventListener("scroll", handler, { passive: true });
return () => scrollContainer.removeEventListener("scroll", handler);
- }, [scrollContainer, userToggled]);
+ }, [scrollContainer, userToggled, updateReadingProgress]);
const normalizeText = useCallback((value: string): string => {
return (value || "").replace(/\s+/g, " ").trim();
@@ -199,8 +286,50 @@ export default function PageReader({
selection.removeAllRanges();
}, [onCaptureSelection, normalizeText, page, t]);
+ const navigateSequentially = useCallback(
+ (direction: SequentialReadDirection): boolean => {
+ // A newly selected chapter may still be compiling. Keep arrows inert in
+ // that state so they cannot skip a chapter before its height is known.
+ if (loading && page?.blocks.length === 0) return false;
+
+ if (
+ !scrollContainer ||
+ scrollContainer.clientHeight <= SCROLL_EDGE_TOLERANCE_PX
+ ) {
+ return false;
+ }
+
+ const target = sequentialReadTarget(scrollContainer, direction);
+ if (target !== null) {
+ scrollContainer?.scrollTo({ top: target });
+ return true;
+ }
+
+ if (direction === "previous" && previousPage) {
+ pendingScrollPlacementRef.current = "end";
+ pendingScrollPlacementPageIdRef.current = previousPage.id;
+ onNavigate?.(previousPage.id);
+ return true;
+ }
+ if (direction === "next" && nextPage) {
+ pendingScrollPlacementRef.current = "start";
+ pendingScrollPlacementPageIdRef.current = nextPage.id;
+ onNavigate?.(nextPage.id);
+ return true;
+ }
+ return false;
+ },
+ [
+ loading,
+ nextPage,
+ onNavigate,
+ page?.blocks.length,
+ previousPage,
+ scrollContainer,
+ ],
+ );
+
useEffect(() => {
- if (!onNavigate) return;
const handler = (event: KeyboardEvent) => {
if (event.metaKey || event.ctrlKey || event.altKey) return;
const target = event.target as HTMLElement | null;
@@ -212,15 +341,15 @@ export default function PageReader({
) {
return;
}
- if (event.key === "ArrowLeft" && previousPage) {
- onNavigate(previousPage.id);
- } else if (event.key === "ArrowRight" && nextPage) {
- onNavigate(nextPage.id);
+ if (event.key === "ArrowLeft") {
+ if (navigateSequentially("previous")) event.preventDefault();
+ } else if (event.key === "ArrowRight") {
+ if (navigateSequentially("next")) event.preventDefault();
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
- }, [onNavigate, previousPage, nextPage]);
+ }, [navigateSequentially]);
if (!page) {
return (
@@ -330,6 +459,7 @@ export default function PageReader({
<div
ref={setScrollContainer}
+ data-testid="chapter-scroll-container"
className="flex-1 overflow-y-auto px-8 py-8"
>
{loading && page.blocks.length === 0 ? (
@@ -491,9 +621,29 @@ export default function PageReader({
label={t("Previous chapter")}
onNavigate={onNavigate}
/>
- <span className="shrink-0 text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]/70">
- {t("← / → to turn pages")}
- </span>
+ <div className="flex min-w-0 shrink-0 flex-col items-center gap-1">
+ <span className="text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]/70">
+ {t("← / → to turn pages")}
+ </span>
+ {chapterHasScroll && (
+ <div className="flex items-center gap-2">
+ <span className="text-[10px] text-[var(--muted-foreground)]/70">
+ {t("Chapter progress: {{percent}}%", {
+ percent: readingPercent,
+ })}
+ </span>
+ <progress
+ data-testid="chapter-progress"
+ className="h-1.5 w-24 accent-[var(--primary)]"
+ max={100}
+ value={readingPercent}
+ aria-label={t("Chapter progress: {{percent}}%", {
+ percent: readingPercent,
+ })}
+ />
+ </div>
+ )}
+ </div>
<NavButton
page={nextPage}
direction="next"
diff --git a/web/lib/book-reader-navigation.ts b/web/lib/book-reader-navigation.ts
new file mode 100644
index 000000000..35e225656
--- /dev/null
+++ b/web/lib/book-reader-navigation.ts
@@ -0,0 +1,46 @@
+export type SequentialReadDirection = "previous" | "next";
+export type ChapterScrollPlacement = "start" | "end";
+
+/** Sub-pixel layout differences must not look like an unread page. */
+export const SCROLL_EDGE_TOLERANCE_PX = 2;
+
+interface ScrollMetrics {
+ scrollTop: number;
+ scrollHeight: number;
+ clientHeight: number;
+}
+
+/**
+ * Return the next in-chapter reading position, or null at that edge.
+ *
+ * A screenful minus a little overlap keeps lines from being split exactly at
+ * the viewport boundary. The function is pure so browser behavior can be tested
+ * without constructing React or DOM fixtures.
+ */
+export function sequentialReadTarget(
+ metrics: ScrollMetrics,
+ direction: SequentialReadDirection,
+): number | null {
+ // A detached or hidden reader can report a zero-height client box. It has
+ // no readable screenfuls, so let the caller keep its current position.
+ if (metrics.clientHeight <= SCROLL_EDGE_TOLERANCE_PX) return null;
+ const maxScrollTop = Math.max(0, metrics.scrollHeight - metrics.clientHeight);
+ if (maxScrollTop <= SCROLL_EDGE_TOLERANCE_PX) return null;
+
+ const step = Math.max(metrics.clientHeight * 0.9, SCROLL_EDGE_TOLERANCE_PX + 1);
+ if (direction === "next") {
+ const remaining = maxScrollTop - metrics.scrollTop;
+ if (remaining <= SCROLL_EDGE_TOLERANCE_PX) return null;
+ return Math.min(metrics.scrollTop + step, maxScrollTop);
+ }
+
+ if (metrics.scrollTop <= SCROLL_EDGE_TOLERANCE_PX) return null;
+ return Math.max(metrics.scrollTop - step, 0);
+}
+
+export function chapterReadingPercent(metrics: ScrollMetrics): number {
+ const maxScrollTop = Math.max(0, metrics.scrollHeight - metrics.clientHeight);
+ if (maxScrollTop <= SCROLL_EDGE_TOLERANCE_PX) return 0;
+ const percent = Math.round((metrics.scrollTop / maxScrollTop) * 100);
+ return Math.min(100, Math.max(0, percent));
+}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 10023c40c..ba5e1e40f 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -3105,7 +3105,8 @@
"Unread": "Unread",
"Bookmark this chapter": "Bookmark this chapter",
"Remove bookmark": "Remove bookmark",
- "← / → to turn pages": "← / → to turn pages",
+ "← / → to turn pages": "← / → to read, then turn pages",
+ "Chapter progress: {{percent}}%": "Chapter progress: {{percent}}%",
"Edit text": "Edit text",
"Edit note": "Edit note",
"Empty note — click to start writing your own annotation.": "Empty note — click to start writing your own annotation.",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index f3343d60f..17624414f 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -3105,7 +3105,8 @@
"Unread": "未读",
"Bookmark this chapter": "收藏本章",
"Remove bookmark": "取消收藏",
- "← / → to turn pages": "← / → 翻页",
+ "← / → to turn pages": "← / → 先阅读再翻页",
+ "Chapter progress: {{percent}}%": "本章进度:{{percent}}%",
"Edit text": "编辑正文",
"Edit note": "编辑笔记",
"Empty note — click to start writing your own annotation.": "空笔记——点击开始写下你的批注。",
diff --git a/web/tests/book-reader-navigation.test.ts b/web/tests/book-reader-navigation.test.ts
new file mode 100644
index 000000000..30744242e
--- /dev/null
+++ b/web/tests/book-reader-navigation.test.ts
@@ -0,0 +1,104 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ chapterReadingPercent,
+ sequentialReadTarget,
+} from "../lib/book-reader-navigation";
+
+test("long chapters advance by one readable screen with overlap", () => {
+ assert.equal(
+ sequentialReadTarget(
+ { scrollTop: 0, scrollHeight: 3000, clientHeight: 600 },
+ "next",
+ ),
+ 540,
+ );
+});
+
+test("long chapters retreat by one readable screen with overlap", () => {
+ assert.equal(
+ sequentialReadTarget(
+ { scrollTop: 700, scrollHeight: 3000, clientHeight: 600 },
+ "previous",
+ ),
+ 160,
+ );
+});
+
+test("scroll targets clamp at chapter boundaries", () => {
+ assert.equal(
+ sequentialReadTarget(
+ { scrollTop: 2_300, scrollHeight: 3_000, clientHeight: 600 },
+ "next",
+ ),
+ 2_400,
+ );
+ assert.equal(
+ sequentialReadTarget(
+ { scrollTop: 300, scrollHeight: 3_000, clientHeight: 600 },
+ "previous",
+ ),
+ 0,
+ );
+});
+
+test("chapter edges and non-scrolling chapters request a page turn", () => {
+ const atStart = { scrollTop: 0, scrollHeight: 3_000, clientHeight: 600 };
+ const atEnd = { scrollTop: 2_400, scrollHeight: 3_000, clientHeight: 600 };
+ const withoutScroll = {
+ scrollTop: 0,
+ scrollHeight: 600,
+ clientHeight: 600,
+ };
+
+ assert.equal(sequentialReadTarget(atStart, "previous"), null);
+ assert.equal(sequentialReadTarget(atEnd, "next"), null);
+ assert.equal(sequentialReadTarget(withoutScroll, "next"), null);
+ assert.equal(sequentialReadTarget(withoutScroll, "previous"), null);
+});
+
+test("hidden or detached readers do not fabricate scroll positions", () => {
+ assert.equal(
+ sequentialReadTarget(
+ { scrollTop: 0, scrollHeight: 3_000, clientHeight: 0 },
+ "next",
+ ),
+ null,
+ );
+ assert.equal(
+ sequentialReadTarget(
+ { scrollTop: 0, scrollHeight: 3_000, clientHeight: 1 },
+ "previous",
+ ),
+ null,
+ );
+});
+
+test("sub-pixel edges do not hide an unread remainder", () => {
+ const nearEnd = { scrollTop: 2_399, scrollHeight: 3_000, clientHeight: 600 };
+ assert.equal(sequentialReadTarget(nearEnd, "next"), null);
+ assert.equal(chapterReadingPercent(nearEnd), 100);
+});
+
+test("chapter progress is bounded and zero when scrolling is unavailable", () => {
+ assert.equal(
+ chapterReadingPercent({
+ scrollTop: 1_200,
+ scrollHeight: 3_000,
+ clientHeight: 600,
+ }),
+ 50,
+ );
+ assert.equal(
+ chapterReadingPercent({ scrollTop: -20, scrollHeight: 3_000, clientHeight: 600 }),
+ 0,
+ );
+ assert.equal(
+ chapterReadingPercent({ scrollTop: 9_999, scrollHeight: 3_000, clientHeight: 600 }),
+ 100,
+ );
+ assert.equal(
+ chapterReadingPercent({ scrollTop: 0, scrollHeight: 601, clientHeight: 600 }),
+ 0,
+ );
+});
diff --git a/web/tests/book-reader-sequential-contract.test.ts b/web/tests/book-reader-sequential-contract.test.ts
new file mode 100644
index 000000000..cedcf84ef
--- /dev/null
+++ b/web/tests/book-reader-sequential-contract.test.ts
@@ -0,0 +1,55 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import path from "node:path";
+
+const source = fs.readFileSync(
+ path.resolve(
+ process.cwd(),
+ "app/(workspace)/book/components/PageReader.tsx",
+ ),
+ "utf8",
+);
+
+test("arrow keys consume the current chapter before turning pages", () => {
+ const callbackStart = source.indexOf("const navigateSequentially");
+ const callbackEnd = source.indexOf("useEffect", callbackStart);
+ const callback = source.slice(callbackStart, callbackEnd);
+ const scrollDecision = callback.indexOf("sequentialReadTarget");
+ const pageTurn = callback.indexOf("onNavigate?.");
+
+ assert.ok(callbackStart >= 0 && callbackEnd > callbackStart);
+ assert.ok(scrollDecision >= 0 && pageTurn > scrollDecision);
+});
+
+test("turning backward lands at the end and forward lands at the start", () => {
+ const previousBranch = source.indexOf(
+ 'direction === "previous" && previousPage',
+ );
+ const nextBranch = source.indexOf('direction === "next" && nextPage');
+
+ assert.ok(previousBranch >= 0);
+ assert.ok(nextBranch > previousBranch);
+ assert.ok(
+ source.slice(previousBranch, nextBranch).includes(
+ 'pendingScrollPlacementRef.current = "end"',
+ ),
+ );
+ assert.ok(
+ source.slice(previousBranch, nextBranch).includes(
+ "pendingScrollPlacementPageIdRef.current = previousPage.id",
+ ),
+ );
+ assert.ok(
+ source.slice(nextBranch).includes(
+ 'pendingScrollPlacementRef.current = "start"',
+ ),
+ );
+});
+
+test("the reader exposes native chapter progress and keeps direct footer turns", () => {
+ assert.ok(source.includes("<progress"));
+ assert.ok(source.includes('max={100}'));
+ assert.ok(source.includes("Chapter progress: {{percent}}%"));
+ assert.ok(source.includes("onNavigate(page.id)"));
+});
diff --git a/web/tests/e2e/book-reader-sequential.audit.ts b/web/tests/e2e/book-reader-sequential.audit.ts
new file mode 100644
index 000000000..04399a313
--- /dev/null
+++ b/web/tests/e2e/book-reader-sequential.audit.ts
@@ -0,0 +1,219 @@
+import { expect, test } from "@playwright/test";
+
+const BASE_URL =
+ process.env.WEB_BASE_URL ||
+ process.env.NEXT_PUBLIC_API_BASE ||
+ "http://localhost:3000";
+
+function json(data: unknown) {
+ return {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(data),
+ };
+}
+
+test("book arrows read the current chapter before turning chapters", async ({
+ page,
+}) => {
+ const paragraph = (chapter: number, section: number) =>
+ Array.from(
+ { length: 12 },
+ (_, row) =>
+ `Chapter ${chapter}, section ${section}, row ${row + 1}: ${"deterministic browser reading content. ".repeat(16)}`,
+ ).join("\n\n");
+
+ const block = (pageId: string, section: number) => ({
+ id: `${pageId}-block-${section}`,
+ type: "text",
+ status: "ready",
+ title: `Section ${section}`,
+ params: {},
+ payload: { body: paragraph(Number(pageId.slice(-1)), section) },
+ source_anchors: [],
+ metadata: {},
+ error: "",
+ created_at: 1,
+ updated_at: 1,
+ });
+
+ const summary = (id: string, title: string, order: number) => ({
+ id,
+ book_id: "sequential-fixture",
+ chapter_id: `${id}-chapter`,
+ title,
+ learning_objectives: [],
+ content_type: "theory",
+ status: "ready",
+ order,
+ blocks: [],
+ block_count: 3,
+ links: [],
+ parent_page_id: "",
+ error: "",
+ created_at: 1,
+ updated_at: 1,
+ });
+
+ const summaries = [
+ summary("page-1", "Previous chapter", 1),
+ summary("page-2", "Current long chapter", 2),
+ summary("page-3", "Next chapter", 3),
+ ];
+ const fullPage = (base: (typeof summaries)[number]) => ({
+ ...base,
+ blocks: [1, 2, 3].map((section) => block(base.id, section)),
+ });
+ const book = {
+ id: "sequential-fixture",
+ title: "Sequential reading fixture",
+ description: "",
+ status: "ready",
+ proposal: null,
+ knowledge_bases: [],
+ language: "en",
+ page_count: 3,
+ chapter_count: 3,
+ created_at: 1,
+ updated_at: 1,
+ metadata: {},
+ };
+ const progress = {
+ book_id: "sequential-fixture",
+ current_page_id: "page-2",
+ visited_page_ids: ["page-2"],
+ bookmarked_page_ids: [],
+ quiz_attempts: [],
+ weak_chapters: [],
+ score: 0,
+ updated_at: 1,
+ };
+
+ await page.route("**/api/**", async (route) => {
+ const requestUrl = new URL(route.request().url());
+ // Middleware proxies same-origin API calls to the backend. Point the
+ // browser fixture directly at that destination so Next's proxy cannot
+ // rewrite it away from Playwright's mock.
+ const url =
+ requestUrl.origin === "http://127.0.0.1:8001"
+ ? new URL(requestUrl.pathname + requestUrl.search, BASE_URL)
+ : requestUrl;
+ const { pathname } = url;
+ if (
+ pathname ===
+ "/api/v1/book/books/sequential-fixture/pages/page-1"
+ ) {
+ return route.fulfill(json({ page: fullPage(summaries[0]) }));
+ }
+ if (
+ pathname ===
+ "/api/v1/book/books/sequential-fixture/pages/page-2"
+ ) {
+ return route.fulfill(json({ page: fullPage(summaries[1]) }));
+ }
+ if (
+ pathname ===
+ "/api/v1/book/books/sequential-fixture/pages/page-3"
+ ) {
+ return route.fulfill(json({ page: fullPage(summaries[2]) }));
+ }
+ if (pathname === "/api/v1/book/books/sequential-fixture") {
+ return route.fulfill(json({ book, spine: null, pages: summaries, progress }));
+ }
+ if (pathname === "/api/v1/book/books") {
+ return route.fulfill(json({ books: [{ ...book, reading: null }] }));
+ }
+ if (pathname === "/api/v1/settings") {
+ return route.fulfill(json({ catalog: [] }));
+ }
+ if (pathname.endsWith("/learning-captures")) {
+ return route.fulfill(json({ captures: [] }));
+ }
+ if (pathname.endsWith("/progress/visit")) {
+ return route.fulfill(json({ progress }));
+ }
+ return route.fulfill(json({}));
+ });
+
+ await page.goto(
+ `${BASE_URL}/book?book=sequential-fixture&page=page-2`,
+ { waitUntil: "domcontentloaded" },
+ );
+ // A hidden reader (for example when the mobile chapter sidebar is expanded)
+ // must not turn the page and skip unread content.
+ await page.keyboard.press("ArrowRight");
+ await expect(page).toHaveURL(/page=page-2/);
+
+ await page.getByRole("button", { name: "Collapse chapters" }).click();
+ await expect(
+ page.getByRole("heading", { name: "Current long chapter" }),
+ ).toBeVisible();
+ await expect(page.getByText("Chapter 2, section 3, row 12:")).toBeVisible();
+
+ const reader = page.getByTestId("chapter-scroll-container");
+ await expect(reader).toBeVisible();
+ const firstScreen = await reader.evaluate((element) => ({
+ clientHeight: element.clientHeight,
+ maxScrollTop: element.scrollHeight - element.clientHeight,
+ scrollTop: element.scrollTop,
+ }));
+ expect(firstScreen.maxScrollTop).toBeGreaterThan(firstScreen.clientHeight);
+
+ await page.keyboard.press("ArrowRight");
+ const afterRight = await reader.evaluate((element) => ({
+ maxScrollTop: element.scrollHeight - element.clientHeight,
+ scrollTop: element.scrollTop,
+ }));
+ expect(afterRight.scrollTop).toBeGreaterThan(0);
+ expect(afterRight.scrollTop).toBeLessThan(afterRight.maxScrollTop);
+ await expect(
+ page.getByRole("heading", { name: "Current long chapter" }),
+ ).toBeVisible();
+ await expect
+ .poll(() =>
+ page
+ .getByTestId("chapter-progress")
+ .evaluate((element) => (element as HTMLProgressElement).value),
+ )
+ .toBe(Math.round((afterRight.scrollTop / afterRight.maxScrollTop) * 100));
+
+ await reader.evaluate((element) => {
+ element.scrollTop = element.scrollHeight;
+ });
+ await expect
+ .poll(() =>
+ page
+ .getByTestId("chapter-progress")
+ .evaluate((element) => (element as HTMLProgressElement).value),
+ )
+ .toBe(100);
+ await page.keyboard.press("ArrowRight");
+ await expect(
+ page.getByRole("heading", { name: "Next chapter" }),
+ ).toBeVisible();
+ await expect(await reader.evaluate((element) => element.scrollTop)).toBe(0);
+
+ await page.keyboard.press("ArrowLeft");
+ await expect(
+ page.getByRole("heading", { name: "Current long chapter" }),
+ ).toBeVisible();
+ await expect
+ .poll(() =>
+ reader.evaluate(
+ (element) =>
+ element.scrollTop === element.scrollHeight - element.clientHeight,
+ ),
+ )
+ .toBe(true);
+
+ await page.keyboard.press("ArrowLeft");
+ const afterLeft = await reader.evaluate((element) => ({
+ maxScrollTop: element.scrollHeight - element.clientHeight,
+ scrollTop: element.scrollTop,
+ }));
+ expect(afterLeft.scrollTop).toBeGreaterThan(0);
+ expect(afterLeft.scrollTop).toBeLessThan(afterLeft.maxScrollTop);
+ await expect(
+ page.getByRole("heading", { name: "Current long chapter" }),
+ ).toBeVisible();
+});