vomebook commited on
Commit ·
a1c62e3
1
Parent(s): f563661
fix(reader): narrow path hit area and keep speech across reader/search handoff
Browse filesFiles changed (5)
59 unmodified lines6061626364656659 unmodified lines.reader-path { min-width: 0; max-width: 100%; align-self: flex-start; padding: 0; border: 0; background: transparent;412 unmodified lines4134144154164174184197 unmodified lines427428429429430430431432433434435436437438439440441442443444445446447448449450436451452453454150 unmodified lines605606607593608609610611612613614615616617618619620621622623412 unmodified lines if (!String(window.name).startsWith(RESUME_PREFIX)) return null; const value = JSON.parse(window.name.slice(RESUME_PREFIX.length)); window.name = ""; if (value?.pending === true) return { pending: true }; return Number.isInteger(value?.unit) && Number.isInteger(value?.offset) ? value : null; } catch (_) { return null; } })();7 unmodified lines if (!(state?.playing || state?.interrupted) || typeof owner?.partAt !== "function" || !Number.isInteger(state.position)) return; const part = owner.partAt(state.position); if (!part) return; sessionStorage.setItem(HANDOFF_KEY, JSON.stringify({ readerUrl: location.href, unit: part.unit, offset: Math.max(0, Math.min(part.raw.length, state.position - part.start)), at: Date.now() })); const value = JSON.stringify({ readerUrl: location.href, unit: part.unit, offset: Math.max(0, Math.min(part.raw.length, state.position - part.start)), at: Date.now() }); sessionStorage.setItem(HANDOFF_KEY, value); // A Reader opened as the first page later reaches a search document that // was never loaded in this tab; sessionStorage is still shared there, but // localStorage also covers a search page opened in a fresh tab. try { localStorage.setItem(HANDOFF_KEY, value); } catch (_) {} } catch (_) { /* Optional: without storage, leaving stops reading as before. */ } }
async function resumeAt(target) { const info = adapter?.source; if (!info) return; if (target.pending) { let offset = 0; try { offset = await adapter.locateTop(); } catch (_) {} if (adapter?.source !== info) return; adapter.following = true; speech()?.readFrom(offset); return; } if (!info || target.unit < info.first || target.unit >= info.units) return; if (target.unit < info.first || target.unit >= info.units) return; let owner = adapter; if (info.units > 1 && (target.unit < owner.base || !owner.covers(target.unit) && target.unit - owner.base > 2)) owner = rebase(target.unit); await owner.ensureUnit(target.unit);150 unmodified lines function install() { if (installed) return; installed = true; try { if (!readerContext.isReaderOverlayFrame?.()) sessionStorage.removeItem(HANDOFF_KEY); } catch (_) {} try { if (!readerContext.isReaderOverlayFrame?.()) { sessionStorage.removeItem(HANDOFF_KEY); localStorage.removeItem(HANDOFF_KEY); } } catch (_) {} // Starting speech in a newly opened book takes over from the Reader that // was left reading in the background. document.addEventListener("click", (event) => { if (!event.target?.closest?.("[data-speech-toggle]")) return; if (readerContext.isReaderOverlayFrame?.()) window.parent.postMessage({ type: "voice-reader-speech-start" }, location.origin); }, { capture: true }); // ← records it before navigating; pagehide covers browser back and other exits. window.addEventListener("pagehide", handoff, { capture: true }); document.querySelector("#back")?.addEventListener("click", handoff, { capture: true });179 unmodified lines1801811821831831841851861879 unmodified lines1971981992002012022036 unmodified lines21021121221121321421521621721821922065 unmodified lines2862872882832892902912926 unmodified lines2993003013023033043053063073083092993103113123135 unmodified lines3193203213113223233243253263273283293143303313323338 unmodified lines342343344345346347348349350351352353179 unmodified lines function shade(current) { document.body.classList.add("reader-overlay-open"); background = Array.from(document.body.children) .filter((element) => element !== current && element !== opening) .filter((element) => element !== current && element !== opening && !element.classList.contains("reader-speech-mini")) .map((element) => { const state = { element,9 unmodified lines const key = bookKey(url.href); if (parked && key && parked.key === key) { // The same book: show the Reader that kept reading, at its reading position. if (frame && frame !== parked.frame) unmount(false); const { frame: kept } = releaseParked(); returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; frame = kept;6 unmodified lines try { kept.contentWindow.CCRDSpeech?.reveal?.(); } catch (_) {} return kept; } disposeParked(); // A foreground Reader that is reading aloud becomes the background // Reader. A different book's background speech is left running until // the new Reader starts its own reading or the listener stops it. if (frame) unmount(true); if (parked && !speech(parked.frame)?.active) disposeParked(); const next = document.createElement("iframe"); next.className = "reader-overlay"; next.title = "在线阅读";65 unmodified lines if (!next.searchParams.get(key) && current.searchParams.get(key)) next.searchParams.set(key, current.searchParams.get(key)); remember(next, returnScroll, true); const focus = unmount(false); const focus = unmount(bookKey(next.href) !== bookKey(current.href)); mount(next); returnFocus = focus; return frame;6 unmodified lines try { handoff = JSON.parse(sessionStorage.getItem("reader-speech-handoff") || "null"); sessionStorage.removeItem("reader-speech-handoff"); // A Reader opened as the first page (or in another tab) has no prior // search document to hand the session to; localStorage survives that // first search-page load for the same short window. if (!handoff) handoff = JSON.parse(localStorage.getItem("reader-speech-handoff") || "null"); localStorage.removeItem("reader-speech-handoff"); } catch (_) { return; } if (!handoff || !(Date.now() - handoff.at < 30000) || frame || parked || !document.body) return; if (!handoff || !(Date.now() - handoff.at < 300000) || frame || parked || !document.body) return; let url; try { url = parse(handoff.readerUrl);5 unmodified lines const next = document.createElement("iframe"); next.className = "reader-overlay reader-overlay-parked"; next.title = "在线阅读"; next.name = "reader-speech-resume:" + JSON.stringify({ unit: handoff.unit, offset: handoff.offset }); next.name = "reader-speech-resume:" + JSON.stringify(handoff.pending ? { pending: true } : { unit: handoff.unit, offset: handoff.offset }); next.src = url.href; document.body.append(next); // A first load of the search page can take longer than the old 30 s // grace to boot the resumed Reader. Keep the bar until it is reading or // the listener stops it instead of silently dropping the session. park(next, null, Date.now() + 30000); park(next, null, Date.now() + 300000); } if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", resumeSpeech, { once: true }); else setTimeout(resumeSpeech);8 unmodified lines return false; } } // Starting speech in another Reader takes over from the background one. root.addEventListener?.("message", (event) => { if (!accepts(event) || event.data?.type !== "voice-reader-speech-start") return; const background = parked?.frame; if (background && event.source !== background.contentWindow) disposeParked(); }); return Object.freeze({ parse, mergeSearchParams,942 unmodified lines943944945946947948949950951952953954942 unmodified lines path = page.locator("#reader-path") path.wait_for(state="visible", timeout=10000) self.assertEqual(path.text_content(), "Test/一级目录/二级目录") # Only the path text is a target, not the whole title column. geometry = path.evaluate("""n => { const r = n.getBoundingClientRect(), h = n.parentElement.getBoundingClientRect(); const range = document.createRange(); range.selectNodeContents(n); return {button: r.width, heading: h.width, text: range.getBoundingClientRect().width}; }""") self.assertLess(geometry["button"], geometry["heading"] - 40, geometry) self.assertLessEqual(geometry["button"], geometry["text"] + 2, geometry) self.assertTrue(page.locator("#status").is_hidden()) path.click() page.wait_for_url("**/Test?**", timeout=10000)310 unmodified lines31131231331431431531631731831831932032132232332432532632132232732832933033133233333441 unmodified lines376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407310 unmodified lines self.assertEqual(page.locator(".reader-speech-mini").count(), 0) self.assertTrue(page.evaluate("() => document.querySelector('iframe.reader-overlay') === __reader && !__nav.backgroundReader && getComputedStyle(__reader).visibility === 'visible'")) self.assertFalse(frame.evaluate("() => document.querySelector('#speech-audio').paused")) # Opening another book stops background reading and releases its Reader. # Opening another book leaves the background reading untouched. page.evaluate("() => __nav.unmount()") bar.wait_for(timeout=3000) page.evaluate("url => { window.__next = __nav.mount(new URL(url)); }", self.reader_url("txt", "other")) self.assertTrue(page.evaluate("() => !__reader.isConnected && __next !== __reader && !__nav.backgroundReader")) self.assertTrue(page.evaluate("() => __reader.isConnected && __next !== __reader && __nav.backgroundReader === __reader")) self.assertEqual(page.locator(".reader-speech-mini").count(), 1) next_frame = page.wait_for_selector("iframe.reader-overlay:not(.reader-overlay-parked)").content_frame() # Starting the new book's speech is the explicit takeover. self.play(next_frame, posts) wait(page, "() => !__reader.isConnected && !__nav.backgroundReader", 5000) self.assertEqual(page.locator(".reader-speech-mini").count(), 0) # Closing the new reading Reader parks it as the background Reader. page.evaluate("() => __nav.unmount()") # A Reader that is not reading closes normally. self.assertTrue(page.evaluate("() => !__next.isConnected && !__nav.backgroundReader")) bar.wait_for(timeout=3000) self.assertTrue(page.evaluate("() => __next.isConnected && __nav.backgroundReader === __next")) bar.get_by_role("button", name="停止").click() wait(page, "() => !__next.isConnected && !__nav.backgroundReader", 5000) self.assertEqual(page.locator(".reader-speech-mini").count(), 0) self.assertFalse(errors, errors) finally: context.close()41 unmodified lines finally: context.close()
def test_first_search_load_resumes_a_handoff_without_session_storage(self): # A Reader opened as the first page writes both stores. A search document # that was never loaded has no sessionStorage handoff; the localStorage # fallback still lets it show the background bar and resume. context, page, posts, errors = self.open("txt", TEXT.encode(), "text/plain; charset=utf-8") try: self.play(page, posts) reader = page.url base = reader.split("reader.html")[0] page.goto(base + "empty", wait_until="domcontentloaded") # pagehide writes the handoff page.evaluate("() => sessionStorage.removeItem('reader-speech-handoff')") page.goto(base + "search/reader-navigation.js", wait_until="domcontentloaded") page.add_style_tag(content=(ROOT / "static/style.css").read_text(encoding="utf-8")) page.add_script_tag(content=(ROOT / "static/search/reader-navigation.js").read_text(encoding="utf-8")) page.evaluate("url => { window.__nav = VoiceOfMLReaderNavigation.createNavigation(new URL(url).pathname, { resume: next => __nav.mount(new URL(next)) }); }", reader) bar = page.locator(".reader-speech-mini") bar.wait_for(timeout=5000) kept = page.wait_for_selector("iframe.reader-overlay-parked", state="attached") frame = kept.content_frame() wait(frame, "()=>{const a=document.querySelector('#speech-audio');return !!a&&!a.paused&&a.currentTime>0.05}", 30000) self.assertEqual(page.evaluate("() => sessionStorage.getItem('reader-speech-handoff')"), None) self.assertEqual(page.evaluate("() => localStorage.getItem('reader-speech-handoff')"), None) self.assertFalse(errors, errors) finally: context.close()
def test_native_pdf_text_layer_is_read_and_image_is_not_offered(self): context, page, posts, errors = self.open("pdf", minimal_pdf(), "application/pdf") try:static/reader.css+1
static/reader/ui/reader-speech.mjs+31-4
static/search/reader-navigation.js+28-6
tests/test_browser.py+6
tests/test_reader_speech.py+39-4