vomebook commited on
Commit
a1c62e3
·
1 Parent(s): f563661

fix(reader): narrow path hit area and keep speech across reader/search handoff

Browse files
static/reader.css CHANGED
@@ -60,6 +60,7 @@ body {
60
  .reader-path {
61
  min-width: 0;
62
  max-width: 100%;
 
63
  padding: 0;
64
  border: 0;
65
  background: transparent;
 
60
  .reader-path {
61
  min-width: 0;
62
  max-width: 100%;
63
+ align-self: flex-start;
64
  padding: 0;
65
  border: 0;
66
  background: transparent;
static/reader/ui/reader-speech.mjs CHANGED
@@ -413,6 +413,7 @@ export function createReaderSpeech(readerContext) {
413
  if (!String(window.name).startsWith(RESUME_PREFIX)) return null;
414
  const value = JSON.parse(window.name.slice(RESUME_PREFIX.length));
415
  window.name = "";
 
416
  return Number.isInteger(value?.unit) && Number.isInteger(value?.offset) ? value : null;
417
  } catch (_) { return null; }
418
  })();
@@ -426,14 +427,28 @@ export function createReaderSpeech(readerContext) {
426
  if (!(state?.playing || state?.interrupted) || typeof owner?.partAt !== "function" || !Number.isInteger(state.position)) return;
427
  const part = owner.partAt(state.position);
428
  if (!part) return;
429
- sessionStorage.setItem(HANDOFF_KEY, JSON.stringify({ readerUrl: location.href, unit: part.unit,
430
- offset: Math.max(0, Math.min(part.raw.length, state.position - part.start)), at: Date.now() }));
 
 
 
 
 
431
  } catch (_) { /* Optional: without storage, leaving stops reading as before. */ }
432
  }
433
 
434
  async function resumeAt(target) {
435
  const info = adapter?.source;
436
- if (!info || target.unit < info.first || target.unit >= info.units) return;
 
 
 
 
 
 
 
 
 
437
  let owner = adapter;
438
  if (info.units > 1 && (target.unit < owner.base || !owner.covers(target.unit) && target.unit - owner.base > 2)) owner = rebase(target.unit);
439
  await owner.ensureUnit(target.unit);
@@ -590,7 +605,19 @@ export function createReaderSpeech(readerContext) {
590
  function install() {
591
  if (installed) return;
592
  installed = true;
593
- try { if (!readerContext.isReaderOverlayFrame?.()) sessionStorage.removeItem(HANDOFF_KEY); } catch (_) {}
 
 
 
 
 
 
 
 
 
 
 
 
594
  // ← records it before navigating; pagehide covers browser back and other exits.
595
  window.addEventListener("pagehide", handoff, { capture: true });
596
  document.querySelector("#back")?.addEventListener("click", handoff, { capture: true });
 
413
  if (!String(window.name).startsWith(RESUME_PREFIX)) return null;
414
  const value = JSON.parse(window.name.slice(RESUME_PREFIX.length));
415
  window.name = "";
416
+ if (value?.pending === true) return { pending: true };
417
  return Number.isInteger(value?.unit) && Number.isInteger(value?.offset) ? value : null;
418
  } catch (_) { return null; }
419
  })();
 
427
  if (!(state?.playing || state?.interrupted) || typeof owner?.partAt !== "function" || !Number.isInteger(state.position)) return;
428
  const part = owner.partAt(state.position);
429
  if (!part) return;
430
+ const value = JSON.stringify({ readerUrl: location.href, unit: part.unit,
431
+ offset: Math.max(0, Math.min(part.raw.length, state.position - part.start)), at: Date.now() });
432
+ sessionStorage.setItem(HANDOFF_KEY, value);
433
+ // A Reader opened as the first page later reaches a search document that
434
+ // was never loaded in this tab; sessionStorage is still shared there, but
435
+ // localStorage also covers a search page opened in a fresh tab.
436
+ try { localStorage.setItem(HANDOFF_KEY, value); } catch (_) {}
437
  } catch (_) { /* Optional: without storage, leaving stops reading as before. */ }
438
  }
439
 
440
  async function resumeAt(target) {
441
  const info = adapter?.source;
442
+ if (!info) return;
443
+ if (target.pending) {
444
+ let offset = 0;
445
+ try { offset = await adapter.locateTop(); } catch (_) {}
446
+ if (adapter?.source !== info) return;
447
+ adapter.following = true;
448
+ speech()?.readFrom(offset);
449
+ return;
450
+ }
451
+ if (target.unit < info.first || target.unit >= info.units) return;
452
  let owner = adapter;
453
  if (info.units > 1 && (target.unit < owner.base || !owner.covers(target.unit) && target.unit - owner.base > 2)) owner = rebase(target.unit);
454
  await owner.ensureUnit(target.unit);
 
605
  function install() {
606
  if (installed) return;
607
  installed = true;
608
+ try {
609
+ if (!readerContext.isReaderOverlayFrame?.()) {
610
+ sessionStorage.removeItem(HANDOFF_KEY);
611
+ localStorage.removeItem(HANDOFF_KEY);
612
+ }
613
+ } catch (_) {}
614
+ // Starting speech in a newly opened book takes over from the Reader that
615
+ // was left reading in the background.
616
+ document.addEventListener("click", (event) => {
617
+ if (!event.target?.closest?.("[data-speech-toggle]")) return;
618
+ if (readerContext.isReaderOverlayFrame?.())
619
+ window.parent.postMessage({ type: "voice-reader-speech-start" }, location.origin);
620
+ }, { capture: true });
621
  // ← records it before navigating; pagehide covers browser back and other exits.
622
  window.addEventListener("pagehide", handoff, { capture: true });
623
  document.querySelector("#back")?.addEventListener("click", handoff, { capture: true });
static/search/reader-navigation.js CHANGED
@@ -180,7 +180,8 @@
180
  function shade(current) {
181
  document.body.classList.add("reader-overlay-open");
182
  background = Array.from(document.body.children)
183
- .filter((element) => element !== current && element !== opening)
 
184
  .map((element) => {
185
  const state = {
186
  element,
@@ -196,6 +197,7 @@
196
  const key = bookKey(url.href);
197
  if (parked && key && parked.key === key) {
198
  // The same book: show the Reader that kept reading, at its reading position.
 
199
  const { frame: kept } = releaseParked();
200
  returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
201
  frame = kept;
@@ -208,7 +210,11 @@
208
  try { kept.contentWindow.CCRDSpeech?.reveal?.(); } catch (_) {}
209
  return kept;
210
  }
211
- disposeParked();
 
 
 
 
212
  const next = document.createElement("iframe");
213
  next.className = "reader-overlay";
214
  next.title = "在线阅读";
@@ -280,7 +286,7 @@
280
  if (!next.searchParams.get(key) && current.searchParams.get(key))
281
  next.searchParams.set(key, current.searchParams.get(key));
282
  remember(next, returnScroll, true);
283
- const focus = unmount(false);
284
  mount(next);
285
  returnFocus = focus;
286
  return frame;
@@ -293,10 +299,15 @@
293
  try {
294
  handoff = JSON.parse(sessionStorage.getItem("reader-speech-handoff") || "null");
295
  sessionStorage.removeItem("reader-speech-handoff");
 
 
 
 
 
296
  } catch (_) {
297
  return;
298
  }
299
- if (!handoff || !(Date.now() - handoff.at < 30000) || frame || parked || !document.body) return;
300
  let url;
301
  try {
302
  url = parse(handoff.readerUrl);
@@ -308,10 +319,15 @@
308
  const next = document.createElement("iframe");
309
  next.className = "reader-overlay reader-overlay-parked";
310
  next.title = "在线阅读";
311
- next.name = "reader-speech-resume:" + JSON.stringify({ unit: handoff.unit, offset: handoff.offset });
 
 
312
  next.src = url.href;
313
  document.body.append(next);
314
- park(next, null, Date.now() + 30000);
 
 
 
315
  }
316
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", resumeSpeech, { once: true });
317
  else setTimeout(resumeSpeech);
@@ -326,6 +342,12 @@
326
  return false;
327
  }
328
  }
 
 
 
 
 
 
329
  return Object.freeze({
330
  parse,
331
  mergeSearchParams,
 
180
  function shade(current) {
181
  document.body.classList.add("reader-overlay-open");
182
  background = Array.from(document.body.children)
183
+ .filter((element) => element !== current && element !== opening &&
184
+ !element.classList.contains("reader-speech-mini"))
185
  .map((element) => {
186
  const state = {
187
  element,
 
197
  const key = bookKey(url.href);
198
  if (parked && key && parked.key === key) {
199
  // The same book: show the Reader that kept reading, at its reading position.
200
+ if (frame && frame !== parked.frame) unmount(false);
201
  const { frame: kept } = releaseParked();
202
  returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
203
  frame = kept;
 
210
  try { kept.contentWindow.CCRDSpeech?.reveal?.(); } catch (_) {}
211
  return kept;
212
  }
213
+ // A foreground Reader that is reading aloud becomes the background
214
+ // Reader. A different book's background speech is left running until
215
+ // the new Reader starts its own reading or the listener stops it.
216
+ if (frame) unmount(true);
217
+ if (parked && !speech(parked.frame)?.active) disposeParked();
218
  const next = document.createElement("iframe");
219
  next.className = "reader-overlay";
220
  next.title = "在线阅读";
 
286
  if (!next.searchParams.get(key) && current.searchParams.get(key))
287
  next.searchParams.set(key, current.searchParams.get(key));
288
  remember(next, returnScroll, true);
289
+ const focus = unmount(bookKey(next.href) !== bookKey(current.href));
290
  mount(next);
291
  returnFocus = focus;
292
  return frame;
 
299
  try {
300
  handoff = JSON.parse(sessionStorage.getItem("reader-speech-handoff") || "null");
301
  sessionStorage.removeItem("reader-speech-handoff");
302
+ // A Reader opened as the first page (or in another tab) has no prior
303
+ // search document to hand the session to; localStorage survives that
304
+ // first search-page load for the same short window.
305
+ if (!handoff) handoff = JSON.parse(localStorage.getItem("reader-speech-handoff") || "null");
306
+ localStorage.removeItem("reader-speech-handoff");
307
  } catch (_) {
308
  return;
309
  }
310
+ if (!handoff || !(Date.now() - handoff.at < 300000) || frame || parked || !document.body) return;
311
  let url;
312
  try {
313
  url = parse(handoff.readerUrl);
 
319
  const next = document.createElement("iframe");
320
  next.className = "reader-overlay reader-overlay-parked";
321
  next.title = "在线阅读";
322
+ next.name = "reader-speech-resume:" + JSON.stringify(handoff.pending
323
+ ? { pending: true }
324
+ : { unit: handoff.unit, offset: handoff.offset });
325
  next.src = url.href;
326
  document.body.append(next);
327
+ // A first load of the search page can take longer than the old 30 s
328
+ // grace to boot the resumed Reader. Keep the bar until it is reading or
329
+ // the listener stops it instead of silently dropping the session.
330
+ park(next, null, Date.now() + 300000);
331
  }
332
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", resumeSpeech, { once: true });
333
  else setTimeout(resumeSpeech);
 
342
  return false;
343
  }
344
  }
345
+ // Starting speech in another Reader takes over from the background one.
346
+ root.addEventListener?.("message", (event) => {
347
+ if (!accepts(event) || event.data?.type !== "voice-reader-speech-start") return;
348
+ const background = parked?.frame;
349
+ if (background && event.source !== background.contentWindow) disposeParked();
350
+ });
351
  return Object.freeze({
352
  parse,
353
  mergeSearchParams,
tests/test_browser.py CHANGED
@@ -943,6 +943,12 @@ class BrowserInteractionTests(unittest.TestCase):
943
  path = page.locator("#reader-path")
944
  path.wait_for(state="visible", timeout=10000)
945
  self.assertEqual(path.text_content(), "Test/一级目录/二级目录")
 
 
 
 
 
 
946
  self.assertTrue(page.locator("#status").is_hidden())
947
  path.click()
948
  page.wait_for_url("**/Test?**", timeout=10000)
 
943
  path = page.locator("#reader-path")
944
  path.wait_for(state="visible", timeout=10000)
945
  self.assertEqual(path.text_content(), "Test/一级目录/二级目录")
946
+ # Only the path text is a target, not the whole title column.
947
+ geometry = path.evaluate("""n => { const r = n.getBoundingClientRect(), h = n.parentElement.getBoundingClientRect();
948
+ const range = document.createRange(); range.selectNodeContents(n);
949
+ return {button: r.width, heading: h.width, text: range.getBoundingClientRect().width}; }""")
950
+ self.assertLess(geometry["button"], geometry["heading"] - 40, geometry)
951
+ self.assertLessEqual(geometry["button"], geometry["text"] + 2, geometry)
952
  self.assertTrue(page.locator("#status").is_hidden())
953
  path.click()
954
  page.wait_for_url("**/Test?**", timeout=10000)
tests/test_reader_speech.py CHANGED
@@ -311,15 +311,24 @@ class ReaderSpeechTest(unittest.TestCase):
311
  self.assertEqual(page.locator(".reader-speech-mini").count(), 0)
312
  self.assertTrue(page.evaluate("() => document.querySelector('iframe.reader-overlay') === __reader && !__nav.backgroundReader && getComputedStyle(__reader).visibility === 'visible'"))
313
  self.assertFalse(frame.evaluate("() => document.querySelector('#speech-audio').paused"))
314
- # Opening another book stops background reading and releases its Reader.
315
  page.evaluate("() => __nav.unmount()")
316
  bar.wait_for(timeout=3000)
317
  page.evaluate("url => { window.__next = __nav.mount(new URL(url)); }", self.reader_url("txt", "other"))
318
- self.assertTrue(page.evaluate("() => !__reader.isConnected && __next !== __reader && !__nav.backgroundReader"))
 
 
 
 
 
319
  self.assertEqual(page.locator(".reader-speech-mini").count(), 0)
 
320
  page.evaluate("() => __nav.unmount()")
321
- # A Reader that is not reading closes normally.
322
- self.assertTrue(page.evaluate("() => !__next.isConnected && !__nav.backgroundReader"))
 
 
 
323
  self.assertFalse(errors, errors)
324
  finally:
325
  context.close()
@@ -367,6 +376,32 @@ class ReaderSpeechTest(unittest.TestCase):
367
  finally:
368
  context.close()
369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
  def test_native_pdf_text_layer_is_read_and_image_is_not_offered(self):
371
  context, page, posts, errors = self.open("pdf", minimal_pdf(), "application/pdf")
372
  try:
 
311
  self.assertEqual(page.locator(".reader-speech-mini").count(), 0)
312
  self.assertTrue(page.evaluate("() => document.querySelector('iframe.reader-overlay') === __reader && !__nav.backgroundReader && getComputedStyle(__reader).visibility === 'visible'"))
313
  self.assertFalse(frame.evaluate("() => document.querySelector('#speech-audio').paused"))
314
+ # Opening another book leaves the background reading untouched.
315
  page.evaluate("() => __nav.unmount()")
316
  bar.wait_for(timeout=3000)
317
  page.evaluate("url => { window.__next = __nav.mount(new URL(url)); }", self.reader_url("txt", "other"))
318
+ self.assertTrue(page.evaluate("() => __reader.isConnected && __next !== __reader && __nav.backgroundReader === __reader"))
319
+ self.assertEqual(page.locator(".reader-speech-mini").count(), 1)
320
+ next_frame = page.wait_for_selector("iframe.reader-overlay:not(.reader-overlay-parked)").content_frame()
321
+ # Starting the new book's speech is the explicit takeover.
322
+ self.play(next_frame, posts)
323
+ wait(page, "() => !__reader.isConnected && !__nav.backgroundReader", 5000)
324
  self.assertEqual(page.locator(".reader-speech-mini").count(), 0)
325
+ # Closing the new reading Reader parks it as the background Reader.
326
  page.evaluate("() => __nav.unmount()")
327
+ bar.wait_for(timeout=3000)
328
+ self.assertTrue(page.evaluate("() => __next.isConnected && __nav.backgroundReader === __next"))
329
+ bar.get_by_role("button", name="停止").click()
330
+ wait(page, "() => !__next.isConnected && !__nav.backgroundReader", 5000)
331
+ self.assertEqual(page.locator(".reader-speech-mini").count(), 0)
332
  self.assertFalse(errors, errors)
333
  finally:
334
  context.close()
 
376
  finally:
377
  context.close()
378
 
379
+ def test_first_search_load_resumes_a_handoff_without_session_storage(self):
380
+ # A Reader opened as the first page writes both stores. A search document
381
+ # that was never loaded has no sessionStorage handoff; the localStorage
382
+ # fallback still lets it show the background bar and resume.
383
+ context, page, posts, errors = self.open("txt", TEXT.encode(), "text/plain; charset=utf-8")
384
+ try:
385
+ self.play(page, posts)
386
+ reader = page.url
387
+ base = reader.split("reader.html")[0]
388
+ page.goto(base + "empty", wait_until="domcontentloaded") # pagehide writes the handoff
389
+ page.evaluate("() => sessionStorage.removeItem('reader-speech-handoff')")
390
+ page.goto(base + "search/reader-navigation.js", wait_until="domcontentloaded")
391
+ page.add_style_tag(content=(ROOT / "static/style.css").read_text(encoding="utf-8"))
392
+ page.add_script_tag(content=(ROOT / "static/search/reader-navigation.js").read_text(encoding="utf-8"))
393
+ page.evaluate("url => { window.__nav = VoiceOfMLReaderNavigation.createNavigation(new URL(url).pathname, { resume: next => __nav.mount(new URL(next)) }); }", reader)
394
+ bar = page.locator(".reader-speech-mini")
395
+ bar.wait_for(timeout=5000)
396
+ kept = page.wait_for_selector("iframe.reader-overlay-parked", state="attached")
397
+ frame = kept.content_frame()
398
+ wait(frame, "()=>{const a=document.querySelector('#speech-audio');return !!a&&!a.paused&&a.currentTime>0.05}", 30000)
399
+ self.assertEqual(page.evaluate("() => sessionStorage.getItem('reader-speech-handoff')"), None)
400
+ self.assertEqual(page.evaluate("() => localStorage.getItem('reader-speech-handoff')"), None)
401
+ self.assertFalse(errors, errors)
402
+ finally:
403
+ context.close()
404
+
405
  def test_native_pdf_text_layer_is_read_and_image_is_not_offered(self):
406
  context, page, posts, errors = self.open("pdf", minimal_pdf(), "application/pdf")
407
  try: