vomebook commited on
Commit
7372f3f
·
1 Parent(s): 2987803

fix(reader): highlight and follow speech on unrendered PDF pages

Browse files

When the clip being read is on a page or section that is not rendered yet, the adapter navigates there, waits for its text layer and the clip is highlighted once. Auto-follow no longer turns itself off after its own smooth scroll, and HTML frame offsets are included. Adds a sparse 30-page PDF regression test. Previously: playback starts once one batch plus its planning context (1,800 chars) is loaded instead of the full 2,400-char lookahead; slow searches through pages without text show page progress; stop cancels a pending text load. PDF pages already rendered use their text layer.

static/reader/ui/reader-speech.mjs CHANGED
@@ -23,6 +23,14 @@ function textNodes(root) {
23
  return nodes;
24
  }
25
 
 
 
 
 
 
 
 
 
26
  function rootText(root) { return textNodes(root).map((node) => node.data).join(""); }
27
 
28
  // PDF/OCR line breaks are layout, not sentences. Keep the length (and thus
@@ -194,16 +202,27 @@ export function createReaderSpeech(readerContext) {
194
  }
195
  return null;
196
  },
 
 
197
  follow(start) {
198
  const part = self.partAt(start);
199
  if (!part) return;
200
- const range = self.range(start, start + 1), rect = range?.getBoundingClientRect();
 
 
 
 
 
 
 
201
  const box = readerContext.viewport.getBoundingClientRect();
202
- if (rect && rect.height && (rect.bottom > box.bottom - 24 || rect.top < box.top)) {
203
- // Follow only when the previous clip was on screen, i.e. the reader is listening along.
204
- if (self.following) range.startContainer.parentElement?.scrollIntoView({ block: "center", behavior: "smooth" });
205
- } else if (!rect && sourceInfo.page && self.following) sourceInfo.locate?.(part.unit);
206
- self.following = !!rect && rect.bottom > box.top && rect.top < box.bottom;
 
 
207
  },
208
  following: true,
209
  async reveal(offset) {
 
23
  return nodes;
24
  }
25
 
26
+ function until(check, timeout) {
27
+ const deadline = performance.now() + timeout;
28
+ return new Promise((resolve) => {
29
+ const poll = () => (check() || performance.now() > deadline ? resolve() : setTimeout(poll, 100));
30
+ poll();
31
+ });
32
+ }
33
+
34
  function rootText(root) { return textNodes(root).map((node) => node.data).join(""); }
35
 
36
  // PDF/OCR line breaks are layout, not sentences. Keep the length (and thus
 
202
  }
203
  return null;
204
  },
205
+ // Follow only while the listener is reading along (the previous clip was
206
+ // on screen or was brought there by us); a reader who scrolled away is left alone.
207
  follow(start) {
208
  const part = self.partAt(start);
209
  if (!part) return;
210
+ const range = self.range(start, start + 1);
211
+ if (!range) {
212
+ // An unrendered page/section: navigate there and wait for its text.
213
+ if (!self.following || sourceInfo.root(part.unit) || !sourceInfo.locate) return;
214
+ return Promise.resolve(sourceInfo.locate(part.unit)).then(() => until(() => sourceInfo.root(part.unit), 8000));
215
+ }
216
+ const rect = range.getBoundingClientRect();
217
+ if (!rect.height) return;
218
  const box = readerContext.viewport.getBoundingClientRect();
219
+ const shift = sourceInfo.frame ? sourceInfo.frame.getBoundingClientRect().top : 0;
220
+ const top = rect.top + shift, bottom = rect.bottom + shift;
221
+ if (self.following && (bottom > box.bottom - 24 || top < box.top)) {
222
+ range.startContainer.parentElement?.scrollIntoView({ block: "center", behavior: "smooth" });
223
+ return;
224
+ }
225
+ self.following = bottom > box.top && top < box.bottom;
226
  },
227
  following: true,
228
  async reveal(offset) {
static/tts-client.js CHANGED
@@ -348,13 +348,19 @@ if (typeof document !== "undefined") window.CCRDSpeech = (() => {
348
  }
349
  marked = null;
350
  }
351
- function mark() {
352
  clearMark();
353
  if (!owner?.current || preview?.id !== owner.snapshot.id || (owner.snapshot.adapter && preview.adapter !== owner.snapshot.adapter)) return;
354
  const start = owner.current.job.batch.start + owner.current.part.start;
355
  const end = owner.current.job.batch.start + owner.current.part.end;
356
  const range = preview.adapter ? preview.adapter.range?.(start, end) : sourceRange(start, end);
357
- if (!range) return;
 
 
 
 
 
 
358
  if (preview.adapter) {
359
  // The range may live in an iframe document or shadow tree: register it in
360
  // that realm's highlight registry and never mutate the host's DOM.
 
348
  }
349
  marked = null;
350
  }
351
+ function mark(retried = false) {
352
  clearMark();
353
  if (!owner?.current || preview?.id !== owner.snapshot.id || (owner.snapshot.adapter && preview.adapter !== owner.snapshot.adapter)) return;
354
  const start = owner.current.job.batch.start + owner.current.part.start;
355
  const end = owner.current.job.batch.start + owner.current.part.end;
356
  const range = preview.adapter ? preview.adapter.range?.(start, end) : sourceRange(start, end);
357
+ if (!range) {
358
+ // The clip's page/section may not be rendered yet: the adapter can bring
359
+ // it into view, after which the same clip is highlighted once.
360
+ const current = owner.current;
361
+ if (preview.adapter && !retried) Promise.resolve(preview.adapter.follow?.(start, end)).then(() => { if (owner?.current === current) mark(true); }, () => {});
362
+ return;
363
+ }
364
  if (preview.adapter) {
365
  // The range may live in an iframe document or shadow tree: register it in
366
  // that realm's highlight registry and never mutate the host's DOM.
tests/test_reader_speech.py CHANGED
@@ -42,7 +42,7 @@ class ReaderSpeechTest(unittest.TestCase):
42
  cls.origin = cls.server.__enter__()
43
  cls.playwright = sync_playwright().start()
44
  try:
45
- cls.browser = cls.playwright.chromium.launch(headless=True, args=["--no-sandbox", "--autoplay-policy=no-user-gesture-required"])
46
  except PlaywrightError as error:
47
  cls.playwright.stop()
48
  cls.server.__exit__(None, None, None)
@@ -145,6 +145,35 @@ class ReaderSpeechTest(unittest.TestCase):
145
  finally:
146
  context.close()
147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  def test_foliate_epub_reads_sections_in_order(self):
149
  if not (ROOT / "static/foliate-reader/view.js").exists():
150
  self.skipTest("fetch Foliate first: node scripts/build/fetch_foliate_reader.mjs")
 
42
  cls.origin = cls.server.__enter__()
43
  cls.playwright = sync_playwright().start()
44
  try:
45
+ cls.browser = cls.playwright.chromium.launch(headless=True, args=["--no-sandbox", "--autoplay-policy=no-user-gesture-required", "--disable-audio-output"])
46
  except PlaywrightError as error:
47
  cls.playwright.stop()
48
  cls.server.__exit__(None, None, None)
 
145
  finally:
146
  context.close()
147
 
148
+ def test_sparse_pdf_reads_distant_text_page_and_follows_there(self):
149
+ # Like scanned books with an appended information page: only page 30 has text.
150
+ count = 30
151
+ stream = b"BT /F1 18 Tf 20 100 Td (Information Page Text.) Tj ET"
152
+ kids = " ".join(f"{3 + index} 0 R" for index in range(count)).encode()
153
+ objects = [b"<< /Type /Catalog /Pages 2 0 R >>", b"<< /Type /Pages /Kids [" + kids + b"] /Count " + str(count).encode() + b" >>"]
154
+ for index in range(count):
155
+ contents = f" /Contents {3 + count} 0 R" if index == count - 1 else ""
156
+ objects.append(f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /Font << /F1 {4 + count} 0 R >> >>{contents} >>".encode())
157
+ objects += [b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"\nendstream",
158
+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"]
159
+ payload = bytearray(b"%PDF-1.4\n"); offsets = []
160
+ for number, body in enumerate(objects, 1):
161
+ offsets.append(len(payload)); payload.extend(f"{number} 0 obj\n".encode() + body + b"\nendobj\n")
162
+ xref = len(payload); payload.extend(f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode())
163
+ for offset in offsets: payload.extend(f"{offset:010d} 00000 n \n".encode())
164
+ payload.extend(f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode())
165
+ context, page, posts, errors = self.open("pdf", bytes(payload), "application/pdf")
166
+ try:
167
+ job = self.play(page, posts)
168
+ self.assertIn("Information Page Text", job["text"])
169
+ wait(page, "() => CSS.highlights.has('ccrd-speech')", 15000)
170
+ self.assertTrue(page.evaluate("""() => { const r = document.querySelector('.reader-page[data-page="30"]').getBoundingClientRect();
171
+ const v = document.querySelector('#viewport').getBoundingClientRect(); return r.bottom > v.top && r.top < v.bottom; }"""))
172
+ self.stop(page)
173
+ self.assertFalse(errors, errors)
174
+ finally:
175
+ context.close()
176
+
177
  def test_foliate_epub_reads_sections_in_order(self):
178
  if not (ROOT / "static/foliate-reader/view.js").exists():
179
  self.skipTest("fetch Foliate first: node scripts/build/fetch_foliate_reader.mjs")