vomebook commited on
Commit
6b4bc4c
·
1 Parent(s): ff072d5

perf: bound Reader chapter retention and reuse text with PDF night mode

Browse files
READER_OPTIMIZATION_REPORT.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reader Retention And Search Reuse
2
+
3
+ ## Local Implementation (2026-10-09)
4
+
5
+ Implemented in the HF and GitHub Search development checkouts. This report
6
+ describes local fixtures and builds; this optimization set has not been deployed.
7
+ Existing concurrent search/paging publications were retained as the new baseline.
8
+
9
+ - Chapter scheduling has three active slots, with at most two speculative loads.
10
+ Demand is promoted ahead of queued speculation, obsolete windows are cancelled,
11
+ and hidden-page/disposal events release speculative ownership. Cancelled creates
12
+ retain their active slot until settlement; late completion cannot delete a newer
13
+ request or insert discarded content.
14
+ - Chapter bundles reuse the existing section virtualizer and scroll anchors, with
15
+ a twelve-loaded-chapter target. Visible/nearby chapters, focused content, native
16
+ selection ranges and selected search highlights remain protected. Evicted
17
+ chapters retain equal-height placeholders and can reload through ordinary
18
+ navigation or complete-index search. Retained byte reservations are released
19
+ on eviction/closure. A formatting context prevents heading/paragraph margin
20
+ collapse from causing height drift during replacement.
21
+ - The pinned DOCX engine parses and renders through its public API. Its parsed
22
+ document owns path-deduplicated image/font/numbering Blob URLs; failures and
23
+ disposal revoke them, and late resource creation is suppressed. Real TTF loading
24
+ verifies the matching same-origin/Blob font CSP policy. No global URL API is
25
+ replaced by runtime code.
26
+ - DOM search retains one complete text snapshot across queries, accounting for
27
+ UTF-16 text and text-part metadata within 8 MiB and 32,768 parts. It retains
28
+ stable parent/checkpoint metadata, not text nodes invalidated by highlighting.
29
+ External mutations, streaming appends, page-label changes and TOC replacement
30
+ disable reuse. Edits during asynchronous cached scanning cause a fresh scan.
31
+ Oversized documents remain fully searched without caching. Disposal clears the
32
+ snapshot; result totals, matching rules and accessible result pages are unchanged.
33
+
34
+ ## Controlled A/B Observations
35
+
36
+ The committed pre-change Reader was replayed against the working-tree Reader in
37
+ fresh Chromium contexts. DOM measurements used six alternating rounds per site,
38
+ 16,000 ordinary paragraphs, an early cross-query match and a tail match. Timing
39
+ covers the actual Reader search routine, not network transfer. Both variants
40
+ returned the same exact totals and visible selected text.
41
+
42
+ | Site | First Search Before/After | Repeated Search Before/After | Repeated Text-Node Visits |
43
+ | --- | --- | --- | --- |
44
+ | HF | 153.55 / 155.10 ms | 156.75 / 1.55 ms | 16,005 / 2 |
45
+ | Pages | 157.15 / 151.65 ms | 171.45 / 1.70 ms | 16,005 / 2 |
46
+
47
+ Both sites' 60-chapter navigation fixture retained 60 loaded chapters before,
48
+ versus 12 after, with lightweight placeholders for previously loaded content.
49
+ This is a DOM retention observation, not a measured heap reduction percentage.
50
+
51
+ A real pinned-engine DOCX fixture repeated one 788,084-byte PNG three times.
52
+ Before, the three data-URL attributes contained 3,152,406 characters in total.
53
+ After, all three rendered images shared one 788,084-byte Blob URL; their attributes
54
+ totalled 192 characters. This measures resource representation and URL reuse,
55
+ not total browser memory or a production loading-speed percentage.
56
+
57
+ Desktop (1100px) and mobile (390px) screenshots confirmed all three images render
58
+ without overlapping Reader controls. Separate regressions verify embedded-font
59
+ loading, URL revocation, blocked late creation, failed chapter reload recovery,
60
+ cross-chapter selections, exact full-book totals and last/first chapter navigation.
61
+
62
+ ## Verification
63
+
64
+ - Six focused optimization browser cases passed on each site, without skips.
65
+ - Existing chapter browser regressions passed: fifteen per site.
66
+ - Existing DOM search/navigation regressions passed: seven per site.
67
+ - Format preparation, mocked DOCX, ZIP admission and chapter resource/loading
68
+ regressions passed on their corresponding site-specific fixtures.
69
+ - Scheduler ownership/promotion/cancellation contracts passed on both sites.
70
+ - Both content-hashed esbuild 0.28.2 artifacts passed their release gates; the
71
+ shared-source cross-project gate passed. Generated artifacts stay in `/tmp/opencode`.
72
+
73
+ Detailed commands and required workflow steps are in each project's `TESTING.md`.
74
+ Production acceptance belongs to the eventual deployment, not these local results.
READER_PDF_THEME_REPORT.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PDF Reader Theme
2
+
3
+ ## Local Change (2026-10-10)
4
+
5
+ Dark mode now filters PDF content surfaces using `invert(.9) hue-rotate(180deg)`:
6
+ native PDF.js canvases and PDF-pages images/canvases. The entire rendered PDF
7
+ page, including embedded illustrations, is adjusted. Light mode restores the
8
+ original presentation. PDF files and canvas source pixels remain unchanged;
9
+ theme switching needs no document reload or PDF rerender.
10
+
11
+ Transparent text layers, selections and search highlights remain unfiltered
12
+ above the page. Ordinary image documents, image-pages, HTML and audio/video
13
+ retain their existing presentation. No HTML theme changes were made in this task.
14
+
15
+ ## Verification
16
+
17
+ - HF: three theme cases and three existing PDF selection/search cases passed.
18
+ - Pages: two theme cases and four existing PDF search cases passed.
19
+ - Native PDF screenshot pixels verify dark paper and light paper at 1100px and
20
+ 390px widths, while source canvas data, page identity and selected text remain
21
+ unchanged. PDF-pages tests preserve the image URL and exclude image-pages.
22
+ - HF's hybrid preview-to-canvas theme handoff passed. The current Pages checkout
23
+ has an image-only PDF-pages renderer; applying HF hybrid tests to that checkout
24
+ was an incorrect test selection, not evidence of a Pages hybrid regression.
25
+ - Reader architecture/regression and cross-project release gates passed.
26
+
27
+ This change remains local and has not been published. Commands are recorded in
28
+ each project's `TESTING.md`.
static/reader-chapter-repository.js CHANGED
@@ -97,5 +97,79 @@
97
  });
98
  }
99
 
100
- root.VoiceOfMLReaderChapters = Object.freeze({ createChapterRepository });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  })(typeof self !== "undefined" ? self : globalThis);
 
97
  });
98
  }
99
 
100
+ function createChapterScheduler({ create, concurrency = 3, speculativeLimit = 2 }) {
101
+ const records = new Map(), active = new Set();
102
+ let disposed = false, scheduled = false;
103
+ const abortError = () => new DOMException("Chapter load cancelled", "AbortError");
104
+ function cancel(record) {
105
+ if (records.get(record.index) !== record) return;
106
+ records.delete(record.index);
107
+ record.controller.abort(abortError());
108
+ record.reject(record.controller.signal.reason);
109
+ }
110
+ function pump() {
111
+ scheduled = false;
112
+ if (disposed) return;
113
+ while (active.size < concurrency) {
114
+ const queued = [...records.values()].filter(record => !record.started);
115
+ const speculative = [...active].filter(record => !record.demand).length;
116
+ const record = queued.find(record => record.demand) ||
117
+ (speculative < speculativeLimit && queued.find(record => !record.demand));
118
+ if (!record) break;
119
+ record.started = true;
120
+ active.add(record);
121
+ Promise.resolve().then(() => {
122
+ record.controller.signal.throwIfAborted();
123
+ return create(record.index, record.controller.signal, record.demand ? "high" : "low");
124
+ }).then(value => {
125
+ record.controller.signal.throwIfAborted();
126
+ record.resolve(value);
127
+ }).catch(record.reject).finally(() => {
128
+ active.delete(record);
129
+ if (records.get(record.index) === record) records.delete(record.index);
130
+ schedule();
131
+ });
132
+ }
133
+ }
134
+ function schedule() {
135
+ if (scheduled || disposed) return;
136
+ scheduled = true;
137
+ Promise.resolve().then(pump);
138
+ }
139
+ function load(index, demand = true) {
140
+ if (disposed) return Promise.reject(abortError());
141
+ if (demand) {
142
+ for (const record of records.values())
143
+ if (!record.demand && record.index !== index) cancel(record);
144
+ }
145
+ let record = records.get(index);
146
+ if (record) {
147
+ record.demand ||= demand;
148
+ schedule();
149
+ return record.promise;
150
+ }
151
+ record = { index, demand, started: false, controller: new root.AbortController() };
152
+ record.promise = new Promise((resolve, reject) => Object.assign(record, { resolve, reject }));
153
+ records.set(index, record);
154
+ schedule();
155
+ return record.promise;
156
+ }
157
+ function prefetch(indices) {
158
+ const wanted = new Set(indices);
159
+ for (const record of records.values())
160
+ if (!record.demand && !wanted.has(record.index)) cancel(record);
161
+ for (const index of wanted) load(index, false).catch(() => {});
162
+ }
163
+ function dispose() {
164
+ disposed = true;
165
+ for (const record of records.values()) cancel(record);
166
+ }
167
+ return Object.freeze({
168
+ load, prefetch, dispose,
169
+ get activeCount() { return active.size; },
170
+ get pendingCount() { return records.size; }
171
+ });
172
+ }
173
+
174
+ root.VoiceOfMLReaderChapters = Object.freeze({ createChapterRepository, createChapterScheduler });
175
  })(typeof self !== "undefined" ? self : globalThis);
static/reader.css CHANGED
@@ -960,6 +960,16 @@ body {
960
  .reader-page canvas.ready {
961
  opacity: 1;
962
  }
 
 
 
 
 
 
 
 
 
 
963
  .reader-pdf-text {
964
  position: absolute;
965
  inset: 0;
@@ -1021,6 +1031,9 @@ body {
1021
  margin: 0 auto;
1022
  background: #fff;
1023
  }
 
 
 
1024
  .reader-chapter-sentinel {
1025
  display: block;
1026
  width: 100%;
@@ -1032,6 +1045,11 @@ body {
1032
  overflow: hidden;
1033
  pointer-events: none;
1034
  }
 
 
 
 
 
1035
  .reader-content[data-mode="audio"],
1036
  .reader-content[data-mode="video"] {
1037
  width: 100%;
 
960
  .reader-page canvas.ready {
961
  opacity: 1;
962
  }
963
+ /* PDF pages keep their transparent text/selection layer above the themed page. */
964
+ :root[data-theme="dark"] .reader-content[data-mode="pdf"] .reader-page canvas,
965
+ :root[data-theme="dark"] .reader-content[data-mode="pdf-pages"] .reader-page canvas,
966
+ :root[data-theme="dark"] .reader-content[data-mode="pdf-pages"] .reader-page > img {
967
+ filter: invert(0.9) hue-rotate(180deg);
968
+ }
969
+ :root[data-theme="dark"] .reader-content[data-mode="pdf"] .reader-page,
970
+ :root[data-theme="dark"] .reader-content[data-mode="pdf-pages"] .reader-page {
971
+ background: #202428;
972
+ }
973
  .reader-pdf-text {
974
  position: absolute;
975
  inset: 0;
 
1031
  margin: 0 auto;
1032
  background: #fff;
1033
  }
1034
+ .reader-epub-chapter {
1035
+ display: flow-root;
1036
+ }
1037
  .reader-chapter-sentinel {
1038
  display: block;
1039
  width: 100%;
 
1045
  overflow: hidden;
1046
  pointer-events: none;
1047
  }
1048
+ .reader-chapter-load-error {
1049
+ min-height: 40px;
1050
+ opacity: 1;
1051
+ pointer-events: auto;
1052
+ }
1053
  .reader-content[data-mode="audio"],
1054
  .reader-content[data-mode="video"] {
1055
  width: 100%;
static/reader.html CHANGED
@@ -5,7 +5,7 @@
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
  <meta
7
  http-equiv="Content-Security-Policy"
8
- 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:;"
9
  />
10
  <title>VoiceOfML Reader</title>
11
  <script>
 
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
  <meta
7
  http-equiv="Content-Security-Policy"
8
+ 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:;"
9
  />
10
  <title>VoiceOfML Reader</title>
11
  <script>
static/reader.js CHANGED
@@ -561,6 +561,7 @@ let foliateContinuous = false,
561
  foliateScrollFrame = 0,
562
  foliateWindowFrame = 0;
563
  let initialReaderTargetSection = null;
 
564
  const FOLIATE_PREFETCH_SECTIONS = 6;
565
  const FOLIATE_PREFETCH_MARGIN = 4000;
566
  const FOLIATE_LOADED_SECTION_LIMIT = 12;
@@ -2632,6 +2633,7 @@ function fetchReaderUrl(rawUrl, requestInit = {}) {
2632
  throw Object.assign(new Error(`HTTP ${response.status}`), { status: response.status });
2633
  }).catch((error) => {
2634
  assertReaderActive();
 
2635
  if (retryableReaderProxyError(error)) throw error;
2636
  return fetchWithReaderTimeout(rawUrl, READER_PROXY_TIMEOUT_MS, requestInit);
2637
  });
@@ -4561,11 +4563,12 @@ async function renderChapterManifest(prepared) {
4561
  const frame = document.createElement("div");
4562
  frame.className = "epub-frame";
4563
  content.appendChild(frame);
4564
- const loaded = new Set(),
4565
- pending = new Map(),
4566
  manifestBase = trustedReaderAssetManifestUrl(chapterManifestUrl || sourceUrl);
4567
  const chapterByIndex = new Map(manifest.chapters.map((chapter) => [chapter.index, chapter]));
4568
  const chapterPrefetchCount = 6;
 
 
4569
  let chapterPreviousObserver = null;
4570
  const chapterBudget = VoiceOfMLReaderSecurity.createByteBudget();
4571
  if (!manifestBase) throw new Error("EPUB_INVALID_MANIFEST_PATH");
@@ -4609,7 +4612,15 @@ async function renderChapterManifest(prepared) {
4609
  );
4610
  if (existing) return existing;
4611
  const next = nextChapterNode(Number(article.dataset.chapter), ".reader-epub-chapter");
4612
- foliateScrollAnchors.preserve(() => frame.insertBefore(article, next || null));
 
 
 
 
 
 
 
 
4613
  foliateScrollAnchors.observe(article);
4614
  return article;
4615
  };
@@ -4652,14 +4663,13 @@ async function renderChapterManifest(prepared) {
4652
  activate: (generation) => activateChapter(manifest.chapters[item.chapter - 1], generation, item.fragment)
4653
  }))
4654
  );
4655
- const fetchChapter = async (chapter) => {
4656
- assertReaderActive();
4657
- if (loaded.has(chapter.index)) return;
4658
- if (pending.has(chapter.index)) return pending.get(chapter.index);
4659
- const task = (async () => {
4660
  const url = chapterUrl(chapter);
4661
  if (!url) throw new Error("EPUB_INVALID_PATH");
4662
- const result = await fetchReaderUrl(url);
4663
  if (!result.ok) throw new Error(`HTTP ${result.status}`);
4664
  const bytes = await VoiceOfMLReaderSecurity.readBytes(
4665
  result,
@@ -4669,6 +4679,7 @@ async function renderChapterManifest(prepared) {
4669
  let inserted = false;
4670
  try {
4671
  assertReaderActive();
 
4672
  const doc = parseChapterDocument(new TextDecoder().decode(bytes));
4673
  for (const element of doc.querySelectorAll("*")) {
4674
  for (const name of ["src", "href", "poster", "xlink:href"])
@@ -4689,16 +4700,9 @@ async function renderChapterManifest(prepared) {
4689
  article.innerHTML = doc.body ? doc.body.innerHTML : "";
4690
  // The generated text index includes head text (e.g. the chapter title).
4691
  article._chapterSearchHead = doc.head ? document.importNode(doc.head, true) : null;
4692
- const marker = frame.querySelector(
4693
- `.reader-chapter-sentinel[data-chapter="${chapter.index}"]`
4694
- );
4695
- if (marker) {
4696
- chapterManifestObserver.unobserve(marker);
4697
- chapterPreviousObserver.unobserve(marker);
4698
- marker.remove();
4699
- }
4700
  insertChapter(article);
4701
  loaded.add(chapter.index);
 
4702
  inserted = true;
4703
  for (const entry of navigationState.tocEntries)
4704
  if (entry.chapterIndex === chapter.index)
@@ -4707,19 +4711,32 @@ async function renderChapterManifest(prepared) {
4707
  if (next) ensureSentinel(next);
4708
  const previous = chapterAt(chapter.index - 1);
4709
  if (previous) ensureSentinel(previous, true);
 
4710
  } catch (error) {
4711
  if (!inserted) chapterBudget.release(bytes.byteLength);
4712
  throw error;
4713
  }
4714
- })().finally(() => {
4715
- pending.delete(chapter.index);
4716
- if (!loaded.has(chapter.index)) ensureSentinel(chapter);
 
 
 
 
 
 
 
 
 
 
 
4717
  });
4718
- pending.set(chapter.index, task);
4719
- return task;
4720
  };
4721
  const activateChapter = async (chapter, generation, fragment = "") => {
4722
- await fetchChapter(chapter);
 
 
 
4723
  if (!isReaderGenerationCurrent("navigation", generation)) return false;
4724
  const node = frame.querySelector(`.reader-epub-chapter[data-chapter="${chapter.index}"]`);
4725
  let id = fragment.replace(/^#/, "");
@@ -4776,22 +4793,75 @@ async function renderChapterManifest(prepared) {
4776
  reportNavigationError(error, generation);
4777
  }
4778
  });
4779
- const prefetchChapters = (startIndex) => {
4780
- const tasks = manifest.chapters
4781
- .slice(startIndex, startIndex + chapterPrefetchCount)
4782
- .map((chapter) => fetchChapter(chapter).catch(() => null));
4783
- if (tasks.length) Promise.all(tasks).catch(() => {});
4784
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4785
  chapterManifestObserver = new IntersectionObserver(
4786
- (entries) =>
4787
- entries
4788
- .filter((entry) => entry.isIntersecting)
4789
- .forEach((entry) => {
4790
- if (readerAbortController.signal.aborted) return;
4791
- const chapter = chapterAt(Number(entry.target.dataset.chapter));
4792
- if (chapter) prefetchChapters(chapter.index - 1);
4793
- }),
4794
- { root: viewport, rootMargin: "4000px 0px" }
4795
  );
4796
  chapterPreviousObserver = new IntersectionObserver((entries) => {
4797
  if (readerAbortController.signal.aborted) return;
@@ -4801,16 +4871,36 @@ async function renderChapterManifest(prepared) {
4801
  if (chapter) fetchChapter(chapter).catch(() => {});
4802
  }
4803
  }, { root: viewport });
4804
- trackReaderResource(() => {
 
 
 
 
 
 
 
 
 
 
 
 
 
4805
  chapterManifestObserver?.disconnect();
4806
  chapterPreviousObserver?.disconnect();
4807
  chapterManifestObserver = null;
4808
  chapterManifestLoader = null;
4809
- });
 
 
 
 
4810
  chapterManifestLoader = async (index) => {
4811
  const chapter = chapterAt(index);
4812
  if (!chapter) return null;
4813
- await fetchChapter(chapter);
 
 
 
4814
  return frame.querySelector(`.reader-epub-chapter[data-chapter="${index}"]`);
4815
  };
4816
  setChapterToc();
@@ -4819,6 +4909,7 @@ async function renderChapterManifest(prepared) {
4819
  const initialChapter = Number.isInteger(savedChapter)
4820
  ? Math.max(0, Math.min(manifest.chapters.length - 1, savedChapter))
4821
  : 0;
 
4822
  if (initialChapter > 0) ensureSentinel(manifest.chapters[initialChapter - 1], true);
4823
  try {
4824
  await fetchChapter(manifest.chapters[initialChapter]);
@@ -4828,7 +4919,8 @@ async function renderChapterManifest(prepared) {
4828
  code: "READER_RESTORE"
4829
  });
4830
  }
4831
- prefetchChapters(initialChapter + 1);
 
4832
  assertReaderActive();
4833
  markReaderContentReady();
4834
  status.textContent = `EPUB · ${manifest.chapters.length} 章`;
@@ -4850,12 +4942,12 @@ async function renderDocx(prepared) {
4850
  const body = document.createElement("div");
4851
  body.className = "docx-body";
4852
  content.append(styles, body);
4853
- await docx.renderAsync(bytes, body, styles, {
4854
  className: "reader-docx",
4855
  inWrapper: true,
4856
  breakPages: true,
4857
  ignoreLastRenderedPageBreak: false,
4858
- useBase64URL: true,
4859
  renderHeaders: true,
4860
  renderFooters: true,
4861
  renderFootnotes: true,
@@ -4864,11 +4956,45 @@ async function renderDocx(prepared) {
4864
  renderComments: false,
4865
  renderAltChunks: false,
4866
  debug: false
4867
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4868
  assertReaderActive();
4869
  body.classList.toggle("reader-document-dark", readerTheme === "dark");
4870
- if (!(body.textContent || "").trim() && !body.querySelector("img, table, svg, canvas"))
 
 
4871
  throw new Error("DOCX rendered no supported content");
 
4872
  const pages = [...body.querySelectorAll(":scope > .reader-docx-wrapper > section.reader-docx")];
4873
  if (pages.length) {
4874
  updateDocumentState({ pageCount: pages.length });
@@ -4899,6 +5025,10 @@ function renderImageDocument(image) {
4899
  status.textContent = "图片";
4900
  }
4901
  function disposeFormatResources(mode) {
 
 
 
 
4902
  if (mode === "swf") {
4903
  swfPlayer?.remove();
4904
  swfPlayer = null;
@@ -5422,7 +5552,7 @@ function loadPdfDocument(target = sourceUrl) {
5422
  pdfFetchPolicy = createPdfFetchPolicy();
5423
  trackReaderResource(() => { pdfFetchPolicy?.dispose(); pdfFetchPolicy = null; });
5424
  }
5425
- pdfFetchPolicy.add([sourceUrl, contentUrl]);
5426
  pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;
5427
  const options = (url) => ({
5428
  url,
@@ -6435,6 +6565,42 @@ function fullSearchEscape(value) {
6435
  }
6436
  let fullSearchActiveMarks = [];
6437
  let fullSearchDomLocator = null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6438
  readerRuntime.events.on("generation", ({ name }) => {
6439
  if (name === "search") {
6440
  fullSearchDomLocator?.dispose();
@@ -6444,6 +6610,8 @@ readerRuntime.events.on("generation", ({ name }) => {
6444
  trackReaderResource(() => {
6445
  fullSearchDomLocator?.dispose();
6446
  fullSearchDomLocator = null;
 
 
6447
  });
6448
  function createFullSearchDomLocator(root, generation) {
6449
  fullSearchDomLocator?.dispose();
@@ -6462,6 +6630,8 @@ function createFullSearchDomLocator(root, generation) {
6462
  };
6463
  const locator = {
6464
  current,
 
 
6465
  build(offsets) {
6466
  if (!current()) return;
6467
  const stride = Math.max(128, Math.ceil(offsets.length / 2048));
@@ -6499,6 +6669,7 @@ function createFullSearchDomLocator(root, generation) {
6499
  }
6500
  function clearFullSearchMarks() {
6501
  fullSearchDomLocator?.pause();
 
6502
  try {
6503
  content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());
6504
  const changedParents = new Set();
@@ -6514,6 +6685,7 @@ function clearFullSearchMarks() {
6514
  content.querySelectorAll(".reader-chapter-search-heading").forEach(node => node.remove());
6515
  } finally {
6516
  fullSearchDomLocator?.resume();
 
6517
  }
6518
  }
6519
  async function fullSearchTextNodes(root, generation, endOffset = Infinity, checkpoint = null) {
@@ -6538,6 +6710,7 @@ async function fullSearchTextNodes(root, generation, endOffset = Infinity, check
6538
  }
6539
  function highlightTextParts(parts) {
6540
  fullSearchDomLocator?.pause();
 
6541
  const marks = [];
6542
  try {
6543
  for (const { node, start, end } of [...parts].reverse()) {
@@ -6552,6 +6725,7 @@ function highlightTextParts(parts) {
6552
  }
6553
  } finally {
6554
  fullSearchDomLocator?.resume();
 
6555
  }
6556
  return marks;
6557
  }
@@ -6637,10 +6811,13 @@ function fullSearchLocation(node, fallback, offset, total, headingLookup = null,
6637
  async function fullSearchDomMatches(root, fallback, query, generation, progressive = false,
6638
  occurrence = null, navigationGeneration = readerRuntime.currentGeneration("navigation")) {
6639
  root = foliateSectionRoot(root);
 
 
 
6640
  const locator = progressive ? createFullSearchDomLocator(root, generation) : null;
6641
- const nodes = await fullSearchTextNodes(root, generation);
6642
  if (!nodes || !isReaderGenerationCurrent("search", generation)) return [];
6643
- const offsets = [],
6644
  chunks = [];
6645
  let length = 0;
6646
  for (const [index, node] of nodes.entries()) {
@@ -6652,24 +6829,28 @@ async function fullSearchDomMatches(root, fallback, query, generation, progressi
6652
  if (!isReaderGenerationCurrent("search", generation)) return [];
6653
  }
6654
  }
6655
- locator?.build(offsets);
6656
- const headingLookup = createFullSearchHeadingLookup(root, offsets);
6657
- const text = chunks.join(""), groups = [], firstHits = [];
 
 
 
 
6658
  const patternText = fullSearchEscape(query);
6659
  let nextStart = 0, total = 0;
6660
- const locateIndex = (index) => {
6661
- let low = 0, high = offsets.length - 1;
6662
  while (low < high) {
6663
  const middle = (low + high) >> 1;
6664
- if (offsets[middle].end <= index) low = middle + 1;
6665
  else high = middle;
6666
  }
6667
  return low;
6668
  };
6669
  const partsFor = (start, end) => {
6670
  const parts = [];
6671
- for (let index = locateIndex(start); index < offsets.length && offsets[index].start < end; index++)
6672
- parts.push(offsets[index]);
6673
  return parts;
6674
  };
6675
  const matchesIn = function* (group) {
@@ -6683,7 +6864,7 @@ async function fullSearchDomMatches(root, fallback, query, generation, progressi
6683
  const resultFor = (match) => {
6684
  const part = offsets[locateIndex(match.index)];
6685
  return {
6686
- location: fullSearchLocation(part.node, fallback, match.index, text.length, headingLookup, part.parent),
6687
  snippet: fullSearchSnippet(text, match.index, match.value.length),
6688
  async activate(navigationGeneration = readerRuntime.currentGeneration("navigation")) {
6689
  if (!isReaderGenerationCurrent("navigation", navigationGeneration)) return false;
@@ -6760,6 +6941,22 @@ async function fullSearchDomMatches(root, fallback, query, generation, progressi
6760
  return [{ target: fullSearchActiveMarks[0] }];
6761
  }
6762
  const fallbackResults = progressive ? null : firstHits.map(resultFor);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6763
  if (navigationGeneration === readerRuntime.currentGeneration("navigation")) {
6764
  for (let i = firstHits.length - 1; i >= 0; i--) {
6765
  const match = firstHits[i], end = match.index + match.value.length;
 
561
  foliateScrollFrame = 0,
562
  foliateWindowFrame = 0;
563
  let initialReaderTargetSection = null;
564
+ let chapterManifestCleanup = null;
565
  const FOLIATE_PREFETCH_SECTIONS = 6;
566
  const FOLIATE_PREFETCH_MARGIN = 4000;
567
  const FOLIATE_LOADED_SECTION_LIMIT = 12;
 
2633
  throw Object.assign(new Error(`HTTP ${response.status}`), { status: response.status });
2634
  }).catch((error) => {
2635
  assertReaderActive();
2636
+ requestInit.signal?.throwIfAborted();
2637
  if (retryableReaderProxyError(error)) throw error;
2638
  return fetchWithReaderTimeout(rawUrl, READER_PROXY_TIMEOUT_MS, requestInit);
2639
  });
 
4563
  const frame = document.createElement("div");
4564
  frame.className = "epub-frame";
4565
  content.appendChild(frame);
4566
+ const loaded = new Set(), retainedBytes = new Map(),
 
4567
  manifestBase = trustedReaderAssetManifestUrl(chapterManifestUrl || sourceUrl);
4568
  const chapterByIndex = new Map(manifest.chapters.map((chapter) => [chapter.index, chapter]));
4569
  const chapterPrefetchCount = 6;
4570
+ let chapterFocusIndex = 1, chapterWindowFrame = 0, chapterWindowReady = false;
4571
+ let chapterNavigating = 0;
4572
  let chapterPreviousObserver = null;
4573
  const chapterBudget = VoiceOfMLReaderSecurity.createByteBudget();
4574
  if (!manifestBase) throw new Error("EPUB_INVALID_MANIFEST_PATH");
 
4612
  );
4613
  if (existing) return existing;
4614
  const next = nextChapterNode(Number(article.dataset.chapter), ".reader-epub-chapter");
4615
+ const marker = frame.querySelector(`.reader-chapter-sentinel[data-chapter="${article.dataset.chapter}"]`);
4616
+ foliateScrollAnchors.preserve(() => {
4617
+ if (marker) {
4618
+ chapterManifestObserver.unobserve(marker);
4619
+ chapterPreviousObserver.unobserve(marker);
4620
+ marker.replaceWith(article);
4621
+ } else frame.insertBefore(article, next || null);
4622
+ });
4623
+ chapterManifestObserver.observe(article);
4624
  foliateScrollAnchors.observe(article);
4625
  return article;
4626
  };
 
4663
  activate: (generation) => activateChapter(manifest.chapters[item.chapter - 1], generation, item.fragment)
4664
  }))
4665
  );
4666
+ const chapterScheduler = VoiceOfMLReaderChapters.createChapterScheduler({
4667
+ create: async (index, signal, priority) => {
4668
+ const chapter = chapterAt(index);
4669
+ assertReaderActive();
 
4670
  const url = chapterUrl(chapter);
4671
  if (!url) throw new Error("EPUB_INVALID_PATH");
4672
+ const result = await fetchReaderUrl(url, { signal, priority });
4673
  if (!result.ok) throw new Error(`HTTP ${result.status}`);
4674
  const bytes = await VoiceOfMLReaderSecurity.readBytes(
4675
  result,
 
4679
  let inserted = false;
4680
  try {
4681
  assertReaderActive();
4682
+ signal.throwIfAborted();
4683
  const doc = parseChapterDocument(new TextDecoder().decode(bytes));
4684
  for (const element of doc.querySelectorAll("*")) {
4685
  for (const name of ["src", "href", "poster", "xlink:href"])
 
4700
  article.innerHTML = doc.body ? doc.body.innerHTML : "";
4701
  // The generated text index includes head text (e.g. the chapter title).
4702
  article._chapterSearchHead = doc.head ? document.importNode(doc.head, true) : null;
 
 
 
 
 
 
 
 
4703
  insertChapter(article);
4704
  loaded.add(chapter.index);
4705
+ retainedBytes.set(chapter.index, bytes.byteLength);
4706
  inserted = true;
4707
  for (const entry of navigationState.tocEntries)
4708
  if (entry.chapterIndex === chapter.index)
 
4711
  if (next) ensureSentinel(next);
4712
  const previous = chapterAt(chapter.index - 1);
4713
  if (previous) ensureSentinel(previous, true);
4714
+ scheduleChapterWindow();
4715
  } catch (error) {
4716
  if (!inserted) chapterBudget.release(bytes.byteLength);
4717
  throw error;
4718
  }
4719
+ }
4720
+ });
4721
+ const fetchChapter = (chapter, demand = true) => {
4722
+ assertReaderActive();
4723
+ if (loaded.has(chapter.index)) return Promise.resolve();
4724
+ return chapterScheduler.load(chapter.index, demand).then(() => {
4725
+ foliateScrollAnchors.whenIdle(trimChapterWindow);
4726
+ }).catch(error => {
4727
+ if (error.name !== "AbortError" && !readerAbortController.signal.aborted) {
4728
+ const marker = ensureSentinel(chapter);
4729
+ marker?.classList.add("reader-chapter-load-error");
4730
+ marker?.removeAttribute("aria-hidden");
4731
+ }
4732
+ throw error;
4733
  });
 
 
4734
  };
4735
  const activateChapter = async (chapter, generation, fragment = "") => {
4736
+ chapterFocusIndex = chapter.index;
4737
+ chapterNavigating++;
4738
+ try { await fetchChapter(chapter); }
4739
+ finally { chapterNavigating--; }
4740
  if (!isReaderGenerationCurrent("navigation", generation)) return false;
4741
  const node = frame.querySelector(`.reader-epub-chapter[data-chapter="${chapter.index}"]`);
4742
  let id = fragment.replace(/^#/, "");
 
4793
  reportNavigationError(error, generation);
4794
  }
4795
  });
4796
+ const chapterVirtualizer = VoiceOfMLReaderVirtual.createSectionVirtualizer({
4797
+ limit: 12,
4798
+ getLoaded: () => [...frame.querySelectorAll(":scope > .reader-epub-chapter")],
4799
+ getIndex: article => Number(article.dataset.chapter),
4800
+ getHeight: article => article.getBoundingClientRect().height,
4801
+ canVirtualize: article => {
4802
+ const rect = article.getBoundingClientRect(), view = viewport.getBoundingClientRect();
4803
+ const selection = window.getSelection();
4804
+ return (rect.bottom < view.top - 800 || rect.top > view.bottom + 800) &&
4805
+ !article.contains(document.activeElement) &&
4806
+ !article.querySelector("mark.full-search-highlight") &&
4807
+ !(selection && !selection.isCollapsed &&
4808
+ selection.containsNode(article, true));
4809
+ },
4810
+ virtualize: (article, index, height) => {
4811
+ loaded.delete(index);
4812
+ const marker = ensureSentinel(chapterAt(index));
4813
+ const style = getComputedStyle(article);
4814
+ marker.classList.add("reader-chapter-placeholder");
4815
+ marker.style.height = `${height}px`;
4816
+ marker.style.marginTop = style.marginTop;
4817
+ marker.style.marginBottom = style.marginBottom;
4818
+ marker.setAttribute("aria-hidden", "true");
4819
+ chapterManifestObserver.unobserve(article);
4820
+ foliateScrollAnchors.unobserve(article);
4821
+ for (const entry of navigationState.tocEntries)
4822
+ if (entry.chapterIndex === index) entry.target = null;
4823
+ for (const image of article.querySelectorAll("img")) image.removeAttribute("src");
4824
+ article.replaceWith(marker);
4825
+ article._chapterSearchHead = null;
4826
+ },
4827
+ release: index => {
4828
+ chapterBudget.release(retainedBytes.get(index));
4829
+ retainedBytes.delete(index);
4830
+ },
4831
+ preserve: change => foliateScrollAnchors.preserve(change)
4832
+ });
4833
+ function trimChapterWindow() {
4834
+ if (chapterWindowReady) chapterVirtualizer.trim(chapterFocusIndex);
4835
+ }
4836
+ function refreshChapterWindow() {
4837
+ chapterWindowFrame = 0;
4838
+ if (!chapterWindowReady || readerAbortController.signal.aborted) return;
4839
+ const view = viewport.getBoundingClientRect();
4840
+ const rows = [...frame.querySelectorAll(":scope > [data-chapter]")];
4841
+ const current = rows.find(row => {
4842
+ const rect = row.getBoundingClientRect();
4843
+ return rect.top <= view.top + 80 && rect.bottom > view.top + 80;
4844
+ }) || rows.find(row => row.getBoundingClientRect().top > view.top);
4845
+ if (current && !chapterNavigating) chapterFocusIndex = Number(current.dataset.chapter);
4846
+ if (!chapterNavigating && current?.classList.contains("reader-chapter-sentinel") &&
4847
+ current.getBoundingClientRect().top < view.bottom)
4848
+ fetchChapter(chapterAt(chapterFocusIndex)).catch(() => {});
4849
+ const indices = document.hidden ? [] : manifest.chapters
4850
+ .slice(Math.max(0, chapterFocusIndex - 2), chapterFocusIndex + chapterPrefetchCount)
4851
+ .filter(chapter => !loaded.has(chapter.index)).map(chapter => chapter.index);
4852
+ chapterScheduler.prefetch(indices);
4853
+ foliateScrollAnchors.whenIdle(trimChapterWindow);
4854
+ }
4855
+ function scheduleChapterWindow() {
4856
+ if (!chapterWindowFrame) chapterWindowFrame = requestAnimationFrame(refreshChapterWindow);
4857
+ }
4858
+ function handleChapterVisibility() {
4859
+ if (document.hidden) chapterScheduler.prefetch([]);
4860
+ else scheduleChapterWindow();
4861
+ }
4862
  chapterManifestObserver = new IntersectionObserver(
4863
+ scheduleChapterWindow,
4864
+ { root: viewport, rootMargin: "800px 0px" }
 
 
 
 
 
 
 
4865
  );
4866
  chapterPreviousObserver = new IntersectionObserver((entries) => {
4867
  if (readerAbortController.signal.aborted) return;
 
4871
  if (chapter) fetchChapter(chapter).catch(() => {});
4872
  }
4873
  }, { root: viewport });
4874
+ viewport.addEventListener("scroll", scheduleChapterWindow, { passive: true });
4875
+ window.addEventListener("resize", scheduleChapterWindow);
4876
+ document.addEventListener("visibilitychange", handleChapterVisibility);
4877
+ let chapterCleaned = false;
4878
+ chapterManifestCleanup = () => {
4879
+ if (chapterCleaned) return;
4880
+ chapterCleaned = true;
4881
+ chapterWindowReady = false;
4882
+ cancelAnimationFrame(chapterWindowFrame);
4883
+ viewport.removeEventListener("scroll", scheduleChapterWindow);
4884
+ window.removeEventListener("resize", scheduleChapterWindow);
4885
+ document.removeEventListener("visibilitychange", handleChapterVisibility);
4886
+ chapterScheduler.dispose();
4887
+ chapterVirtualizer.dispose();
4888
  chapterManifestObserver?.disconnect();
4889
  chapterPreviousObserver?.disconnect();
4890
  chapterManifestObserver = null;
4891
  chapterManifestLoader = null;
4892
+ for (const bytes of retainedBytes.values()) chapterBudget.release(bytes);
4893
+ retainedBytes.clear();
4894
+ loaded.clear();
4895
+ };
4896
+ trackReaderResource(chapterManifestCleanup);
4897
  chapterManifestLoader = async (index) => {
4898
  const chapter = chapterAt(index);
4899
  if (!chapter) return null;
4900
+ chapterFocusIndex = index;
4901
+ chapterNavigating++;
4902
+ try { await fetchChapter(chapter); }
4903
+ finally { chapterNavigating--; }
4904
  return frame.querySelector(`.reader-epub-chapter[data-chapter="${index}"]`);
4905
  };
4906
  setChapterToc();
 
4909
  const initialChapter = Number.isInteger(savedChapter)
4910
  ? Math.max(0, Math.min(manifest.chapters.length - 1, savedChapter))
4911
  : 0;
4912
+ chapterFocusIndex = manifest.chapters[initialChapter].index;
4913
  if (initialChapter > 0) ensureSentinel(manifest.chapters[initialChapter - 1], true);
4914
  try {
4915
  await fetchChapter(manifest.chapters[initialChapter]);
 
4919
  code: "READER_RESTORE"
4920
  });
4921
  }
4922
+ chapterWindowReady = true;
4923
+ scheduleChapterWindow();
4924
  assertReaderActive();
4925
  markReaderContentReady();
4926
  status.textContent = `EPUB · ${manifest.chapters.length} 章`;
 
4942
  const body = document.createElement("div");
4943
  body.className = "docx-body";
4944
  content.append(styles, body);
4945
+ const options = {
4946
  className: "reader-docx",
4947
  inWrapper: true,
4948
  breakPages: true,
4949
  ignoreLastRenderedPageBreak: false,
4950
+ useBase64URL: false,
4951
  renderHeaders: true,
4952
  renderFooters: true,
4953
  renderFootnotes: true,
 
4956
  renderComments: false,
4957
  renderAltChunks: false,
4958
  debug: false
4959
+ };
4960
+ const docxDocument = await docx.parseAsync(bytes, options);
4961
+ assertReaderActive();
4962
+ const urls = new Set(), urlsByPath = new Map(), blobToURL = docxDocument.blobToURL.bind(docxDocument);
4963
+ let released = false;
4964
+ const release = () => {
4965
+ released = true;
4966
+ for (const url of urls) URL.revokeObjectURL(url);
4967
+ urls.clear();
4968
+ urlsByPath.clear();
4969
+ };
4970
+ const untrack = trackReaderResource(release);
4971
+ // Own this parsed document's images, fonts and numbering assets only.
4972
+ docxDocument.blobToURL = (blob, path) => {
4973
+ if (released) return null;
4974
+ if (path && urlsByPath.has(path)) return urlsByPath.get(path);
4975
+ const url = blobToURL(blob, path);
4976
+ if (typeof url === "string" && url.startsWith("blob:")) {
4977
+ urls.add(url);
4978
+ if (path) urlsByPath.set(path, url);
4979
+ }
4980
+ return url;
4981
+ };
4982
+ try {
4983
+ const nodes = await docx.renderDocument(docxDocument, options);
4984
+ assertReaderActive();
4985
+ for (const node of nodes) (node.nodeName === "STYLE" ? styles : body).appendChild(node);
4986
+ } catch (error) {
4987
+ release();
4988
+ untrack();
4989
+ throw error;
4990
+ }
4991
  assertReaderActive();
4992
  body.classList.toggle("reader-document-dark", readerTheme === "dark");
4993
+ if (!(body.textContent || "").trim() && !body.querySelector("img, table, svg, canvas")) {
4994
+ release();
4995
+ untrack();
4996
  throw new Error("DOCX rendered no supported content");
4997
+ }
4998
  const pages = [...body.querySelectorAll(":scope > .reader-docx-wrapper > section.reader-docx")];
4999
  if (pages.length) {
5000
  updateDocumentState({ pageCount: pages.length });
 
5025
  status.textContent = "图片";
5026
  }
5027
  function disposeFormatResources(mode) {
5028
+ if (mode === "epub-chapters") {
5029
+ chapterManifestCleanup?.();
5030
+ chapterManifestCleanup = null;
5031
+ }
5032
  if (mode === "swf") {
5033
  swfPlayer?.remove();
5034
  swfPlayer = null;
 
5552
  pdfFetchPolicy = createPdfFetchPolicy();
5553
  trackReaderResource(() => { pdfFetchPolicy?.dispose(); pdfFetchPolicy = null; });
5554
  }
5555
+ pdfFetchPolicy.add([target, readerContentUrl(target)]);
5556
  pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;
5557
  const options = (url) => ({
5558
  url,
 
6565
  }
6566
  let fullSearchActiveMarks = [];
6567
  let fullSearchDomLocator = null;
6568
+ let fullSearchDomSnapshot = null;
6569
+ const DOM_SEARCH_SNAPSHOT_BYTES = 8 * 1024 * 1024;
6570
+ function createDomSearchSnapshot(root) {
6571
+ fullSearchDomSnapshot?.dispose();
6572
+ let valid = true, disposed = false, value = null;
6573
+ const invalidate = () => { valid = false; value = null; };
6574
+ const observer = new MutationObserver(invalidate);
6575
+ const current = () => {
6576
+ if (observer.takeRecords().length) invalidate();
6577
+ return valid && !disposed;
6578
+ };
6579
+ const resume = () => {
6580
+ if (!disposed) observer.observe(root, {
6581
+ subtree: true, childList: true, characterData: true,
6582
+ attributes: true, attributeFilter: ["class", "data-page"]
6583
+ });
6584
+ };
6585
+ const snapshot = {
6586
+ root, current, resume,
6587
+ get value() { return current() ? value : null; },
6588
+ set(data) {
6589
+ if (!current()) return;
6590
+ if (data.offsets.length > 32768 || data.text.length * 2 + data.offsets.length * 64 > DOM_SEARCH_SNAPSHOT_BYTES) {
6591
+ snapshot.dispose();
6592
+ return;
6593
+ }
6594
+ // Owned highlights replace text nodes but leave these parent boundaries intact.
6595
+ value = { ...data, offsets: data.offsets.map(({ parent, start, end }) => ({ parent, start, end })) };
6596
+ },
6597
+ pause() { current(); observer.disconnect(); },
6598
+ dispose() { disposed = true; invalidate(); observer.disconnect(); }
6599
+ };
6600
+ resume();
6601
+ fullSearchDomSnapshot = snapshot;
6602
+ return snapshot;
6603
+ }
6604
  readerRuntime.events.on("generation", ({ name }) => {
6605
  if (name === "search") {
6606
  fullSearchDomLocator?.dispose();
 
6610
  trackReaderResource(() => {
6611
  fullSearchDomLocator?.dispose();
6612
  fullSearchDomLocator = null;
6613
+ fullSearchDomSnapshot?.dispose();
6614
+ fullSearchDomSnapshot = null;
6615
  });
6616
  function createFullSearchDomLocator(root, generation) {
6617
  fullSearchDomLocator?.dispose();
 
6630
  };
6631
  const locator = {
6632
  current,
6633
+ boundaries() { return current() ? checkpoints.slice() : []; },
6634
+ seed(boundaries) { if (current()) checkpoints.push(...boundaries); },
6635
  build(offsets) {
6636
  if (!current()) return;
6637
  const stride = Math.max(128, Math.ceil(offsets.length / 2048));
 
6669
  }
6670
  function clearFullSearchMarks() {
6671
  fullSearchDomLocator?.pause();
6672
+ fullSearchDomSnapshot?.pause();
6673
  try {
6674
  content.querySelectorAll(".reader-text-hit-box").forEach(node => node.remove());
6675
  const changedParents = new Set();
 
6685
  content.querySelectorAll(".reader-chapter-search-heading").forEach(node => node.remove());
6686
  } finally {
6687
  fullSearchDomLocator?.resume();
6688
+ fullSearchDomSnapshot?.resume();
6689
  }
6690
  }
6691
  async function fullSearchTextNodes(root, generation, endOffset = Infinity, checkpoint = null) {
 
6710
  }
6711
  function highlightTextParts(parts) {
6712
  fullSearchDomLocator?.pause();
6713
+ fullSearchDomSnapshot?.pause();
6714
  const marks = [];
6715
  try {
6716
  for (const { node, start, end } of [...parts].reverse()) {
 
6725
  }
6726
  } finally {
6727
  fullSearchDomLocator?.resume();
6728
+ fullSearchDomSnapshot?.resume();
6729
  }
6730
  return marks;
6731
  }
 
6811
  async function fullSearchDomMatches(root, fallback, query, generation, progressive = false,
6812
  occurrence = null, navigationGeneration = readerRuntime.currentGeneration("navigation")) {
6813
  root = foliateSectionRoot(root);
6814
+ const cached = progressive && fullSearchDomSnapshot?.root === root &&
6815
+ fullSearchDomSnapshot.value?.toc === navigationState.tocEntries ? fullSearchDomSnapshot.value : null;
6816
+ const snapshot = progressive ? (cached ? fullSearchDomSnapshot : createDomSearchSnapshot(root)) : null;
6817
  const locator = progressive ? createFullSearchDomLocator(root, generation) : null;
6818
+ const nodes = cached ? [] : await fullSearchTextNodes(root, generation);
6819
  if (!nodes || !isReaderGenerationCurrent("search", generation)) return [];
6820
+ const offsets = cached ? cached.offsets : [],
6821
  chunks = [];
6822
  let length = 0;
6823
  for (const [index, node] of nodes.entries()) {
 
6829
  if (!isReaderGenerationCurrent("search", generation)) return [];
6830
  }
6831
  }
6832
+ if (cached) locator?.seed(cached.checkpoints);
6833
+ else locator?.build(offsets);
6834
+ const headingLookup = cached ? cached.headingLookup : createFullSearchHeadingLookup(root, offsets);
6835
+ const text = cached ? cached.text : chunks.join(""), groups = [], firstHits = [];
6836
+ if (!cached && snapshot && (headingLookup || !navigationState.tocEntries.some(entry => entry.target)))
6837
+ snapshot.set({ text, offsets, headingLookup, checkpoints: locator.boundaries(), toc: navigationState.tocEntries });
6838
+ let highlightOffsets = offsets;
6839
  const patternText = fullSearchEscape(query);
6840
  let nextStart = 0, total = 0;
6841
+ const locateIndex = (index, parts = offsets) => {
6842
+ let low = 0, high = parts.length - 1;
6843
  while (low < high) {
6844
  const middle = (low + high) >> 1;
6845
+ if (parts[middle].end <= index) low = middle + 1;
6846
  else high = middle;
6847
  }
6848
  return low;
6849
  };
6850
  const partsFor = (start, end) => {
6851
  const parts = [];
6852
+ for (let index = locateIndex(start, highlightOffsets); index < highlightOffsets.length && highlightOffsets[index].start < end; index++)
6853
+ parts.push(highlightOffsets[index]);
6854
  return parts;
6855
  };
6856
  const matchesIn = function* (group) {
 
6864
  const resultFor = (match) => {
6865
  const part = offsets[locateIndex(match.index)];
6866
  return {
6867
+ location: fullSearchLocation(part.node || part.parent, fallback, match.index, text.length, headingLookup, part.parent),
6868
  snippet: fullSearchSnippet(text, match.index, match.value.length),
6869
  async activate(navigationGeneration = readerRuntime.currentGeneration("navigation")) {
6870
  if (!isReaderGenerationCurrent("navigation", navigationGeneration)) return false;
 
6941
  return [{ target: fullSearchActiveMarks[0] }];
6942
  }
6943
  const fallbackResults = progressive ? null : firstHits.map(resultFor);
6944
+ if (cached && !snapshot.current())
6945
+ return fullSearchDomMatches(root, fallback, query, generation, progressive, occurrence, navigationGeneration);
6946
+ if (cached && firstHits.length && navigationGeneration === readerRuntime.currentGeneration("navigation")) {
6947
+ const checkpoint = locator.checkpoint(firstHits[0].index);
6948
+ const end = firstHits[firstHits.length - 1].index + firstHits[firstHits.length - 1].value.length;
6949
+ const markNodes = await fullSearchTextNodes(root, generation, end, checkpoint);
6950
+ if (!markNodes || !isReaderGenerationCurrent("search", generation)) return [];
6951
+ if (!snapshot.current())
6952
+ return fullSearchDomMatches(root, fallback, query, generation, progressive, occurrence, navigationGeneration);
6953
+ let position = checkpoint?.start || 0;
6954
+ highlightOffsets = markNodes.map(node => {
6955
+ const part = { node, start: position, end: position + node.data.length };
6956
+ position = part.end;
6957
+ return part;
6958
+ });
6959
+ }
6960
  if (navigationGeneration === readerRuntime.currentGeneration("navigation")) {
6961
  for (let i = firstHits.length - 1; i >= 0; i--) {
6962
  const match = firstHits[i], end = match.index + match.value.length;
tests/test_reader_chapter_scheduler.js ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const assert = require("assert");
2
+ const fs = require("fs");
3
+ const path = require("path");
4
+ const vm = require("vm");
5
+
6
+ async function main() {
7
+ const sandbox = { DOMException, AbortController };
8
+ sandbox.self = sandbox;
9
+ vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static/reader-chapter-repository.js"), "utf8"), sandbox);
10
+ const starts = [], held = new Map();
11
+ const scheduler = sandbox.VoiceOfMLReaderChapters.createChapterScheduler({
12
+ create(index, signal, priority) {
13
+ starts.push({ index, signal, priority });
14
+ return new Promise(resolve => held.set(index, resolve));
15
+ }
16
+ });
17
+ const tick = () => new Promise(resolve => setImmediate(resolve));
18
+ scheduler.prefetch([1, 2, 3, 4, 5, 6]);
19
+ await tick();
20
+ assert.deepStrictEqual(starts.map(item => item.index), [1, 2]);
21
+ const foreground = scheduler.load(20);
22
+ await tick();
23
+ assert.deepStrictEqual(starts.map(item => item.index), [1, 2, 20]);
24
+ assert.strictEqual(starts[2].priority, "high");
25
+ assert.ok(starts[0].signal.aborted && starts[1].signal.aborted);
26
+ assert.strictEqual(scheduler.activeCount, 3, "cancelled creates retain ownership until settlement");
27
+ held.get(20)("target");
28
+ assert.strictEqual(await foreground, "target");
29
+ held.get(1)("late"); held.get(2)("late");
30
+ await tick();
31
+ assert.strictEqual(scheduler.activeCount, 0);
32
+ assert.strictEqual(scheduler.pendingCount, 0);
33
+ scheduler.prefetch([30, 31, 32]);
34
+ const promoted = scheduler.load(32);
35
+ assert.strictEqual(scheduler.load(32), promoted);
36
+ await tick();
37
+ assert.strictEqual(starts[3].index, 32, "queued demand overtakes speculation");
38
+ held.get(32)("promoted");
39
+ assert.strictEqual(await promoted, "promoted");
40
+ await tick();
41
+ scheduler.prefetch([40, 41, 42]);
42
+ await tick();
43
+ scheduler.prefetch([41, 43]);
44
+ assert.ok(starts.find(item => item.index === 40).signal.aborted);
45
+ const closing = scheduler.load(50);
46
+ const rejected = assert.rejects(closing, error => error.name === "AbortError");
47
+ scheduler.dispose();
48
+ await rejected;
49
+ for (const resolve of held.values()) resolve("closed");
50
+ await tick();
51
+ assert.strictEqual(scheduler.activeCount, 0);
52
+ assert.strictEqual(scheduler.pendingCount, 0);
53
+ await assert.rejects(scheduler.load(1), error => error.name === "AbortError");
54
+ console.log("reader chapter scheduler contracts passed");
55
+ }
56
+
57
+ main().catch(error => { console.error(error); process.exitCode = 1; });
tests/test_reader_optimizations.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Focused offline acceptance for Reader scheduling, retention and text reuse."""
2
+
3
+ import gzip
4
+ import hashlib
5
+ import io
6
+ import json
7
+ import unittest
8
+ import urllib.parse
9
+ import zipfile
10
+
11
+ from tests import test_reader_refactor as fixtures
12
+
13
+
14
+ @unittest.skipIf(fixtures.support.sync_playwright is None, "Playwright is unavailable")
15
+ class ReaderOptimizationTests(unittest.TestCase):
16
+ setUpClass = classmethod(fixtures.ReaderRefactorTest.setUpClass.__func__)
17
+ tearDownClass = classmethod(fixtures.ReaderRefactorTest.tearDownClass.__func__)
18
+ setUp = fixtures.ReaderRefactorTest.setUp
19
+ tearDown = fixtures.ReaderRefactorTest.tearDown
20
+ reader_url = fixtures.ReaderRefactorTest.reader_url
21
+ serve = fixtures.ReaderRefactorTest.serve
22
+ open = fixtures.ReaderRefactorTest.open
23
+ search = fixtures.ReaderRefactorTest.search
24
+
25
+ def expose(self):
26
+ def instrument(route):
27
+ response = route.fetch()
28
+ script = response.text().replace('chapterManifestCleanup = () => {', '''
29
+ window.__chapterStats = () => ({active: chapterScheduler.activeCount,
30
+ pending: chapterScheduler.pendingCount, bytes: chapterBudget.used});
31
+ chapterManifestCleanup = () => {''')
32
+ route.fulfill(response=response, body=script + '''
33
+ window.__snapshot = () => fullSearchDomSnapshot;
34
+ window.__query = async query => {
35
+ fullSearchInput.value = query;
36
+ await runFullSearch();
37
+ return chapterSearchPage?.total || 0;
38
+ };
39
+ window.__goChapter = index => navigationState.tocEntries[index-1].activate(beginReaderNavigation());
40
+ window.__walkProbe = () => {
41
+ const doc = (htmlFrame?.contentDocument?.body || content).ownerDocument;
42
+ const native = doc.createTreeWalker.bind(doc);
43
+ window.__visits = 0;
44
+ doc.createTreeWalker = (...args) => {
45
+ const walker = native(...args), next = walker.nextNode.bind(walker);
46
+ walker.nextNode = () => { __visits++; return next(); };
47
+ return walker;
48
+ };
49
+ };
50
+ ''')
51
+ self.page.route('**/static/reader.js?*', instrument)
52
+
53
+ def chapter_book(self, hold=False):
54
+ self.expose()
55
+ base = 'https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/' + 'a' * 64 + '/'
56
+ chapters, texts, bodies = [], [], {}
57
+ for index in range(1, 61):
58
+ path = f'chapter-{index}.xhtml'
59
+ body = f'<h1 id="heading-{index}">Chapter {index}</h1><p style="height:1600px">needle unique-{index}</p>'
60
+ bodies[base + path] = body
61
+ chapters.append(dict(index=index, path=path, title=f'Chapter {index}', bytes=len(body)))
62
+ texts.append(dict(index=index, path=path, title=f'Chapter {index}', text=f'Chapter {index} needle unique-{index}'))
63
+ packed = gzip.compress(json.dumps(dict(version=1, kind='epub-search-index', chapters=texts)).encode(), mtime=0)
64
+ manifest = dict(version=1, kind='epub-chapters', chapters=chapters,
65
+ search_index=dict(path='epub-search-index.json.gz', bytes=len(packed), sha256=hashlib.sha256(packed).hexdigest()))
66
+ requested, held = [], []
67
+ def resource(route):
68
+ raw = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)['url'][0]
69
+ requested.append(raw)
70
+ if hold and raw in (base + 'chapter-2.xhtml', base + 'chapter-3.xhtml'):
71
+ held.append(route)
72
+ elif raw.endswith('chapter-manifest.json'):
73
+ route.fulfill(json=manifest, headers={'Access-Control-Allow-Origin': '*'})
74
+ elif raw.endswith('epub-search-index.json.gz'):
75
+ route.fulfill(body=packed, content_type='application/gzip', headers={'Access-Control-Allow-Origin': '*'})
76
+ else:
77
+ route.fulfill(body=bodies[raw], content_type='text/html', headers={'Access-Control-Allow-Origin': '*'})
78
+ self.context.route('**/api/reader-content**', resource)
79
+ self.open(self.reader_url('epub-chapters', url=base + 'chapter-manifest.json'))
80
+ return requested, held
81
+
82
+ def test_chapter_demand_overtakes_stalled_prefetch_and_close_cancels_queue(self):
83
+ requested, held = self.chapter_book(hold=True)
84
+ self.page.expose_function('__heldCount', lambda: len(held))
85
+ self.page.wait_for_function('async () => await __heldCount() === 2')
86
+ self.assertEqual(self.page.evaluate('__chapterStats().active'), 2)
87
+ self.assertEqual(len(held), 2)
88
+ self.assertTrue(self.page.evaluate('__goChapter(40)'))
89
+ self.assertTrue(any(url.endswith('chapter-40.xhtml') for url in requested))
90
+ self.assertEqual(self.page.locator('.reader-epub-chapter[data-chapter="2"]').count(), 0)
91
+ self.page.evaluate('window.dispatchEvent(new Event("voice-reader-dispose"))')
92
+ self.page.wait_for_function('() => __chapterStats().active === 0 && __chapterStats().pending === 0')
93
+ for route in held:
94
+ route.abort()
95
+ self.assertEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'disposed')
96
+ self.assertEqual(self.page.evaluate('__chapterStats().bytes'), 0)
97
+
98
+ def test_chapter_window_preserves_geometry_selection_and_complete_search(self):
99
+ requested, _held = self.chapter_book()
100
+ for width in (1100, 390):
101
+ with self.subTest(width=width):
102
+ self.page.set_viewport_size(dict(width=width, height=800))
103
+ for chapter in (1, 10, 20, 30, 40, 50, 60):
104
+ self.assertTrue(self.page.evaluate('__goChapter', chapter))
105
+ self.page.wait_for_function('() => document.querySelectorAll(".reader-epub-chapter").length <= 12 && __chapterStats().pending === 0')
106
+ self.assertGreater(self.page.locator('.reader-chapter-placeholder').count(), 0)
107
+ self.assertTrue(self.page.evaluate('__goChapter(1)'))
108
+ self.page.wait_for_function('() => __chapterStats().pending === 0')
109
+ self.page.evaluate('async () => {await __goChapter(3); await __goChapter(2); await __goChapter(1);}')
110
+ self.page.evaluate('''() => {
111
+ window.__pinned = document.querySelector('.reader-epub-chapter[data-chapter="1"]');
112
+ window.__pinnedMiddle = document.querySelector('.reader-epub-chapter[data-chapter="2"]');
113
+ const range = document.createRange();
114
+ range.setStart(__pinned.querySelector('p').firstChild, 0);
115
+ range.setEnd(document.querySelector('.reader-epub-chapter[data-chapter="3"] p').firstChild, 3);
116
+ getSelection().removeAllRanges(); getSelection().addRange(range);
117
+ }''')
118
+ self.assertTrue(self.page.evaluate('__goChapter(60)'))
119
+ self.page.wait_for_function('() => __chapterStats().pending === 0')
120
+ self.assertTrue(self.page.evaluate('__pinned.isConnected'))
121
+ self.assertTrue(self.page.evaluate('__pinnedMiddle.isConnected'))
122
+ self.page.evaluate('getSelection().removeAllRanges(); document.querySelector("#viewport").dispatchEvent(new Event("scroll"))')
123
+ self.assertTrue(self.page.evaluate('__goChapter(30)'))
124
+ self.page.wait_for_function('() => __chapterStats().pending === 0')
125
+ self.page.wait_for_function('() => !__pinned.isConnected')
126
+ marker = self.page.locator('.reader-chapter-placeholder[data-chapter="1"]')
127
+ self.assertGreater(marker.evaluate('node => node.getBoundingClientRect().height'), 1600)
128
+ before = self.page.locator('#viewport').evaluate('node => node.scrollHeight')
129
+ 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])')
130
+ if width == 1100:
131
+ self.page.route('**/*chapter-1.xhtml', lambda route: route.fulfill(status=503, body='temporary fixture failure'))
132
+ self.assertTrue(self.page.evaluate('async () => {try {await __goChapter(1); return false;} catch (_) {return true;}}'))
133
+ self.assertGreater(marker.evaluate('node => node.getBoundingClientRect().height'), 1600)
134
+ self.page.unroute('**/*chapter-1.xhtml')
135
+ self.assertTrue(self.page.evaluate('__goChapter(1)'))
136
+ self.page.wait_for_function('() => __chapterStats().pending === 0')
137
+ after = self.page.locator('#viewport').evaluate('node => node.scrollHeight')
138
+ 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])')
139
+ self.assertAlmostEqual(before, after, delta=3, msg=json.dumps(dict(before=before_rows, after=after_rows)))
140
+ self.assertEqual(self.page.evaluate('__query("needle")'), 60)
141
+ self.search('needle')
142
+ self.page.locator('.full-search-result').first.click()
143
+ self.page.wait_for_function('() => document.querySelector(".reader-epub-chapter[data-chapter=\\"1\\"] mark")')
144
+ self.assertEqual(self.page.locator('mark.full-search-highlight').text_content(), 'needle')
145
+ self.assertGreater(sum(url.endswith('chapter-1.xhtml') for url in requested), 1)
146
+
147
+ def docx_url(self):
148
+ return self.reader_url('docx', url='https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/' + 'a' * 64 + '/document.docx')
149
+
150
+ def image_docx(self, image=None, repeats=3, font=None):
151
+ support = fixtures.support
152
+ with zipfile.ZipFile(io.BytesIO(support.minimal_docx())) as archive:
153
+ files = {name: archive.read(name) for name in archive.namelist()}
154
+ files['[Content_Types].xml'] = files['[Content_Types].xml'].decode().replace('</Types>', '<Default Extension="png" ContentType="image/png"/></Types>')
155
+ 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>'
156
+ files['word/media/image.png'] = image if image is not None else support.PNG_BYTES
157
+ 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>'''
158
+ files['word/document.xml'] = files['word/document.xml'].decode().replace('<w:sectPr/>', drawing * repeats + '<w:sectPr/>')
159
+ if font is not None:
160
+ 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>')
161
+ 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>')
162
+ 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>'
163
+ 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>'
164
+ files['word/fonts/font.odttf'] = font
165
+ 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>')
166
+ return support.zip_bytes(files)
167
+
168
+ def test_real_docx_images_use_owned_blob_urls_and_release_on_close(self):
169
+ self.page.add_init_script('''window.__created = []; window.__revoked = [];
170
+ const create = URL.createObjectURL.bind(URL), revoke = URL.revokeObjectURL.bind(URL);
171
+ URL.createObjectURL = blob => { const url=create(blob); __created.push(url); return url; };
172
+ URL.revokeObjectURL = url => { __revoked.push(url); return revoke(url); };''')
173
+ font = (fixtures.support.ROOT / 'static/vendor/standard_fonts/LiberationSans-Regular.ttf').read_bytes()
174
+ self.serve(self.image_docx(font=font), 'application/octet-stream')
175
+ self.open(self.docx_url())
176
+ self.page.wait_for_function('() => document.querySelectorAll(".docx-body img").length === 3 && [...document.querySelectorAll(".docx-body img")].every(image => image.naturalWidth > 0)')
177
+ self.assertTrue(all(url.startswith('blob:') for url in self.page.locator('.docx-body img').evaluate_all('images => images.map(image => image.src)')))
178
+ self.assertEqual(self.page.evaluate('__revoked.length'), 0)
179
+ self.assertEqual(self.page.evaluate('async () => (await document.fonts.load("16px FixtureFont")).length'), 1)
180
+ self.assertTrue(self.page.evaluate('[...document.fonts].some(font => font.family === "FixtureFont" && font.status === "loaded")'))
181
+ self.assertEqual(self.page.evaluate('__created.length'), 2)
182
+ self.page.evaluate('window.dispatchEvent(new Event("voice-reader-dispose"))')
183
+ self.assertEqual(self.page.evaluate('__created.slice().sort()'), self.page.evaluate('__revoked.slice().sort()'))
184
+
185
+ def test_docx_failure_and_late_render_cannot_leak_blob_assets(self):
186
+ script = '''window.docx = {
187
+ parseAsync: async () => ({blobToURL: blob => URL.createObjectURL(blob)}),
188
+ renderDocument: async doc => {
189
+ window.__ownedUrl = doc.blobToURL(new Blob(['font']), 'font.ttf');
190
+ window.__lateBlob = () => doc.blobToURL(new Blob(['late']), 'image.png');
191
+ if (location.search.includes('hold=1')) await new Promise(resolve => {window.__releaseDocx = resolve;});
192
+ throw new Error('render fixture failure');
193
+ }
194
+ };'''
195
+ self.page.route('**/static/vendor/docx-preview.min.*.js', lambda route: route.fulfill(content_type='text/javascript', body=script))
196
+ self.page.add_init_script('''window.__revoked = []; const revoke=URL.revokeObjectURL.bind(URL);
197
+ URL.revokeObjectURL = url => {__revoked.push(url); revoke(url);};''')
198
+ self.serve(fixtures.support.minimal_docx(), 'application/octet-stream')
199
+ for hold in (False, True):
200
+ with self.subTest(hold=hold):
201
+ self.page.goto(self.docx_url() + ('&hold=1' if hold else ''))
202
+ self.page.wait_for_function('() => !!window.__ownedUrl')
203
+ if hold:
204
+ self.page.evaluate('window.dispatchEvent(new Event("voice-reader-dispose")); __releaseDocx()')
205
+ else:
206
+ self.page.wait_for_function('() => document.documentElement.dataset.readerPhase === "failed"')
207
+ self.assertEqual(self.page.evaluate('__revoked'), [self.page.evaluate('__ownedUrl')])
208
+ self.assertIsNone(self.page.evaluate('__lateBlob()'))
209
+
210
+ def test_dom_snapshot_reuses_text_after_highlights_and_invalidates_external_edits(self):
211
+ self.expose()
212
+ body = '<p><span>nee</span><b>dle</b> otherword</p>' + '<p>ordinary</p>' * 4000 + '<p>tail needle</p>'
213
+ for extension in ('html', 'md', 'txt', 'docx'):
214
+ with self.subTest(extension=extension):
215
+ if extension == 'docx':
216
+ 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];}};'))
217
+ self.serve(fixtures.support.minimal_docx(), 'application/octet-stream')
218
+ self.open(self.docx_url())
219
+ else:
220
+ self.serve('needle otherword\n' + 'ordinary\n' * 4000 + 'tail needle' if extension == 'txt' else body)
221
+ self.open(self.reader_url(extension))
222
+ self.assertEqual(self.page.evaluate('__query("needle")'), 2)
223
+ self.page.evaluate('window.__originalSnapshot = __snapshot(); __walkProbe()')
224
+ self.assertEqual(self.page.evaluate('__query("otherword")'), 1)
225
+ self.assertTrue(self.page.evaluate('__snapshot() === __originalSnapshot'))
226
+ self.assertLess(self.page.evaluate('__visits'), 10)
227
+ self.assertEqual(self.page.evaluate('__query("needle")'), 2)
228
+ self.assertEqual(self.page.evaluate('''() => {
229
+ const root = document.querySelector('.html-frame')?.contentDocument.body || document.querySelector('#content');
230
+ setTimeout(() => root.prepend(root.ownerDocument.createTextNode('prefix needle ')), 0);
231
+ return __query('needle');
232
+ }'''), 3)
233
+ self.page.evaluate('''() => {
234
+ const root = document.querySelector('.html-frame')?.contentDocument.body || document.querySelector('#content');
235
+ root.append(root.ownerDocument.createTextNode(' added needle'));
236
+ }''')
237
+ self.assertEqual(self.page.evaluate('__query("needle")'), 4)
238
+ self.assertFalse(self.page.evaluate('__snapshot() === __originalSnapshot'))
239
+ self.page.evaluate('window.dispatchEvent(new Event("voice-reader-dispose"))')
240
+ self.assertTrue(self.page.evaluate('__snapshot() === null'))
241
+
242
+ def test_oversized_dom_snapshot_is_uncached_without_losing_matches(self):
243
+ self.expose()
244
+ self.serve('a' * (4 * 1024 * 1024) + ' needle')
245
+ self.open(self.reader_url('txt'))
246
+ self.assertEqual(self.page.evaluate('__query("needle")'), 1)
247
+ self.assertIsNone(self.page.evaluate('__snapshot().value'))
248
+ self.assertEqual(self.page.evaluate('__query("needle")'), 1)
249
+
250
+
251
+ if __name__ == '__main__':
252
+ unittest.main()
tests/test_reader_pdf_hybrid.py CHANGED
@@ -113,6 +113,36 @@ class HybridPdfTests(unittest.TestCase):
113
  self.page.locator("#page-number").fill(str(number))
114
  self.page.locator("#page-number").press("Enter")
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  def test_first_stream_fast_pdf_later_pages_skip_images_and_zoom_keeps_canvas(self):
117
  shell = self.open()
118
  shell.evaluate("s => {window.__firstShell=s; window.__beforeTop=s.getBoundingClientRect().top;}")
 
113
  self.page.locator("#page-number").fill(str(number))
114
  self.page.locator("#page-number").press("Enter")
115
 
116
+ def test_dark_theme_keeps_preview_and_pdf_handoff_consistent(self):
117
+ shell = self.open()
118
+ self.page.set_viewport_size({"width": 390, "height": 844})
119
+ def assert_theme(surface, theme):
120
+ self.page.evaluate("theme => document.documentElement.dataset.theme = theme", theme)
121
+ self.assertEqual(surface.evaluate("e => getComputedStyle(e).filter"),
122
+ "invert(0.9) hue-rotate(180deg)" if theme == "dark" else "none")
123
+ bounds = shell.bounding_box()
124
+ pixels = Image.open(io.BytesIO(self.page.screenshot())).convert('RGB')
125
+ pixel = pixels.getpixel((round(bounds['x'] + bounds['width'] * .8), round(bounds['y'] + 30)))
126
+ return pixel
127
+ preview = shell.locator('img.ready')
128
+ dark = assert_theme(preview, 'dark')
129
+ light = assert_theme(preview, 'light')
130
+ self.assertLess(max(dark), 50)
131
+ self.assertGreater(min(light), 240)
132
+ assert_theme(preview, 'dark')
133
+ self.page.evaluate('window.__releaseDocument()')
134
+ canvas = shell.locator('canvas.ready')
135
+ canvas.wait_for()
136
+ self.assertEqual(shell.locator('img').count(), 0)
137
+ self.assertEqual(shell.locator('.reader-pdf-text').evaluate("e => getComputedStyle(e).filter"), 'none')
138
+ dark = assert_theme(canvas, 'dark')
139
+ light = assert_theme(canvas, 'light')
140
+ self.assertNotEqual(dark, light)
141
+ assert_theme(canvas, 'dark')
142
+ self.page.evaluate("document.querySelector('#content').dataset.mode = 'image-pages'")
143
+ self.assertEqual(canvas.evaluate("e => getComputedStyle(e).filter"), 'none')
144
+ self.assertEqual(self.errors, [])
145
+
146
  def test_first_stream_fast_pdf_later_pages_skip_images_and_zoom_keeps_canvas(self):
147
  shell = self.open()
148
  shell.evaluate("s => {window.__firstShell=s; window.__beforeTop=s.getBoundingClientRect().top;}")
tests/test_reader_performance.py CHANGED
@@ -137,9 +137,10 @@ window.ePub = () => ({ renderTo: (frame) => ({
137
  }) });
138
  """
139
  DOCX_SCRIPT = """
140
- window.docx = { renderAsync: (_bytes, body) => new Promise((resolve) => setTimeout(() => {
141
- body.textContent = 'DOCX readable'; resolve();
142
- }, 20)) };
 
143
  """
144
  PNG_BYTES = bytes.fromhex(
145
  "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
@@ -1314,7 +1315,7 @@ class ReaderPerformanceTest(unittest.TestCase):
1314
  page = context.new_page()
1315
  page.route("**/static/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1316
  page.route("**/static/vendor/jszip.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body="window.JSZip=function(){window.__archiveParserStarted=true};"))
1317
- 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}};"))
1318
  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'); } });"))
1319
  page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/octet-stream", body=payload))
1320
  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"
 
137
  }) });
138
  """
139
  DOCX_SCRIPT = """
140
+ window.docx = { parseAsync: async () => ({blobToURL: blob => URL.createObjectURL(blob)}),
141
+ renderDocument: () => new Promise(resolve => setTimeout(() => {
142
+ resolve([document.createTextNode('DOCX readable')]);
143
+ }, 20)) };
144
  """
145
  PNG_BYTES = bytes.fromhex(
146
  "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
 
1315
  page = context.new_page()
1316
  page.route("**/static/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
1317
  page.route("**/static/vendor/jszip.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body="window.JSZip=function(){window.__archiveParserStarted=true};"))
1318
+ 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}};"))
1319
  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'); } });"))
1320
  page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/octet-stream", body=payload))
1321
  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"
tests/test_reader_refactor.py CHANGED
@@ -2243,7 +2243,7 @@ class ReaderRefactorTest(unittest.TestCase):
2243
  with self.subTest(extension=extension):
2244
  if extension == 'docx':
2245
  self.page.route('**/static/vendor/docx-preview.min.*.js', lambda route: route.fulfill(
2246
- content_type='text/javascript', body="window.docx = {renderAsync: async (_bytes, body) => {body.innerHTML = " + json.dumps(html) + ";}}"))
2247
  self.serve(support.minimal_docx(), 'application/octet-stream')
2248
  else:
2249
  self.serve('before needle after\n' + 'ordinary\n' * 8000 + 'last needle' if extension == 'txt' else html,
 
2243
  with self.subTest(extension=extension):
2244
  if extension == 'docx':
2245
  self.page.route('**/static/vendor/docx-preview.min.*.js', lambda route: route.fulfill(
2246
+ 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];}}"))
2247
  self.serve(support.minimal_docx(), 'application/octet-stream')
2248
  else:
2249
  self.serve('before needle after\n' + 'ordinary\n' * 8000 + 'last needle' if extension == 'txt' else html,
tests/test_reader_style.py CHANGED
@@ -4,6 +4,7 @@ import io
4
  import unittest
5
  import urllib.parse
6
  import zipfile
 
7
 
8
  from tests.test_reader_performance import (
9
  STORE_SCRIPT,
@@ -14,6 +15,7 @@ from tests.test_reader_performance import (
14
  sync_playwright,
15
  zip_bytes,
16
  )
 
17
 
18
 
19
  @unittest.skipIf(sync_playwright is None, "install requirements-test.txt for reader style tests")
@@ -136,6 +138,84 @@ class ReaderStyleTests(unittest.TestCase):
136
  for selector in (".reader-error", ".epub-frame .reader-markdown", ".reader-markdown a"):
137
  self.assert_contrast(selector)
138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  def open_theme_fixture(self, extension, data):
140
  self.page.route("**/api/reader-content**", lambda route: route.fulfill(body=data))
141
  source = urllib.parse.quote(
 
4
  import unittest
5
  import urllib.parse
6
  import zipfile
7
+ from PIL import Image
8
 
9
  from tests.test_reader_performance import (
10
  STORE_SCRIPT,
 
15
  sync_playwright,
16
  zip_bytes,
17
  )
18
+ from tests import test_reader_performance as support
19
 
20
 
21
  @unittest.skipIf(sync_playwright is None, "install requirements-test.txt for reader style tests")
 
138
  for selector in (".reader-error", ".epub-frame .reader-markdown", ".reader-markdown a"):
139
  self.assert_contrast(selector)
140
 
141
+ def test_pdf_page_surface_follows_dark_theme_without_touching_text_layer(self):
142
+ self.page.route("**/api/reader-content**", lambda route: route.fulfill(
143
+ content_type="application/pdf", body=support.minimal_pdf()
144
+ ))
145
+ source = urllib.parse.quote(
146
+ "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/theme.pdf", safe=""
147
+ )
148
+ self.page.goto(
149
+ f"{self.origin}/static/reader.html?url={source}&ext=pdf&title=Theme PDF",
150
+ wait_until="domcontentloaded",
151
+ )
152
+ self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
153
+ canvas = self.page.locator('.reader-content[data-mode="pdf"] .reader-page canvas').first
154
+ self.page.locator('.reader-page canvas.ready').first.wait_for()
155
+ self.page.wait_for_function("() => document.querySelector('.reader-page')?.dataset.textReady === '1'")
156
+ self.page.locator('.reader-page').first.evaluate("node => window.__themePage = node")
157
+ text_layer = self.page.locator('.reader-pdf-text').first
158
+ self.assertEqual(text_layer.evaluate("e => getComputedStyle(e).filter"), "none")
159
+ self.assertEqual(canvas.evaluate("e => getComputedStyle(e).filter"), "invert(0.9) hue-rotate(180deg)")
160
+ self.page.locator("#history").click()
161
+ for theme in ('light', 'dark'):
162
+ self.page.locator("#theme-toggle").click()
163
+ self.settle()
164
+ self.assertEqual(canvas.evaluate("e => getComputedStyle(e).filter"), 'none' if theme == 'light' else 'invert(0.9) hue-rotate(180deg)')
165
+ self.page.locator("#history").click()
166
+ for width in (1100, 390):
167
+ self.page.set_viewport_size({"width": width, "height": 844})
168
+ self.page.locator('.reader-pdf-text-run').first.evaluate("node => {const range=document.createRange(); range.selectNodeContents(node); getSelection().removeAllRanges(); getSelection().addRange(range);}")
169
+ selected = self.page.evaluate("getSelection().toString()")
170
+ self.assertEqual(selected, 'Reader PDF')
171
+ original_pixels = canvas.evaluate("c => c.toDataURL()")
172
+ for theme in ("dark", "light", "dark"):
173
+ self.page.evaluate("theme => document.documentElement.dataset.theme = theme", theme)
174
+ self.settle()
175
+ bounds = self.page.locator('.reader-page').first.bounding_box()
176
+ png = Image.open(io.BytesIO(self.page.screenshot())).convert("RGB")
177
+ pixel = png.getpixel((round(bounds['x'] + bounds['width'] * .85), round(bounds['y'] + 30)))
178
+ self.assertTrue(max(pixel) < 50 if theme == "dark" else min(pixel) > 240, (theme, pixel))
179
+ self.assertEqual(canvas.evaluate("c => c.toDataURL()"), original_pixels)
180
+ self.assertTrue(self.page.evaluate("document.querySelector('.reader-page') === __themePage"))
181
+ self.assertEqual(self.page.evaluate("getSelection().toString()"), selected)
182
+ self.page.evaluate("getSelection().removeAllRanges()")
183
+ self.page.locator('#history').click()
184
+ self.page.locator('#full-search-toggle').click()
185
+ self.page.locator('#full-search-input').fill('Reader')
186
+ self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
187
+ mark = self.page.locator('.reader-page mark.full-search-highlight').first
188
+ self.assertEqual(mark.text_content(), 'Reader')
189
+ self.assertEqual(mark.evaluate("e => getComputedStyle(e).filter"), 'none')
190
+ self.assertNotEqual(mark.evaluate("e => getComputedStyle(e).backgroundColor"), 'rgba(0, 0, 0, 0)')
191
+ self.page.locator('#content').evaluate("node => node.dataset.mode = 'image-pages'")
192
+ self.assertEqual(self.page.locator('.reader-page canvas').first.evaluate("e => getComputedStyle(e).filter"), 'none')
193
+
194
+ def test_pdf_page_images_follow_theme_but_original_images_do_not(self):
195
+ output = io.BytesIO()
196
+ Image.new('RGB', (600, 800), 'white').save(output, 'WEBP')
197
+ self.page.route('**/api/reader-content**', lambda route: route.fulfill(
198
+ json={"version": 2, "kind": "pdf-pages", "page_count": 1}))
199
+ self.page.route('**/pages/page-*.webp', lambda route: route.fulfill(
200
+ content_type='image/webp', body=output.getvalue()))
201
+ source = urllib.parse.quote('https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/' + 'a' * 64 + '/page-manifest.json', safe='')
202
+ self.page.goto(f'{self.origin}/static/reader.html?url={source}&ext=pdf-pages')
203
+ image = self.page.locator('.reader-page img.ready').first
204
+ image.wait_for()
205
+ original = image.get_attribute('src')
206
+ for width in (1100, 390):
207
+ self.page.set_viewport_size({'width': width, 'height': 844})
208
+ for theme in ('dark', 'light', 'dark'):
209
+ self.page.evaluate('theme => document.documentElement.dataset.theme = theme', theme)
210
+ self.settle()
211
+ bounds = image.bounding_box()
212
+ png = Image.open(io.BytesIO(self.page.screenshot())).convert('RGB')
213
+ pixel = png.getpixel((round(bounds['x'] + bounds['width'] * .8), round(bounds['y'] + 30)))
214
+ self.assertTrue(max(pixel) < 50 if theme == 'dark' else min(pixel) > 240, (theme, pixel))
215
+ self.assertEqual(image.get_attribute('src'), original)
216
+ self.page.evaluate("document.querySelector('#content').dataset.mode = 'image-pages'")
217
+ self.assertEqual(image.evaluate('e => getComputedStyle(e).filter'), 'none')
218
+
219
  def open_theme_fixture(self, extension, data):
220
  self.page.route("**/api/reader-content**", lambda route: route.fulfill(body=data))
221
  source = urllib.parse.quote(