vomebook commited on
Commit ·
6b4bc4c
1
Parent(s): ff072d5
perf: bound Reader chapter retention and reuse text with PDF night mode
Browse filesFiles changed (12)
- READER_OPTIMIZATION_REPORT.mdAdded+74
- READER_PDF_THEME_REPORT.mdAdded+28
- static/reader-chapter-repository.js+75-1
- static/reader.css+18
- static/reader.html+1-1
- static/reader.js+255-58
- tests/test_reader_chapter_scheduler.jsAdded+57
- tests/test_reader_optimizations.pyAdded+252
- tests/test_reader_pdf_hybrid.py+30
- tests/test_reader_performance.py+5-4
- tests/test_reader_refactor.py+1-1
- tests/test_reader_style.py+80
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374# Reader Retention And Search Reuse
## Local Implementation (2026-10-09)
Implemented in the HF and GitHub Search development checkouts. This reportdescribes local fixtures and builds; this optimization set has not been deployed.Existing concurrent search/paging publications were retained as the new baseline.
- Chapter scheduling has three active slots, with at most two speculative loads. Demand is promoted ahead of queued speculation, obsolete windows are cancelled, and hidden-page/disposal events release speculative ownership. Cancelled creates retain their active slot until settlement; late completion cannot delete a newer request or insert discarded content.- Chapter bundles reuse the existing section virtualizer and scroll anchors, with a twelve-loaded-chapter target. Visible/nearby chapters, focused content, native selection ranges and selected search highlights remain protected. Evicted chapters retain equal-height placeholders and can reload through ordinary navigation or complete-index search. Retained byte reservations are released on eviction/closure. A formatting context prevents heading/paragraph margin collapse from causing height drift during replacement.- The pinned DOCX engine parses and renders through its public API. Its parsed document owns path-deduplicated image/font/numbering Blob URLs; failures and disposal revoke them, and late resource creation is suppressed. Real TTF loading verifies the matching same-origin/Blob font CSP policy. No global URL API is replaced by runtime code.- DOM search retains one complete text snapshot across queries, accounting for UTF-16 text and text-part metadata within 8 MiB and 32,768 parts. It retains stable parent/checkpoint metadata, not text nodes invalidated by highlighting. External mutations, streaming appends, page-label changes and TOC replacement disable reuse. Edits during asynchronous cached scanning cause a fresh scan. Oversized documents remain fully searched without caching. Disposal clears the snapshot; result totals, matching rules and accessible result pages are unchanged.
## Controlled A/B Observations
The committed pre-change Reader was replayed against the working-tree Reader infresh Chromium contexts. DOM measurements used six alternating rounds per site,16,000 ordinary paragraphs, an early cross-query match and a tail match. Timingcovers the actual Reader search routine, not network transfer. Both variantsreturned the same exact totals and visible selected text.
| Site | First Search Before/After | Repeated Search Before/After | Repeated Text-Node Visits || --- | --- | --- | --- || HF | 153.55 / 155.10 ms | 156.75 / 1.55 ms | 16,005 / 2 || Pages | 157.15 / 151.65 ms | 171.45 / 1.70 ms | 16,005 / 2 |
Both sites' 60-chapter navigation fixture retained 60 loaded chapters before,versus 12 after, with lightweight placeholders for previously loaded content.This is a DOM retention observation, not a measured heap reduction percentage.
A real pinned-engine DOCX fixture repeated one 788,084-byte PNG three times.Before, the three data-URL attributes contained 3,152,406 characters in total.After, all three rendered images shared one 788,084-byte Blob URL; their attributestotalled 192 characters. This measures resource representation and URL reuse,not total browser memory or a production loading-speed percentage.
Desktop (1100px) and mobile (390px) screenshots confirmed all three images renderwithout overlapping Reader controls. Separate regressions verify embedded-fontloading, URL revocation, blocked late creation, failed chapter reload recovery,cross-chapter selections, exact full-book totals and last/first chapter navigation.
## Verification
- Six focused optimization browser cases passed on each site, without skips.- Existing chapter browser regressions passed: fifteen per site.- Existing DOM search/navigation regressions passed: seven per site.- Format preparation, mocked DOCX, ZIP admission and chapter resource/loading regressions passed on their corresponding site-specific fixtures.- Scheduler ownership/promotion/cancellation contracts passed on both sites.- Both content-hashed esbuild 0.28.2 artifacts passed their release gates; the shared-source cross-project gate passed. Generated artifacts stay in `/tmp/opencode`.
Detailed commands and required workflow steps are in each project's `TESTING.md`.Production acceptance belongs to the eventual deployment, not these local results.12345678910111213141516171819202122232425262728# PDF Reader Theme
## Local Change (2026-10-10)
Dark mode now filters PDF content surfaces using `invert(.9) hue-rotate(180deg)`:native PDF.js canvases and PDF-pages images/canvases. The entire rendered PDFpage, including embedded illustrations, is adjusted. Light mode restores theoriginal presentation. PDF files and canvas source pixels remain unchanged;theme switching needs no document reload or PDF rerender.
Transparent text layers, selections and search highlights remain unfilteredabove the page. Ordinary image documents, image-pages, HTML and audio/videoretain their existing presentation. No HTML theme changes were made in this task.
## Verification
- HF: three theme cases and three existing PDF selection/search cases passed.- Pages: two theme cases and four existing PDF search cases passed.- Native PDF screenshot pixels verify dark paper and light paper at 1100px and 390px widths, while source canvas data, page identity and selected text remain unchanged. PDF-pages tests preserve the image URL and exclude image-pages.- HF's hybrid preview-to-canvas theme handoff passed. The current Pages checkout has an image-only PDF-pages renderer; applying HF hybrid tests to that checkout was an incorrect test selection, not evidence of a Pages hybrid regression.- Reader architecture/regression and cross-project release gates passed.
This change remains local and has not been published. Commands are recorded ineach project's `TESTING.md`.96 unmodified lines97989910010196 unmodified lines});}root.VoiceOfMLReaderChapters = Object.freeze({ createChapterRepository });})(typeof self !== "undefined" ? self : globalThis);96 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417596 unmodified lines});}function createChapterScheduler({ create, concurrency = 3, speculativeLimit = 2 }) {const records = new Map(), active = new Set();let disposed = false, scheduled = false;const abortError = () => new DOMException("Chapter load cancelled", "AbortError");function cancel(record) {if (records.get(record.index) !== record) return;records.delete(record.index);record.controller.abort(abortError());record.reject(record.controller.signal.reason);}function pump() {scheduled = false;if (disposed) return;while (active.size < concurrency) {const queued = [...records.values()].filter(record => !record.started);const speculative = [...active].filter(record => !record.demand).length;const record = queued.find(record => record.demand) ||(speculative < speculativeLimit && queued.find(record => !record.demand));if (!record) break;record.started = true;active.add(record);Promise.resolve().then(() => {record.controller.signal.throwIfAborted();return create(record.index, record.controller.signal, record.demand ? "high" : "low");}).then(value => {record.controller.signal.throwIfAborted();record.resolve(value);}).catch(record.reject).finally(() => {active.delete(record);if (records.get(record.index) === record) records.delete(record.index);schedule();});}}function schedule() {if (scheduled || disposed) return;scheduled = true;Promise.resolve().then(pump);}function load(index, demand = true) {if (disposed) return Promise.reject(abortError());if (demand) {for (const record of records.values())if (!record.demand && record.index !== index) cancel(record);}let record = records.get(index);if (record) {record.demand ||= demand;schedule();return record.promise;}record = { index, demand, started: false, controller: new root.AbortController() };record.promise = new Promise((resolve, reject) => Object.assign(record, { resolve, reject }));records.set(index, record);schedule();return record.promise;}function prefetch(indices) {const wanted = new Set(indices);for (const record of records.values())if (!record.demand && !wanted.has(record.index)) cancel(record);for (const index of wanted) load(index, false).catch(() => {});}function dispose() {disposed = true;for (const record of records.values()) cancel(record);}return Object.freeze({load, prefetch, dispose,get activeCount() { return active.size; },get pendingCount() { return records.size; }});}root.VoiceOfMLReaderChapters = Object.freeze({ createChapterRepository, createChapterScheduler });})(typeof self !== "undefined" ? self : globalThis);
959 unmodified lines96096196296396496555 unmodified lines1021102210231024102510265 unmodified lines103210331034103510361037959 unmodified lines.reader-page canvas.ready {opacity: 1;}.reader-pdf-text {position: absolute;inset: 0;55 unmodified linesmargin: 0 auto;background: #fff;}.reader-chapter-sentinel {display: block;width: 100%;5 unmodified linesoverflow: hidden;pointer-events: none;}.reader-content[data-mode="audio"],.reader-content[data-mode="video"] {width: 100%;959 unmodified lines96096196296396496596696796896997097197297397497555 unmodified lines1031103210331034103510361037103810395 unmodified lines10451046104710481049105010511052105310541055959 unmodified lines.reader-page canvas.ready {opacity: 1;}/* PDF pages keep their transparent text/selection layer above the themed page. */:root[data-theme="dark"] .reader-content[data-mode="pdf"] .reader-page canvas,:root[data-theme="dark"] .reader-content[data-mode="pdf-pages"] .reader-page canvas,:root[data-theme="dark"] .reader-content[data-mode="pdf-pages"] .reader-page > img {filter: invert(0.9) hue-rotate(180deg);}:root[data-theme="dark"] .reader-content[data-mode="pdf"] .reader-page,:root[data-theme="dark"] .reader-content[data-mode="pdf-pages"] .reader-page {background: #202428;}.reader-pdf-text {position: absolute;inset: 0;55 unmodified linesmargin: 0 auto;background: #fff;}.reader-epub-chapter {display: flow-root;}.reader-chapter-sentinel {display: block;width: 100%;5 unmodified linesoverflow: hidden;pointer-events: none;}.reader-chapter-load-error {min-height: 40px;opacity: 1;pointer-events: auto;}.reader-content[data-mode="audio"],.reader-content[data-mode="video"] {width: 100%;
4 unmodified lines5678910114 unmodified lines<meta name="viewport" content="width=device-width, initial-scale=1" /><metahttp-equiv="Content-Security-Policy"content="default-src 'self'; base-uri 'self' blob:; script-src 'self' https://unpkg.com 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline' blob:; img-src 'self' data: blob: https:; media-src 'self' https://voiceofml-search.hf.space https://hf-mirror.com https://huggingface.co https://*.hf.co https://*.huggingface.co; connect-src 'self' blob: https://unpkg.com https://huggingface.co https://*.hf.co https://*.huggingface.co https://voiceofml-search.hf.space https://hf-mirror.com; frame-src 'self' blob:;"/><title>VoiceOfML Reader</title><script>4 unmodified lines5678910114 unmodified lines<meta name="viewport" content="width=device-width, initial-scale=1" /><metahttp-equiv="Content-Security-Policy"content="default-src 'self'; base-uri 'self' blob:; script-src 'self' https://unpkg.com 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline' blob:; font-src 'self' blob:; img-src 'self' data: blob: https:; media-src 'self' https://voiceofml-search.hf.space https://hf-mirror.com https://huggingface.co https://*.hf.co https://*.huggingface.co; connect-src 'self' blob: https://unpkg.com https://huggingface.co https://*.hf.co https://*.huggingface.co https://voiceofml-search.hf.space https://hf-mirror.com; frame-src 'self' blob:;"/><title>VoiceOfML Reader</title><script>
560 unmodified lines5615625635645655662065 unmodified lines2632263326342635263626371923 unmodified lines4561456245634564456545664567456845694570457137 unmodified lines460946104611461246134614461536 unmodified lines465246534654465546564657465846594660466146624663466446653 unmodified lines46694670467146724673467414 unmodified lines46894690469146924693469446954696469746984699470047014702470347042 unmodified lines470747084709471047114712471347144715471647174718471947204721472247234724472550 unmodified lines47764777477847794780478147824783478447854786478747884789479047914792479347944795479647973 unmodified lines48014802480348044805480648074808480948104811481248134814481548162 unmodified lines4819482048214822482348243 unmodified lines482848294830483148324833483415 unmodified lines4850485148524853485448554856485748584859486048612 unmodified lines4864486548664867486848694870487148724873487424 unmodified lines489949004901490249034904517 unmodified lines54225423542454255426542754281006 unmodified lines6435643664376438643964403 unmodified lines64446445644664476448644912 unmodified lines64626463646464656466646731 unmodified lines6499650065016502650365049 unmodified lines65146515651665176518651918 unmodified lines6538653965406541654265438 unmodified lines65526553655465556556655779 unmodified lines66376638663966406641664266436644664566465 unmodified lines6652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466757 unmodified lines668366846685668666876688668970 unmodified lines676067616762676367646765560 unmodified linesfoliateScrollFrame = 0,foliateWindowFrame = 0;let initialReaderTargetSection = null;const FOLIATE_PREFETCH_SECTIONS = 6;const FOLIATE_PREFETCH_MARGIN = 4000;const FOLIATE_LOADED_SECTION_LIMIT = 12;2065 unmodified linesthrow Object.assign(new Error(`HTTP ${response.status}`), { status: response.status });}).catch((error) => {assertReaderActive();if (retryableReaderProxyError(error)) throw error;return fetchWithReaderTimeout(rawUrl, READER_PROXY_TIMEOUT_MS, requestInit);});1923 unmodified linesconst frame = document.createElement("div");frame.className = "epub-frame";content.appendChild(frame);const loaded = new Set(),pending = new Map(),manifestBase = trustedReaderAssetManifestUrl(chapterManifestUrl || sourceUrl);const chapterByIndex = new Map(manifest.chapters.map((chapter) => [chapter.index, chapter]));const chapterPrefetchCount = 6;let chapterPreviousObserver = null;const chapterBudget = VoiceOfMLReaderSecurity.createByteBudget();if (!manifestBase) throw new Error("EPUB_INVALID_MANIFEST_PATH");37 unmodified lines);if (existing) return existing;const next = nextChapterNode(Number(article.dataset.chapter), ".reader-epub-chapter");foliateScrollAnchors.preserve(() => frame.insertBefore(article, next || null));foliateScrollAnchors.observe(article);return article;};36 unmodified linesactivate: (generation) => activateChapter(manifest.chapters[item.chapter - 1], generation, item.fragment)})));const fetchChapter = async (chapter) => {assertReaderActive();if (loaded.has(chapter.index)) return;if (pending.has(chapter.index)) return pending.get(chapter.index);const task = (async () => {const url = chapterUrl(chapter);if (!url) throw new Error("EPUB_INVALID_PATH");const result = await fetchReaderUrl(url);if (!result.ok) throw new Error(`HTTP ${result.status}`);const bytes = await VoiceOfMLReaderSecurity.readBytes(result,3 unmodified lineslet inserted = false;try {assertReaderActive();const doc = parseChapterDocument(new TextDecoder().decode(bytes));for (const element of doc.querySelectorAll("*")) {for (const name of ["src", "href", "poster", "xlink:href"])14 unmodified linesarticle.innerHTML = doc.body ? doc.body.innerHTML : "";// The generated text index includes head text (e.g. the chapter title).article._chapterSearchHead = doc.head ? document.importNode(doc.head, true) : null;const marker = frame.querySelector(`.reader-chapter-sentinel[data-chapter="${chapter.index}"]`);if (marker) {chapterManifestObserver.unobserve(marker);chapterPreviousObserver.unobserve(marker);marker.remove();}insertChapter(article);loaded.add(chapter.index);inserted = true;for (const entry of navigationState.tocEntries)if (entry.chapterIndex === chapter.index)2 unmodified linesif (next) ensureSentinel(next);const previous = chapterAt(chapter.index - 1);if (previous) ensureSentinel(previous, true);} catch (error) {if (!inserted) chapterBudget.release(bytes.byteLength);throw error;}})().finally(() => {pending.delete(chapter.index);if (!loaded.has(chapter.index)) ensureSentinel(chapter);});pending.set(chapter.index, task);return task;};const activateChapter = async (chapter, generation, fragment = "") => {await fetchChapter(chapter);if (!isReaderGenerationCurrent("navigation", generation)) return false;const node = frame.querySelector(`.reader-epub-chapter[data-chapter="${chapter.index}"]`);let id = fragment.replace(/^#/, "");50 unmodified linesreportNavigationError(error, generation);}});const prefetchChapters = (startIndex) => {const tasks = manifest.chapters.slice(startIndex, startIndex + chapterPrefetchCount).map((chapter) => fetchChapter(chapter).catch(() => null));if (tasks.length) Promise.all(tasks).catch(() => {});};chapterManifestObserver = new IntersectionObserver((entries) =>entries.filter((entry) => entry.isIntersecting).forEach((entry) => {if (readerAbortController.signal.aborted) return;const chapter = chapterAt(Number(entry.target.dataset.chapter));if (chapter) prefetchChapters(chapter.index - 1);}),{ root: viewport, rootMargin: "4000px 0px" });chapterPreviousObserver = new IntersectionObserver((entries) => {if (readerAbortController.signal.aborted) return;3 unmodified linesif (chapter) fetchChapter(chapter).catch(() => {});}}, { root: viewport });trackReaderResource(() => {chapterManifestObserver?.disconnect();chapterPreviousObserver?.disconnect();chapterManifestObserver = null;chapterManifestLoader = null;});chapterManifestLoader = async (index) => {const chapter = chapterAt(index);if (!chapter) return null;await fetchChapter(chapter);return frame.querySelector(`.reader-epub-chapter[data-chapter="${index}"]`);};setChapterToc();2 unmodified linesconst initialChapter = Number.isInteger(savedChapter)? Math.max(0, Math.min(manifest.chapters.length - 1, savedChapter)): 0;if (initialChapter > 0) ensureSentinel(manifest.chapters[initialChapter - 1], true);try {await fetchChapter(manifest.chapters[initialChapter]);3 unmodified linescode: "READER_RESTORE"});}prefetchChapters(initialChapter + 1);assertReaderActive();markReaderContentReady();status.textContent = `EPUB · ${manifest.chapters.length} 章`;15 unmodified linesconst body = document.createElement("div");body.className = "docx-body";content.append(styles, body);await docx.renderAsync(bytes, body, styles, {className: "reader-docx",inWrapper: true,breakPages: true,ignoreLastRenderedPageBreak: false,useBase64URL: true,renderHeaders: true,renderFooters: true,renderFootnotes: true,2 unmodified linesrenderComments: false,renderAltChunks: false,debug: false});assertReaderActive();body.classList.toggle("reader-document-dark", readerTheme === "dark");if (!(body.textContent || "").trim() && !body.querySelector("img, table, svg, canvas"))throw new Error("DOCX rendered no supported content");const pages = [...body.querySelectorAll(":scope > .reader-docx-wrapper > section.reader-docx")];if (pages.length) {updateDocumentState({ pageCount: pages.length });24 unmodified linesstatus.textContent = "图片";}function disposeFormatResources(mode) {if (mode === "swf") {swfPlayer?.remove();swfPlayer = null;517 unmodified linespdfFetchPolicy = createPdfFetchPolicy();trackReaderResource(() => { pdfFetchPolicy?.dispose(); pdfFetchPolicy = null; });}pdfFetchPolicy.add([sourceUrl, contentUrl]);pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;const options = (url) => ({url,1006 unmodified lines}let fullSearchActiveMarks = [];let fullSearchDomLocator = null;readerRuntime.events.on("generation", ({ name }) => {if (name === "search") {fullSearchDomLocator?.dispose();3 unmodified linestrackReaderResource(() => {fullSearchDomLocator?.dispose();fullSearchDomLocator = null;});function createFullSearchDomLocator(root, generation) {fullSearchDomLocator?.dispose();12 unmodified lines};const locator = {current,build(offsets) {if (!current()) return;const stride = Math.max(128, Math.ceil(offsets.length / 2048));31 unmodified lines}function clearFullSearchMarks() {fullSearchDomLocator?.pause();try {content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());const changedParents = new Set();9 unmodified linescontent.querySelectorAll(".reader-chapter-search-heading").forEach(node => node.remove());} finally {fullSearchDomLocator?.resume();}}async function fullSearchTextNodes(root, generation, endOffset = Infinity, checkpoint = null) {18 unmodified lines}function highlightTextParts(parts) {fullSearchDomLocator?.pause();const marks = [];try {for (const { node, start, end } of [...parts].reverse()) {8 unmodified lines}} finally {fullSearchDomLocator?.resume();}return marks;}79 unmodified linesasync function fullSearchDomMatches(root, fallback, query, generation, progressive = false,occurrence = null, navigationGeneration = readerRuntime.currentGeneration("navigation")) {root = foliateSectionRoot(root);const locator = progressive ? createFullSearchDomLocator(root, generation) : null;const nodes = await fullSearchTextNodes(root, generation);if (!nodes || !isReaderGenerationCurrent("search", generation)) return [];const offsets = [],chunks = [];let length = 0;for (const [index, node] of nodes.entries()) {5 unmodified linesif (!isReaderGenerationCurrent("search", generation)) return [];}}locator?.build(offsets);const headingLookup = createFullSearchHeadingLookup(root, offsets);const text = chunks.join(""), groups = [], firstHits = [];const patternText = fullSearchEscape(query);let nextStart = 0, total = 0;const locateIndex = (index) => {let low = 0, high = offsets.length - 1;while (low < high) {const middle = (low + high) >> 1;if (offsets[middle].end <= index) low = middle + 1;else high = middle;}return low;};const partsFor = (start, end) => {const parts = [];for (let index = locateIndex(start); index < offsets.length && offsets[index].start < end; index++)parts.push(offsets[index]);return parts;};const matchesIn = function* (group) {7 unmodified linesconst resultFor = (match) => {const part = offsets[locateIndex(match.index)];return {location: fullSearchLocation(part.node, fallback, match.index, text.length, headingLookup, part.parent),snippet: fullSearchSnippet(text, match.index, match.value.length),async activate(navigationGeneration = readerRuntime.currentGeneration("navigation")) {if (!isReaderGenerationCurrent("navigation", navigationGeneration)) return false;70 unmodified linesreturn [{ target: fullSearchActiveMarks[0] }];}const fallbackResults = progressive ? null : firstHits.map(resultFor);if (navigationGeneration === readerRuntime.currentGeneration("navigation")) {for (let i = firstHits.length - 1; i >= 0; i--) {const match = firstHits[i], end = match.index + match.value.length;560 unmodified lines5615625635645655665672065 unmodified lines26332634263526362637263826391923 unmodified lines45634564456545664567456845694570457145724573457437 unmodified lines46124613461446154616461746184619462046214622462346244625462636 unmodified lines46634664466546664667466846694670467146724673467446753 unmodified lines467946804681468246834684468514 unmodified lines4700470147024703470447054706470747082 unmodified lines4711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474250 unmodified lines4793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648673 unmodified lines4871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549062 unmodified lines49094910491149124913491449153 unmodified lines4919492049214922492349244925492615 unmodified lines4942494349444945494649474948494949504951495249532 unmodified lines49564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500024 unmodified lines5025502650275028502950305031503250335034517 unmodified lines55525553555455555556555755581006 unmodified lines6565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566063 unmodified lines6610661166126613661466156616661712 unmodified lines6630663166326633663466356636663731 unmodified lines66696670667166726673667466759 unmodified lines668566866687668866896690669118 unmodified lines67106711671267136714671567168 unmodified lines672567266727672867296730673179 unmodified lines68116812681368146815681668176818681968206821682268235 unmodified lines68296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568567 unmodified lines686468656866686768686869687070 unmodified lines6941694269436944694569466947694869496950695169526953695469556956695769586959696069616962560 unmodified linesfoliateScrollFrame = 0,foliateWindowFrame = 0;let initialReaderTargetSection = null;let chapterManifestCleanup = null;const FOLIATE_PREFETCH_SECTIONS = 6;const FOLIATE_PREFETCH_MARGIN = 4000;const FOLIATE_LOADED_SECTION_LIMIT = 12;2065 unmodified linesthrow Object.assign(new Error(`HTTP ${response.status}`), { status: response.status });}).catch((error) => {assertReaderActive();requestInit.signal?.throwIfAborted();if (retryableReaderProxyError(error)) throw error;return fetchWithReaderTimeout(rawUrl, READER_PROXY_TIMEOUT_MS, requestInit);});1923 unmodified linesconst frame = document.createElement("div");frame.className = "epub-frame";content.appendChild(frame);const loaded = new Set(), retainedBytes = new Map(),manifestBase = trustedReaderAssetManifestUrl(chapterManifestUrl || sourceUrl);const chapterByIndex = new Map(manifest.chapters.map((chapter) => [chapter.index, chapter]));const chapterPrefetchCount = 6;let chapterFocusIndex = 1, chapterWindowFrame = 0, chapterWindowReady = false;let chapterNavigating = 0;let chapterPreviousObserver = null;const chapterBudget = VoiceOfMLReaderSecurity.createByteBudget();if (!manifestBase) throw new Error("EPUB_INVALID_MANIFEST_PATH");37 unmodified lines);if (existing) return existing;const next = nextChapterNode(Number(article.dataset.chapter), ".reader-epub-chapter");const marker = frame.querySelector(`.reader-chapter-sentinel[data-chapter="${article.dataset.chapter}"]`);foliateScrollAnchors.preserve(() => {if (marker) {chapterManifestObserver.unobserve(marker);chapterPreviousObserver.unobserve(marker);marker.replaceWith(article);} else frame.insertBefore(article, next || null);});chapterManifestObserver.observe(article);foliateScrollAnchors.observe(article);return article;};36 unmodified linesactivate: (generation) => activateChapter(manifest.chapters[item.chapter - 1], generation, item.fragment)})));const chapterScheduler = VoiceOfMLReaderChapters.createChapterScheduler({create: async (index, signal, priority) => {const chapter = chapterAt(index);assertReaderActive();const url = chapterUrl(chapter);if (!url) throw new Error("EPUB_INVALID_PATH");const result = await fetchReaderUrl(url, { signal, priority });if (!result.ok) throw new Error(`HTTP ${result.status}`);const bytes = await VoiceOfMLReaderSecurity.readBytes(result,3 unmodified lineslet inserted = false;try {assertReaderActive();signal.throwIfAborted();const doc = parseChapterDocument(new TextDecoder().decode(bytes));for (const element of doc.querySelectorAll("*")) {for (const name of ["src", "href", "poster", "xlink:href"])14 unmodified linesarticle.innerHTML = doc.body ? doc.body.innerHTML : "";// The generated text index includes head text (e.g. the chapter title).article._chapterSearchHead = doc.head ? document.importNode(doc.head, true) : null;insertChapter(article);loaded.add(chapter.index);retainedBytes.set(chapter.index, bytes.byteLength);inserted = true;for (const entry of navigationState.tocEntries)if (entry.chapterIndex === chapter.index)2 unmodified linesif (next) ensureSentinel(next);const previous = chapterAt(chapter.index - 1);if (previous) ensureSentinel(previous, true);scheduleChapterWindow();} catch (error) {if (!inserted) chapterBudget.release(bytes.byteLength);throw error;}}});const fetchChapter = (chapter, demand = true) => {assertReaderActive();if (loaded.has(chapter.index)) return Promise.resolve();return chapterScheduler.load(chapter.index, demand).then(() => {foliateScrollAnchors.whenIdle(trimChapterWindow);}).catch(error => {if (error.name !== "AbortError" && !readerAbortController.signal.aborted) {const marker = ensureSentinel(chapter);marker?.classList.add("reader-chapter-load-error");marker?.removeAttribute("aria-hidden");}throw error;});};const activateChapter = async (chapter, generation, fragment = "") => {chapterFocusIndex = chapter.index;chapterNavigating++;try { await fetchChapter(chapter); }finally { chapterNavigating--; }if (!isReaderGenerationCurrent("navigation", generation)) return false;const node = frame.querySelector(`.reader-epub-chapter[data-chapter="${chapter.index}"]`);let id = fragment.replace(/^#/, "");50 unmodified linesreportNavigationError(error, generation);}});const chapterVirtualizer = VoiceOfMLReaderVirtual.createSectionVirtualizer({limit: 12,getLoaded: () => [...frame.querySelectorAll(":scope > .reader-epub-chapter")],getIndex: article => Number(article.dataset.chapter),getHeight: article => article.getBoundingClientRect().height,canVirtualize: article => {const rect = article.getBoundingClientRect(), view = viewport.getBoundingClientRect();const selection = window.getSelection();return (rect.bottom < view.top - 800 || rect.top > view.bottom + 800) &&!article.contains(document.activeElement) &&!article.querySelector("mark.full-search-highlight") &&!(selection && !selection.isCollapsed &&selection.containsNode(article, true));},virtualize: (article, index, height) => {loaded.delete(index);const marker = ensureSentinel(chapterAt(index));const style = getComputedStyle(article);marker.classList.add("reader-chapter-placeholder");marker.style.height = `${height}px`;marker.style.marginTop = style.marginTop;marker.style.marginBottom = style.marginBottom;marker.setAttribute("aria-hidden", "true");chapterManifestObserver.unobserve(article);foliateScrollAnchors.unobserve(article);for (const entry of navigationState.tocEntries)if (entry.chapterIndex === index) entry.target = null;for (const image of article.querySelectorAll("img")) image.removeAttribute("src");article.replaceWith(marker);article._chapterSearchHead = null;},release: index => {chapterBudget.release(retainedBytes.get(index));retainedBytes.delete(index);},preserve: change => foliateScrollAnchors.preserve(change)});function trimChapterWindow() {if (chapterWindowReady) chapterVirtualizer.trim(chapterFocusIndex);}function refreshChapterWindow() {chapterWindowFrame = 0;if (!chapterWindowReady || readerAbortController.signal.aborted) return;const view = viewport.getBoundingClientRect();const rows = [...frame.querySelectorAll(":scope > [data-chapter]")];const current = rows.find(row => {const rect = row.getBoundingClientRect();return rect.top <= view.top + 80 && rect.bottom > view.top + 80;}) || rows.find(row => row.getBoundingClientRect().top > view.top);if (current && !chapterNavigating) chapterFocusIndex = Number(current.dataset.chapter);if (!chapterNavigating && current?.classList.contains("reader-chapter-sentinel") &¤t.getBoundingClientRect().top < view.bottom)fetchChapter(chapterAt(chapterFocusIndex)).catch(() => {});const indices = document.hidden ? [] : manifest.chapters.slice(Math.max(0, chapterFocusIndex - 2), chapterFocusIndex + chapterPrefetchCount).filter(chapter => !loaded.has(chapter.index)).map(chapter => chapter.index);chapterScheduler.prefetch(indices);foliateScrollAnchors.whenIdle(trimChapterWindow);}function scheduleChapterWindow() {if (!chapterWindowFrame) chapterWindowFrame = requestAnimationFrame(refreshChapterWindow);}function handleChapterVisibility() {if (document.hidden) chapterScheduler.prefetch([]);else scheduleChapterWindow();}chapterManifestObserver = new IntersectionObserver(scheduleChapterWindow,{ root: viewport, rootMargin: "800px 0px" });chapterPreviousObserver = new IntersectionObserver((entries) => {if (readerAbortController.signal.aborted) return;3 unmodified linesif (chapter) fetchChapter(chapter).catch(() => {});}}, { root: viewport });viewport.addEventListener("scroll", scheduleChapterWindow, { passive: true });window.addEventListener("resize", scheduleChapterWindow);document.addEventListener("visibilitychange", handleChapterVisibility);let chapterCleaned = false;chapterManifestCleanup = () => {if (chapterCleaned) return;chapterCleaned = true;chapterWindowReady = false;cancelAnimationFrame(chapterWindowFrame);viewport.removeEventListener("scroll", scheduleChapterWindow);window.removeEventListener("resize", scheduleChapterWindow);document.removeEventListener("visibilitychange", handleChapterVisibility);chapterScheduler.dispose();chapterVirtualizer.dispose();chapterManifestObserver?.disconnect();chapterPreviousObserver?.disconnect();chapterManifestObserver = null;chapterManifestLoader = null;for (const bytes of retainedBytes.values()) chapterBudget.release(bytes);retainedBytes.clear();loaded.clear();};trackReaderResource(chapterManifestCleanup);chapterManifestLoader = async (index) => {const chapter = chapterAt(index);if (!chapter) return null;chapterFocusIndex = index;chapterNavigating++;try { await fetchChapter(chapter); }finally { chapterNavigating--; }return frame.querySelector(`.reader-epub-chapter[data-chapter="${index}"]`);};setChapterToc();2 unmodified linesconst initialChapter = Number.isInteger(savedChapter)? Math.max(0, Math.min(manifest.chapters.length - 1, savedChapter)): 0;chapterFocusIndex = manifest.chapters[initialChapter].index;if (initialChapter > 0) ensureSentinel(manifest.chapters[initialChapter - 1], true);try {await fetchChapter(manifest.chapters[initialChapter]);3 unmodified linescode: "READER_RESTORE"});}chapterWindowReady = true;scheduleChapterWindow();assertReaderActive();markReaderContentReady();status.textContent = `EPUB · ${manifest.chapters.length} 章`;15 unmodified linesconst body = document.createElement("div");body.className = "docx-body";content.append(styles, body);const options = {className: "reader-docx",inWrapper: true,breakPages: true,ignoreLastRenderedPageBreak: false,useBase64URL: false,renderHeaders: true,renderFooters: true,renderFootnotes: true,2 unmodified linesrenderComments: false,renderAltChunks: false,debug: false};const docxDocument = await docx.parseAsync(bytes, options);assertReaderActive();const urls = new Set(), urlsByPath = new Map(), blobToURL = docxDocument.blobToURL.bind(docxDocument);let released = false;const release = () => {released = true;for (const url of urls) URL.revokeObjectURL(url);urls.clear();urlsByPath.clear();};const untrack = trackReaderResource(release);// Own this parsed document's images, fonts and numbering assets only.docxDocument.blobToURL = (blob, path) => {if (released) return null;if (path && urlsByPath.has(path)) return urlsByPath.get(path);const url = blobToURL(blob, path);if (typeof url === "string" && url.startsWith("blob:")) {urls.add(url);if (path) urlsByPath.set(path, url);}return url;};try {const nodes = await docx.renderDocument(docxDocument, options);assertReaderActive();for (const node of nodes) (node.nodeName === "STYLE" ? styles : body).appendChild(node);} catch (error) {release();untrack();throw error;}assertReaderActive();body.classList.toggle("reader-document-dark", readerTheme === "dark");if (!(body.textContent || "").trim() && !body.querySelector("img, table, svg, canvas")) {release();untrack();throw new Error("DOCX rendered no supported content");}const pages = [...body.querySelectorAll(":scope > .reader-docx-wrapper > section.reader-docx")];if (pages.length) {updateDocumentState({ pageCount: pages.length });24 unmodified linesstatus.textContent = "图片";}function disposeFormatResources(mode) {if (mode === "epub-chapters") {chapterManifestCleanup?.();chapterManifestCleanup = null;}if (mode === "swf") {swfPlayer?.remove();swfPlayer = null;517 unmodified linespdfFetchPolicy = createPdfFetchPolicy();trackReaderResource(() => { pdfFetchPolicy?.dispose(); pdfFetchPolicy = null; });}pdfFetchPolicy.add([target, readerContentUrl(target)]);pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;const options = (url) => ({url,1006 unmodified lines}let fullSearchActiveMarks = [];let fullSearchDomLocator = null;let fullSearchDomSnapshot = null;const DOM_SEARCH_SNAPSHOT_BYTES = 8 * 1024 * 1024;function createDomSearchSnapshot(root) {fullSearchDomSnapshot?.dispose();let valid = true, disposed = false, value = null;const invalidate = () => { valid = false; value = null; };const observer = new MutationObserver(invalidate);const current = () => {if (observer.takeRecords().length) invalidate();return valid && !disposed;};const resume = () => {if (!disposed) observer.observe(root, {subtree: true, childList: true, characterData: true,attributes: true, attributeFilter: ["class", "data-page"]});};const snapshot = {root, current, resume,get value() { return current() ? value : null; },set(data) {if (!current()) return;if (data.offsets.length > 32768 || data.text.length * 2 + data.offsets.length * 64 > DOM_SEARCH_SNAPSHOT_BYTES) {snapshot.dispose();return;}// Owned highlights replace text nodes but leave these parent boundaries intact.value = { ...data, offsets: data.offsets.map(({ parent, start, end }) => ({ parent, start, end })) };},pause() { current(); observer.disconnect(); },dispose() { disposed = true; invalidate(); observer.disconnect(); }};resume();fullSearchDomSnapshot = snapshot;return snapshot;}readerRuntime.events.on("generation", ({ name }) => {if (name === "search") {fullSearchDomLocator?.dispose();3 unmodified linestrackReaderResource(() => {fullSearchDomLocator?.dispose();fullSearchDomLocator = null;fullSearchDomSnapshot?.dispose();fullSearchDomSnapshot = null;});function createFullSearchDomLocator(root, generation) {fullSearchDomLocator?.dispose();12 unmodified lines};const locator = {current,boundaries() { return current() ? checkpoints.slice() : []; },seed(boundaries) { if (current()) checkpoints.push(...boundaries); },build(offsets) {if (!current()) return;const stride = Math.max(128, Math.ceil(offsets.length / 2048));31 unmodified lines}function clearFullSearchMarks() {fullSearchDomLocator?.pause();fullSearchDomSnapshot?.pause();try {content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());const changedParents = new Set();9 unmodified linescontent.querySelectorAll(".reader-chapter-search-heading").forEach(node => node.remove());} finally {fullSearchDomLocator?.resume();fullSearchDomSnapshot?.resume();}}async function fullSearchTextNodes(root, generation, endOffset = Infinity, checkpoint = null) {18 unmodified lines}function highlightTextParts(parts) {fullSearchDomLocator?.pause();fullSearchDomSnapshot?.pause();const marks = [];try {for (const { node, start, end } of [...parts].reverse()) {8 unmodified lines}} finally {fullSearchDomLocator?.resume();fullSearchDomSnapshot?.resume();}return marks;}79 unmodified linesasync function fullSearchDomMatches(root, fallback, query, generation, progressive = false,occurrence = null, navigationGeneration = readerRuntime.currentGeneration("navigation")) {root = foliateSectionRoot(root);const cached = progressive && fullSearchDomSnapshot?.root === root &&fullSearchDomSnapshot.value?.toc === navigationState.tocEntries ? fullSearchDomSnapshot.value : null;const snapshot = progressive ? (cached ? fullSearchDomSnapshot : createDomSearchSnapshot(root)) : null;const locator = progressive ? createFullSearchDomLocator(root, generation) : null;const nodes = cached ? [] : await fullSearchTextNodes(root, generation);if (!nodes || !isReaderGenerationCurrent("search", generation)) return [];const offsets = cached ? cached.offsets : [],chunks = [];let length = 0;for (const [index, node] of nodes.entries()) {5 unmodified linesif (!isReaderGenerationCurrent("search", generation)) return [];}}if (cached) locator?.seed(cached.checkpoints);else locator?.build(offsets);const headingLookup = cached ? cached.headingLookup : createFullSearchHeadingLookup(root, offsets);const text = cached ? cached.text : chunks.join(""), groups = [], firstHits = [];if (!cached && snapshot && (headingLookup || !navigationState.tocEntries.some(entry => entry.target)))snapshot.set({ text, offsets, headingLookup, checkpoints: locator.boundaries(), toc: navigationState.tocEntries });let highlightOffsets = offsets;const patternText = fullSearchEscape(query);let nextStart = 0, total = 0;const locateIndex = (index, parts = offsets) => {let low = 0, high = parts.length - 1;while (low < high) {const middle = (low + high) >> 1;if (parts[middle].end <= index) low = middle + 1;else high = middle;}return low;};const partsFor = (start, end) => {const parts = [];for (let index = locateIndex(start, highlightOffsets); index < highlightOffsets.length && highlightOffsets[index].start < end; index++)parts.push(highlightOffsets[index]);return parts;};const matchesIn = function* (group) {7 unmodified linesconst resultFor = (match) => {const part = offsets[locateIndex(match.index)];return {location: fullSearchLocation(part.node || part.parent, fallback, match.index, text.length, headingLookup, part.parent),snippet: fullSearchSnippet(text, match.index, match.value.length),async activate(navigationGeneration = readerRuntime.currentGeneration("navigation")) {if (!isReaderGenerationCurrent("navigation", navigationGeneration)) return false;70 unmodified linesreturn [{ target: fullSearchActiveMarks[0] }];}const fallbackResults = progressive ? null : firstHits.map(resultFor);if (cached && !snapshot.current())return fullSearchDomMatches(root, fallback, query, generation, progressive, occurrence, navigationGeneration);if (cached && firstHits.length && navigationGeneration === readerRuntime.currentGeneration("navigation")) {const checkpoint = locator.checkpoint(firstHits[0].index);const end = firstHits[firstHits.length - 1].index + firstHits[firstHits.length - 1].value.length;const markNodes = await fullSearchTextNodes(root, generation, end, checkpoint);if (!markNodes || !isReaderGenerationCurrent("search", generation)) return [];if (!snapshot.current())return fullSearchDomMatches(root, fallback, query, generation, progressive, occurrence, navigationGeneration);let position = checkpoint?.start || 0;highlightOffsets = markNodes.map(node => {const part = { node, start: position, end: position + node.data.length };position = part.end;return part;});}if (navigationGeneration === readerRuntime.currentGeneration("navigation")) {for (let i = firstHits.length - 1; i >= 0; i--) {const match = firstHits[i], end = match.index + match.value.length;
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657const assert = require("assert");const fs = require("fs");const path = require("path");const vm = require("vm");
async function main() { const sandbox = { DOMException, AbortController }; sandbox.self = sandbox; vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static/reader-chapter-repository.js"), "utf8"), sandbox); const starts = [], held = new Map(); const scheduler = sandbox.VoiceOfMLReaderChapters.createChapterScheduler({ create(index, signal, priority) { starts.push({ index, signal, priority }); return new Promise(resolve => held.set(index, resolve)); } }); const tick = () => new Promise(resolve => setImmediate(resolve)); scheduler.prefetch([1, 2, 3, 4, 5, 6]); await tick(); assert.deepStrictEqual(starts.map(item => item.index), [1, 2]); const foreground = scheduler.load(20); await tick(); assert.deepStrictEqual(starts.map(item => item.index), [1, 2, 20]); assert.strictEqual(starts[2].priority, "high"); assert.ok(starts[0].signal.aborted && starts[1].signal.aborted); assert.strictEqual(scheduler.activeCount, 3, "cancelled creates retain ownership until settlement"); held.get(20)("target"); assert.strictEqual(await foreground, "target"); held.get(1)("late"); held.get(2)("late"); await tick(); assert.strictEqual(scheduler.activeCount, 0); assert.strictEqual(scheduler.pendingCount, 0); scheduler.prefetch([30, 31, 32]); const promoted = scheduler.load(32); assert.strictEqual(scheduler.load(32), promoted); await tick(); assert.strictEqual(starts[3].index, 32, "queued demand overtakes speculation"); held.get(32)("promoted"); assert.strictEqual(await promoted, "promoted"); await tick(); scheduler.prefetch([40, 41, 42]); await tick(); scheduler.prefetch([41, 43]); assert.ok(starts.find(item => item.index === 40).signal.aborted); const closing = scheduler.load(50); const rejected = assert.rejects(closing, error => error.name === "AbortError"); scheduler.dispose(); await rejected; for (const resolve of held.values()) resolve("closed"); await tick(); assert.strictEqual(scheduler.activeCount, 0); assert.strictEqual(scheduler.pendingCount, 0); await assert.rejects(scheduler.load(1), error => error.name === "AbortError"); console.log("reader chapter scheduler contracts passed");}
main().catch(error => { console.error(error); process.exitCode = 1; });123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252"""Focused offline acceptance for Reader scheduling, retention and text reuse."""
import gzipimport hashlibimport ioimport jsonimport unittestimport urllib.parseimport zipfile
from tests import test_reader_refactor as fixtures
@unittest.skipIf(fixtures.support.sync_playwright is None, "Playwright is unavailable")class ReaderOptimizationTests(unittest.TestCase): setUpClass = classmethod(fixtures.ReaderRefactorTest.setUpClass.__func__) tearDownClass = classmethod(fixtures.ReaderRefactorTest.tearDownClass.__func__) setUp = fixtures.ReaderRefactorTest.setUp tearDown = fixtures.ReaderRefactorTest.tearDown reader_url = fixtures.ReaderRefactorTest.reader_url serve = fixtures.ReaderRefactorTest.serve open = fixtures.ReaderRefactorTest.open search = fixtures.ReaderRefactorTest.search
def expose(self): def instrument(route): response = route.fetch() script = response.text().replace('chapterManifestCleanup = () => {', ''' window.__chapterStats = () => ({active: chapterScheduler.activeCount, pending: chapterScheduler.pendingCount, bytes: chapterBudget.used}); chapterManifestCleanup = () => {''') route.fulfill(response=response, body=script + ''' window.__snapshot = () => fullSearchDomSnapshot; window.__query = async query => { fullSearchInput.value = query; await runFullSearch(); return chapterSearchPage?.total || 0; }; window.__goChapter = index => navigationState.tocEntries[index-1].activate(beginReaderNavigation()); window.__walkProbe = () => { const doc = (htmlFrame?.contentDocument?.body || content).ownerDocument; const native = doc.createTreeWalker.bind(doc); window.__visits = 0; doc.createTreeWalker = (...args) => { const walker = native(...args), next = walker.nextNode.bind(walker); walker.nextNode = () => { __visits++; return next(); }; return walker; }; }; ''') self.page.route('**/static/reader.js?*', instrument)
def chapter_book(self, hold=False): self.expose() base = 'https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/' + 'a' * 64 + '/' chapters, texts, bodies = [], [], {} for index in range(1, 61): path = f'chapter-{index}.xhtml' body = f'<h1 id="heading-{index}">Chapter {index}</h1><p style="height:1600px">needle unique-{index}</p>' bodies[base + path] = body chapters.append(dict(index=index, path=path, title=f'Chapter {index}', bytes=len(body))) texts.append(dict(index=index, path=path, title=f'Chapter {index}', text=f'Chapter {index} needle unique-{index}')) packed = gzip.compress(json.dumps(dict(version=1, kind='epub-search-index', chapters=texts)).encode(), mtime=0) manifest = dict(version=1, kind='epub-chapters', chapters=chapters, search_index=dict(path='epub-search-index.json.gz', bytes=len(packed), sha256=hashlib.sha256(packed).hexdigest())) requested, held = [], [] def resource(route): raw = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)['url'][0] requested.append(raw) if hold and raw in (base + 'chapter-2.xhtml', base + 'chapter-3.xhtml'): held.append(route) elif raw.endswith('chapter-manifest.json'): route.fulfill(json=manifest, headers={'Access-Control-Allow-Origin': '*'}) elif raw.endswith('epub-search-index.json.gz'): route.fulfill(body=packed, content_type='application/gzip', headers={'Access-Control-Allow-Origin': '*'}) else: route.fulfill(body=bodies[raw], content_type='text/html', headers={'Access-Control-Allow-Origin': '*'}) self.context.route('**/api/reader-content**', resource) self.open(self.reader_url('epub-chapters', url=base + 'chapter-manifest.json')) return requested, held
def test_chapter_demand_overtakes_stalled_prefetch_and_close_cancels_queue(self): requested, held = self.chapter_book(hold=True) self.page.expose_function('__heldCount', lambda: len(held)) self.page.wait_for_function('async () => await __heldCount() === 2') self.assertEqual(self.page.evaluate('__chapterStats().active'), 2) self.assertEqual(len(held), 2) self.assertTrue(self.page.evaluate('__goChapter(40)')) self.assertTrue(any(url.endswith('chapter-40.xhtml') for url in requested)) self.assertEqual(self.page.locator('.reader-epub-chapter[data-chapter="2"]').count(), 0) self.page.evaluate('window.dispatchEvent(new Event("voice-reader-dispose"))') self.page.wait_for_function('() => __chapterStats().active === 0 && __chapterStats().pending === 0') for route in held: route.abort() self.assertEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'disposed') self.assertEqual(self.page.evaluate('__chapterStats().bytes'), 0)
def test_chapter_window_preserves_geometry_selection_and_complete_search(self): requested, _held = self.chapter_book() for width in (1100, 390): with self.subTest(width=width): self.page.set_viewport_size(dict(width=width, height=800)) for chapter in (1, 10, 20, 30, 40, 50, 60): self.assertTrue(self.page.evaluate('__goChapter', chapter)) self.page.wait_for_function('() => document.querySelectorAll(".reader-epub-chapter").length <= 12 && __chapterStats().pending === 0') self.assertGreater(self.page.locator('.reader-chapter-placeholder').count(), 0) self.assertTrue(self.page.evaluate('__goChapter(1)')) self.page.wait_for_function('() => __chapterStats().pending === 0') self.page.evaluate('async () => {await __goChapter(3); await __goChapter(2); await __goChapter(1);}') self.page.evaluate('''() => { window.__pinned = document.querySelector('.reader-epub-chapter[data-chapter="1"]'); window.__pinnedMiddle = document.querySelector('.reader-epub-chapter[data-chapter="2"]'); const range = document.createRange(); range.setStart(__pinned.querySelector('p').firstChild, 0); range.setEnd(document.querySelector('.reader-epub-chapter[data-chapter="3"] p').firstChild, 3); getSelection().removeAllRanges(); getSelection().addRange(range); }''') self.assertTrue(self.page.evaluate('__goChapter(60)')) self.page.wait_for_function('() => __chapterStats().pending === 0') self.assertTrue(self.page.evaluate('__pinned.isConnected')) self.assertTrue(self.page.evaluate('__pinnedMiddle.isConnected')) self.page.evaluate('getSelection().removeAllRanges(); document.querySelector("#viewport").dispatchEvent(new Event("scroll"))') self.assertTrue(self.page.evaluate('__goChapter(30)')) self.page.wait_for_function('() => __chapterStats().pending === 0') self.page.wait_for_function('() => !__pinned.isConnected') marker = self.page.locator('.reader-chapter-placeholder[data-chapter="1"]') self.assertGreater(marker.evaluate('node => node.getBoundingClientRect().height'), 1600) before = self.page.locator('#viewport').evaluate('node => node.scrollHeight') before_rows = self.page.locator('.epub-frame > [data-chapter]').evaluate_all('nodes => nodes.map(node => [node.dataset.chapter, node.className, node.getBoundingClientRect().height, node.offsetTop])') if width == 1100: self.page.route('**/*chapter-1.xhtml', lambda route: route.fulfill(status=503, body='temporary fixture failure')) self.assertTrue(self.page.evaluate('async () => {try {await __goChapter(1); return false;} catch (_) {return true;}}')) self.assertGreater(marker.evaluate('node => node.getBoundingClientRect().height'), 1600) self.page.unroute('**/*chapter-1.xhtml') self.assertTrue(self.page.evaluate('__goChapter(1)')) self.page.wait_for_function('() => __chapterStats().pending === 0') after = self.page.locator('#viewport').evaluate('node => node.scrollHeight') after_rows = self.page.locator('.epub-frame > [data-chapter]').evaluate_all('nodes => nodes.map(node => [node.dataset.chapter, node.className, node.getBoundingClientRect().height, node.offsetTop])') self.assertAlmostEqual(before, after, delta=3, msg=json.dumps(dict(before=before_rows, after=after_rows))) self.assertEqual(self.page.evaluate('__query("needle")'), 60) self.search('needle') self.page.locator('.full-search-result').first.click() self.page.wait_for_function('() => document.querySelector(".reader-epub-chapter[data-chapter=\\"1\\"] mark")') self.assertEqual(self.page.locator('mark.full-search-highlight').text_content(), 'needle') self.assertGreater(sum(url.endswith('chapter-1.xhtml') for url in requested), 1)
def docx_url(self): return self.reader_url('docx', url='https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/' + 'a' * 64 + '/document.docx')
def image_docx(self, image=None, repeats=3, font=None): support = fixtures.support with zipfile.ZipFile(io.BytesIO(support.minimal_docx())) as archive: files = {name: archive.read(name) for name in archive.namelist()} files['[Content_Types].xml'] = files['[Content_Types].xml'].decode().replace('</Types>', '<Default Extension="png" ContentType="image/png"/></Types>') files['word/_rels/document.xml.rels'] = '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="image" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image.png"/></Relationships>' files['word/media/image.png'] = image if image is not None else support.PNG_BYTES drawing = '''<w:p><w:r><w:drawing><wp:inline xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"><wp:extent cx="1524000" cy="762000"/><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:blipFill><a:blip xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" r:embed="image"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1524000" cy="762000"/></a:xfrm><a:prstGeom prst="rect"/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>''' files['word/document.xml'] = files['word/document.xml'].decode().replace('<w:sectPr/>', drawing * repeats + '<w:sectPr/>') if font is not None: files['[Content_Types].xml'] = files['[Content_Types].xml'].replace('</Types>', '<Default Extension="odttf" ContentType="application/vnd.openxmlformats-officedocument.obfuscatedFont"/><Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/></Types>') files['word/_rels/document.xml.rels'] = files['word/_rels/document.xml.rels'].replace('</Relationships>', '<Relationship Id="fontTable" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml"/></Relationships>') files['word/fontTable.xml'] = '<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:font w:name="FixtureFont"><w:embedRegular r:id="font" w:fontKey="{00000000-0000-0000-0000-000000000000}"/></w:font></w:fonts>' files['word/_rels/fontTable.xml.rels'] = '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="font" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/font" Target="fonts/font.odttf"/></Relationships>' files['word/fonts/font.odttf'] = font files['word/document.xml'] = files['word/document.xml'].replace('<w:r><w:t>', '<w:r><w:rPr><w:rFonts w:ascii="FixtureFont" w:hAnsi="FixtureFont"/></w:rPr><w:t>') return support.zip_bytes(files)
def test_real_docx_images_use_owned_blob_urls_and_release_on_close(self): self.page.add_init_script('''window.__created = []; window.__revoked = []; const create = URL.createObjectURL.bind(URL), revoke = URL.revokeObjectURL.bind(URL); URL.createObjectURL = blob => { const url=create(blob); __created.push(url); return url; }; URL.revokeObjectURL = url => { __revoked.push(url); return revoke(url); };''') font = (fixtures.support.ROOT / 'static/vendor/standard_fonts/LiberationSans-Regular.ttf').read_bytes() self.serve(self.image_docx(font=font), 'application/octet-stream') self.open(self.docx_url()) self.page.wait_for_function('() => document.querySelectorAll(".docx-body img").length === 3 && [...document.querySelectorAll(".docx-body img")].every(image => image.naturalWidth > 0)') self.assertTrue(all(url.startswith('blob:') for url in self.page.locator('.docx-body img').evaluate_all('images => images.map(image => image.src)'))) self.assertEqual(self.page.evaluate('__revoked.length'), 0) self.assertEqual(self.page.evaluate('async () => (await document.fonts.load("16px FixtureFont")).length'), 1) self.assertTrue(self.page.evaluate('[...document.fonts].some(font => font.family === "FixtureFont" && font.status === "loaded")')) self.assertEqual(self.page.evaluate('__created.length'), 2) self.page.evaluate('window.dispatchEvent(new Event("voice-reader-dispose"))') self.assertEqual(self.page.evaluate('__created.slice().sort()'), self.page.evaluate('__revoked.slice().sort()'))
def test_docx_failure_and_late_render_cannot_leak_blob_assets(self): script = '''window.docx = { parseAsync: async () => ({blobToURL: blob => URL.createObjectURL(blob)}), renderDocument: async doc => { window.__ownedUrl = doc.blobToURL(new Blob(['font']), 'font.ttf'); window.__lateBlob = () => doc.blobToURL(new Blob(['late']), 'image.png'); if (location.search.includes('hold=1')) await new Promise(resolve => {window.__releaseDocx = resolve;}); throw new Error('render fixture failure'); } };''' self.page.route('**/static/vendor/docx-preview.min.*.js', lambda route: route.fulfill(content_type='text/javascript', body=script)) self.page.add_init_script('''window.__revoked = []; const revoke=URL.revokeObjectURL.bind(URL); URL.revokeObjectURL = url => {__revoked.push(url); revoke(url);};''') self.serve(fixtures.support.minimal_docx(), 'application/octet-stream') for hold in (False, True): with self.subTest(hold=hold): self.page.goto(self.docx_url() + ('&hold=1' if hold else '')) self.page.wait_for_function('() => !!window.__ownedUrl') if hold: self.page.evaluate('window.dispatchEvent(new Event("voice-reader-dispose")); __releaseDocx()') else: self.page.wait_for_function('() => document.documentElement.dataset.readerPhase === "failed"') self.assertEqual(self.page.evaluate('__revoked'), [self.page.evaluate('__ownedUrl')]) self.assertIsNone(self.page.evaluate('__lateBlob()'))
def test_dom_snapshot_reuses_text_after_highlights_and_invalidates_external_edits(self): self.expose() body = '<p><span>nee</span><b>dle</b> otherword</p>' + '<p>ordinary</p>' * 4000 + '<p>tail needle</p>' for extension in ('html', 'md', 'txt', 'docx'): with self.subTest(extension=extension): if extension == 'docx': self.page.route('**/static/vendor/docx-preview.min.*.js', lambda route: route.fulfill(content_type='text/javascript', body='window.docx={parseAsync:async()=>({blobToURL:()=>null}),renderDocument:async()=>{const node=document.createElement("div");node.innerHTML=' + json.dumps(body) + ';return [node];}};')) self.serve(fixtures.support.minimal_docx(), 'application/octet-stream') self.open(self.docx_url()) else: self.serve('needle otherword\n' + 'ordinary\n' * 4000 + 'tail needle' if extension == 'txt' else body) self.open(self.reader_url(extension)) self.assertEqual(self.page.evaluate('__query("needle")'), 2) self.page.evaluate('window.__originalSnapshot = __snapshot(); __walkProbe()') self.assertEqual(self.page.evaluate('__query("otherword")'), 1) self.assertTrue(self.page.evaluate('__snapshot() === __originalSnapshot')) self.assertLess(self.page.evaluate('__visits'), 10) self.assertEqual(self.page.evaluate('__query("needle")'), 2) self.assertEqual(self.page.evaluate('''() => { const root = document.querySelector('.html-frame')?.contentDocument.body || document.querySelector('#content'); setTimeout(() => root.prepend(root.ownerDocument.createTextNode('prefix needle ')), 0); return __query('needle'); }'''), 3) self.page.evaluate('''() => { const root = document.querySelector('.html-frame')?.contentDocument.body || document.querySelector('#content'); root.append(root.ownerDocument.createTextNode(' added needle')); }''') self.assertEqual(self.page.evaluate('__query("needle")'), 4) self.assertFalse(self.page.evaluate('__snapshot() === __originalSnapshot')) self.page.evaluate('window.dispatchEvent(new Event("voice-reader-dispose"))') self.assertTrue(self.page.evaluate('__snapshot() === null'))
def test_oversized_dom_snapshot_is_uncached_without_losing_matches(self): self.expose() self.serve('a' * (4 * 1024 * 1024) + ' needle') self.open(self.reader_url('txt')) self.assertEqual(self.page.evaluate('__query("needle")'), 1) self.assertIsNone(self.page.evaluate('__snapshot().value')) self.assertEqual(self.page.evaluate('__query("needle")'), 1)
if __name__ == '__main__': unittest.main()112 unmodified lines113114115116117118112 unmodified linesself.page.locator("#page-number").fill(str(number))self.page.locator("#page-number").press("Enter")def test_first_stream_fast_pdf_later_pages_skip_images_and_zoom_keeps_canvas(self):shell = self.open()shell.evaluate("s => {window.__firstShell=s; window.__beforeTop=s.getBoundingClientRect().top;}")112 unmodified lines113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148112 unmodified linesself.page.locator("#page-number").fill(str(number))self.page.locator("#page-number").press("Enter")def test_dark_theme_keeps_preview_and_pdf_handoff_consistent(self):shell = self.open()self.page.set_viewport_size({"width": 390, "height": 844})def assert_theme(surface, theme):self.page.evaluate("theme => document.documentElement.dataset.theme = theme", theme)self.assertEqual(surface.evaluate("e => getComputedStyle(e).filter"),"invert(0.9) hue-rotate(180deg)" if theme == "dark" else "none")bounds = shell.bounding_box()pixels = Image.open(io.BytesIO(self.page.screenshot())).convert('RGB')pixel = pixels.getpixel((round(bounds['x'] + bounds['width'] * .8), round(bounds['y'] + 30)))return pixelpreview = shell.locator('img.ready')dark = assert_theme(preview, 'dark')light = assert_theme(preview, 'light')self.assertLess(max(dark), 50)self.assertGreater(min(light), 240)assert_theme(preview, 'dark')self.page.evaluate('window.__releaseDocument()')canvas = shell.locator('canvas.ready')canvas.wait_for()self.assertEqual(shell.locator('img').count(), 0)self.assertEqual(shell.locator('.reader-pdf-text').evaluate("e => getComputedStyle(e).filter"), 'none')dark = assert_theme(canvas, 'dark')light = assert_theme(canvas, 'light')self.assertNotEqual(dark, light)assert_theme(canvas, 'dark')self.page.evaluate("document.querySelector('#content').dataset.mode = 'image-pages'")self.assertEqual(canvas.evaluate("e => getComputedStyle(e).filter"), 'none')self.assertEqual(self.errors, [])def test_first_stream_fast_pdf_later_pages_skip_images_and_zoom_keeps_canvas(self):shell = self.open()shell.evaluate("s => {window.__firstShell=s; window.__beforeTop=s.getBoundingClientRect().top;}")
136 unmodified lines1371381391401411421431441451168 unmodified lines1314131513161317131813191320136 unmodified lines}) });"""DOCX_SCRIPT = """window.docx = { renderAsync: (_bytes, body) => new Promise((resolve) => setTimeout(() => {body.textContent = 'DOCX readable'; resolve();}, 20)) };"""PNG_BYTES = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"1168 unmodified linespage = context.new_page()page.route("**/static/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))page.route("**/static/vendor/jszip.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body="window.JSZip=function(){window.__archiveParserStarted=true};"))page.route("**/static/vendor/docx-preview.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body="window.docx={renderAsync(){window.__archiveParserStarted=true}};"))page.route("**/static/foliate-reader/view.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body="customElements.define('foliate-view', class extends HTMLElement { open() { window.__archiveParserStarted=true; throw new Error('parser must not start'); } });"))page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/octet-stream", body=payload))source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/bomb.epub" if extension == "epub" else f"https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/{'a' * 64}/docx-native-v1/document.docx"136 unmodified lines1371381391401411421431441451461168 unmodified lines1315131613171318131913201321136 unmodified lines}) });"""DOCX_SCRIPT = """window.docx = { parseAsync: async () => ({blobToURL: blob => URL.createObjectURL(blob)}),renderDocument: () => new Promise(resolve => setTimeout(() => {resolve([document.createTextNode('DOCX readable')]);}, 20)) };"""PNG_BYTES = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"1168 unmodified linespage = context.new_page()page.route("**/static/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))page.route("**/static/vendor/jszip.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body="window.JSZip=function(){window.__archiveParserStarted=true};"))page.route("**/static/vendor/docx-preview.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body="window.docx={parseAsync(){window.__archiveParserStarted=true}};"))page.route("**/static/foliate-reader/view.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body="customElements.define('foliate-view', class extends HTMLElement { open() { window.__archiveParserStarted=true; throw new Error('parser must not start'); } });"))page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/octet-stream", body=payload))source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/bomb.epub" if extension == "epub" else f"https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/{'a' * 64}/docx-native-v1/document.docx"
2242 unmodified lines22432244224522462247224822492242 unmodified lineswith self.subTest(extension=extension):if extension == 'docx':self.page.route('**/static/vendor/docx-preview.min.*.js', lambda route: route.fulfill(content_type='text/javascript', body="window.docx = {renderAsync: async (_bytes, body) => {body.innerHTML = " + json.dumps(html) + ";}}"))self.serve(support.minimal_docx(), 'application/octet-stream')else:self.serve('before needle after\n' + 'ordinary\n' * 8000 + 'last needle' if extension == 'txt' else html,2242 unmodified lines22432244224522462247224822492242 unmodified lineswith self.subTest(extension=extension):if extension == 'docx':self.page.route('**/static/vendor/docx-preview.min.*.js', lambda route: route.fulfill(content_type='text/javascript', body="window.docx = {parseAsync: async () => ({blobToURL:()=>null}), renderDocument: async () => {const body=document.createElement('div'); body.innerHTML = " + json.dumps(html) + ";return [body];}}"))self.serve(support.minimal_docx(), 'application/octet-stream')else:self.serve('before needle after\n' + 'ordinary\n' * 8000 + 'last needle' if extension == 'txt' else html,
3 unmodified lines4567894 unmodified lines141516171819116 unmodified lines1361371381391401413 unmodified linesimport unittestimport urllib.parseimport zipfilefrom tests.test_reader_performance import (STORE_SCRIPT,4 unmodified linessync_playwright,zip_bytes,)@unittest.skipIf(sync_playwright is None, "install requirements-test.txt for reader style tests")116 unmodified linesfor selector in (".reader-error", ".epub-frame .reader-markdown", ".reader-markdown a"):self.assert_contrast(selector)def open_theme_fixture(self, extension, data):self.page.route("**/api/reader-content**", lambda route: route.fulfill(body=data))source = urllib.parse.quote(3 unmodified lines456789104 unmodified lines15161718192021116 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202213 unmodified linesimport unittestimport urllib.parseimport zipfilefrom PIL import Imagefrom tests.test_reader_performance import (STORE_SCRIPT,4 unmodified linessync_playwright,zip_bytes,)from tests import test_reader_performance as support@unittest.skipIf(sync_playwright is None, "install requirements-test.txt for reader style tests")116 unmodified linesfor selector in (".reader-error", ".epub-frame .reader-markdown", ".reader-markdown a"):self.assert_contrast(selector)def test_pdf_page_surface_follows_dark_theme_without_touching_text_layer(self):self.page.route("**/api/reader-content**", lambda route: route.fulfill(content_type="application/pdf", body=support.minimal_pdf()))source = urllib.parse.quote("https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/theme.pdf", safe="")self.page.goto(f"{self.origin}/static/reader.html?url={source}&ext=pdf&title=Theme PDF",wait_until="domcontentloaded",)self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")canvas = self.page.locator('.reader-content[data-mode="pdf"] .reader-page canvas').firstself.page.locator('.reader-page canvas.ready').first.wait_for()self.page.wait_for_function("() => document.querySelector('.reader-page')?.dataset.textReady === '1'")self.page.locator('.reader-page').first.evaluate("node => window.__themePage = node")text_layer = self.page.locator('.reader-pdf-text').firstself.assertEqual(text_layer.evaluate("e => getComputedStyle(e).filter"), "none")self.assertEqual(canvas.evaluate("e => getComputedStyle(e).filter"), "invert(0.9) hue-rotate(180deg)")self.page.locator("#history").click()for theme in ('light', 'dark'):self.page.locator("#theme-toggle").click()self.settle()self.assertEqual(canvas.evaluate("e => getComputedStyle(e).filter"), 'none' if theme == 'light' else 'invert(0.9) hue-rotate(180deg)')self.page.locator("#history").click()for width in (1100, 390):self.page.set_viewport_size({"width": width, "height": 844})self.page.locator('.reader-pdf-text-run').first.evaluate("node => {const range=document.createRange(); range.selectNodeContents(node); getSelection().removeAllRanges(); getSelection().addRange(range);}")selected = self.page.evaluate("getSelection().toString()")self.assertEqual(selected, 'Reader PDF')original_pixels = canvas.evaluate("c => c.toDataURL()")for theme in ("dark", "light", "dark"):self.page.evaluate("theme => document.documentElement.dataset.theme = theme", theme)self.settle()bounds = self.page.locator('.reader-page').first.bounding_box()png = Image.open(io.BytesIO(self.page.screenshot())).convert("RGB")pixel = png.getpixel((round(bounds['x'] + bounds['width'] * .85), round(bounds['y'] + 30)))self.assertTrue(max(pixel) < 50 if theme == "dark" else min(pixel) > 240, (theme, pixel))self.assertEqual(canvas.evaluate("c => c.toDataURL()"), original_pixels)self.assertTrue(self.page.evaluate("document.querySelector('.reader-page') === __themePage"))self.assertEqual(self.page.evaluate("getSelection().toString()"), selected)self.page.evaluate("getSelection().removeAllRanges()")self.page.locator('#history').click()self.page.locator('#full-search-toggle').click()self.page.locator('#full-search-input').fill('Reader')self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")mark = self.page.locator('.reader-page mark.full-search-highlight').firstself.assertEqual(mark.text_content(), 'Reader')self.assertEqual(mark.evaluate("e => getComputedStyle(e).filter"), 'none')self.assertNotEqual(mark.evaluate("e => getComputedStyle(e).backgroundColor"), 'rgba(0, 0, 0, 0)')self.page.locator('#content').evaluate("node => node.dataset.mode = 'image-pages'")self.assertEqual(self.page.locator('.reader-page canvas').first.evaluate("e => getComputedStyle(e).filter"), 'none')def test_pdf_page_images_follow_theme_but_original_images_do_not(self):output = io.BytesIO()Image.new('RGB', (600, 800), 'white').save(output, 'WEBP')self.page.route('**/api/reader-content**', lambda route: route.fulfill(json={"version": 2, "kind": "pdf-pages", "page_count": 1}))self.page.route('**/pages/page-*.webp', lambda route: route.fulfill(content_type='image/webp', body=output.getvalue()))source = urllib.parse.quote('https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/' + 'a' * 64 + '/page-manifest.json', safe='')self.page.goto(f'{self.origin}/static/reader.html?url={source}&ext=pdf-pages')image = self.page.locator('.reader-page img.ready').firstimage.wait_for()original = image.get_attribute('src')for width in (1100, 390):self.page.set_viewport_size({'width': width, 'height': 844})for theme in ('dark', 'light', 'dark'):self.page.evaluate('theme => document.documentElement.dataset.theme = theme', theme)self.settle()bounds = image.bounding_box()png = Image.open(io.BytesIO(self.page.screenshot())).convert('RGB')pixel = png.getpixel((round(bounds['x'] + bounds['width'] * .8), round(bounds['y'] + 30)))self.assertTrue(max(pixel) < 50 if theme == 'dark' else min(pixel) > 240, (theme, pixel))self.assertEqual(image.get_attribute('src'), original)self.page.evaluate("document.querySelector('#content').dataset.mode = 'image-pages'")self.assertEqual(image.evaluate('e => getComputedStyle(e).filter'), 'none')def open_theme_fixture(self, extension, data):self.page.route("**/api/reader-content**", lambda route: route.fulfill(body=data))source = urllib.parse.quote(
READER_OPTIMIZATION_REPORT.mdAdded+74
READER_PDF_THEME_REPORT.mdAdded+28
static/reader-chapter-repository.js+75-1
static/reader.css+18
static/reader.html+1-1
static/reader.js+255-58
tests/test_reader_chapter_scheduler.jsAdded+57
tests/test_reader_optimizations.pyAdded+252
tests/test_reader_pdf_hybrid.py+30
tests/test_reader_performance.py+5-4
tests/test_reader_refactor.py+1-1
tests/test_reader_style.py+80