vomebook commited on
Commit ·
166a79c
1
Parent(s): 11c5876
feat(reader): Readwise-style follow, 回到原位置 toggle, background listening
Browse filesAny reader-initiated scroll (wheel/touch/scroll keys/pointer navigation) stops auto-follow until 回到播放位置 or a new start, so sentences no longer pull the page back. After 回到播放位置 the button reads 回到原位置 until the playing sentence leaves the view. 听书 starts at the first line in view (loading that page/section first). The button appears only once text is found near the reading position (scanned PDFs, comics). Closing a Reader that is reading keeps it hidden with a small player (返回阅读/暂停/停止); reopening the same book reuses it, opening another book releases it. The shared player keeps list numbers (1. / (3).) with their item.
Files changed (6)
2442 unmodified lines244324442445244624462447244824492450245124522442 unmodified lineslet readerOverlay = null;let readerUiState = "base";let readerClosing = false;const readerNavigation = VoiceOfMLReaderNavigation.createNavigation("/static/reader.html");const readerNavigation = VoiceOfMLReaderNavigation.createNavigation("/static/reader.html", { // "返回阅读" on the background-reading bar reopens the kept Reader. resume: (url) => navigateToReader(url)});let readerReturnScrollState = null;let readerReturnSnapshot = null;let readerReturnRestoreGeneration = 0;195 unmodified lines19619719819920020120220320420520620720820921021121221321421533 unmodified lines24925025123825225325425525619 unmodified lines27627727826427928028128226626728328428528628728828929029129229329429529629729851 unmodified lines35035135232532632732832933035335435535635735835936036136236336436533336636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539612 unmodified lines40941041141241341441517 unmodified lines4334344354364374384397 unmodified lines4474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025 unmodified lines5085095104054064074085115125135145155165175184 unmodified lines523524525419526527528529530531532533534535536537421422423424425538539540541542543544545195 unmodified lines }); return chain; }, // Load through `unit` (the unit the reader is looking at). ensureUnit(unit) { chain = chain.then(async () => { for (let guard = 0; !done && next <= unit && guard < 400; guard++) await loadNext(); }); return chain; }, // Offset of a unit-local position; past an empty unit, the next text. offsetOf(position) { const part = parts.find((item) => item.unit === position.unit); if (part) return part.start + Math.min(position.offset, part.raw.length); return parts.find((item) => item.unit > position.unit)?.start ?? text.length; }, locateTop: () => locateTop(), partAt(offset) { let low = 0, high = parts.length - 1; while (low <= high) {33 unmodified lines const part = self.partAt(start); if (!part) return; self.current = start; if (!self.following) return; // Parked in the background (Reader closed while reading): no layout to follow. if (!self.following || !readerContext.viewport.getClientRects().length) return; const range = self.range(start, start + 1); if (!range) { // An unrendered page/section: navigate there and wait for its text.19 unmodified lines const top = rect.top + shift, bottom = rect.bottom + shift; return { inside: top >= box.top && bottom <= box.bottom - 24, overlaps: bottom > box.top && top < box.bottom }; }, // A settled scroll that we did not start: follow only if the clip is still on screen. // Any scroll the reader starts (wheel, touch, scroll keys, scrollbar, // TOC/progress navigation) stops following; only "回到播放位置" or a new // start resumes it (Readwise Reader / Spotify "Sync" model, no timeout). userScrolled() { if (self.current === null || performance.now() < self.autoUntil) return; self.following = !!self.visible(self.current)?.overlaps; if (performance.now() < self.autoUntil) return; self.following = false; }, inView(offset) { return !!self.visible(offset)?.overlaps; }, saveView() { const win = sourceInfo.frame?.contentWindow; return { top: readerContext.viewport.scrollTop, frame: win ? win.scrollY : null }; }, restoreView(view) { self.following = false; self.autoUntil = performance.now() + 600; readerContext.viewport.scrollTop = view.top; if (view.frame !== null) sourceInfo.frame?.contentWindow?.scrollTo(0, view.frame); }, async reveal(offset) { const part = self.partAt(offset);51 unmodified lines } const root = info.root(unit); if (!root) return { unit, offset: 0 }; const doc = root.ownerDocument || document; let x = box.left + 24, y = box.top + 12; if (info.frame) { const frameBox = info.frame.getBoundingClientRect(); x = 24; y = Math.max(12, box.top - frameBox.top + 12); } const shadow = root.getRootNode?.(); const caret = caretIn(doc, x, y, shadow?.nodeType === 11 ? [shadow] : []); if (!caret || !root.contains(caret.node)) return { unit, offset: 0 }; // First character whose line reaches below the viewport top. Rendered // characters are in reading order, so a binary search over each text node // is exact even for one 32 KiB TXT text node (no hit-testing guesswork). const shift = info.frame ? info.frame.getBoundingClientRect().top : 0; const limit = box.top + 4 - shift; const doc = root.ownerDocument || document, range = doc.createRange(); const bottom = (node, index) => { range.setStart(node, index); range.setEnd(node, Math.min(node.length, index + 1)); const rect = [...range.getClientRects()].find((item) => item.height) || range.getBoundingClientRect(); return rect.height ? rect.bottom : null; }; let total = 0; for (const node of textNodes(root)) { if (node === caret.node) return { unit, offset: total + caret.offset }; const last = bottom(node, Math.max(0, node.length - 1)); if (last !== null && last > limit) { let low = 0, high = node.length - 1; while (low < high) { const middle = (low + high) >> 1, value = bottom(node, middle); if (value !== null && value > limit) high = middle; else low = middle + 1; } return { unit, offset: total + low }; } total += node.length; } return { unit, offset: 0 }; }
// Exact start for "听书"/"从当前阅读位置开始": the window is re-based to the // unit in view when it is not loaded (or would need many earlier units). async function locateTop() { const position = topPosition(); if (!adapter || !position) return 0; let target = adapter; if (target.source.units > 1 && (position.unit < target.base || !target.covers(position.unit) && position.unit - target.base > 2)) { target = rebase(position.unit); } await target.ensureUnit(position.unit); target.following = true; // Reading starts where the reader looks: follow it. return target.offsetOf(position); }
// ---- Publication to the shared player -------------------------------------- function publish(next) { adapter = next;12 unmodified lines }
function syncToView() { if (!adapter && offerSource) { offer(offerSource); return; } if (!adapter || adapter.source.units <= 1) return; const state = speech()?.state?.(); if (state?.active) return; // Never re-base under active playback.17 unmodified lines global = next.offsetFromNode(node, offset); if (global === null || global === undefined) return; } if (adapter) adapter.following = true; speech()?.readFrom(global); }
7 unmodified lines }
// ---- Lifecycle --------------------------------------------------------------- // Formats whose text may be absent (scanned PDF, comic books, empty files) // only get the button once text is found at/near the reading position. const probeText = new Map(), probeSeen = new Map(); let generation = 0, probing = null, offerSource = null;
function withProbeCache(info) { const load = info.load; return { ...info, load: (unit) => { const hit = probeText.get(unit); if (hit) { probeText.delete(unit); return hit; } return load(unit); } }; }
function needsProbe(info) { const current = mode(); if (current === "epub-chapters") return false; if (current === "pdf-pages" && (readerContext.ocrManifestUrl || readerContext.pdfOcrManifest)) return false; return true; }
async function probe(info, owner) { const from = info.units > 1 ? (topPosition()?.unit ?? info.first) : info.first; for (let unit = Math.max(info.first, from - 1); unit < Math.min(info.units, from + 12); unit++) { if (!probeSeen.has(unit)) { const text = Promise.resolve(info.load(unit)).then((value) => String(value || ""), () => ""); probeText.set(unit, text); probeSeen.set(unit, text.then((value) => !!value.trim())); } const found = await probeSeen.get(unit); if (owner !== generation) return null; if (found) return from; } return null; }
function offer(info) { if (adapter || probing) return; const owner = generation; probing = probe(info, owner).then((from) => { if (owner !== generation) return; probing = null; if (from === null || adapter) return; publish(createAdapter(info, info.units > 1 ? Math.max(info.first, from - 1) : info.first)); }, () => { if (owner === generation) probing = null; }); }
function detach() { generation++; probing = null; offerSource = null; probeText.clear(); probeSeen.clear(); for (const off of cleanup.splice(0)) off(); adapter = null; speech()?.previewClosed();5 unmodified lines if (!player) return; document.querySelector("[data-speech-toggle]")?.remove(); if (!hasText()) return; const info = source(); if (!info || info.units <= info.first) return; const start = info.units > 1 ? Math.max(info.first, (topPosition()?.unit ?? info.first) - 1) : info.first; publish(createAdapter(info, start)); const raw = source(); if (!raw || raw.units <= raw.first) return; const info = withProbeCache(raw); if (needsProbe(info)) { offerSource = info; offer(info); } else publish(createAdapter(info, info.units > 1 ? Math.max(info.first, (topPosition()?.unit ?? info.first) - 1) : info.first)); const listen = (target, type, handler, options) => { if (!target) return; target.addEventListener(type, handler, options);4 unmodified lines let timer = 0, settle = 0; const onScroll = () => { clearTimeout(timer); timer = setTimeout(syncToView, 250); clearTimeout(settle); settle = setTimeout(() => adapter?.userScrolled(), 150); clearTimeout(settle); settle = setTimeout(() => speech()?.viewChanged?.(), 150); }; // Reader-initiated movement stops auto-follow at once, including during one // of our own smooth scrolls. Scroll events alone (layout shifts, lazy pages, // our own follow) never do. The player panel's buttons are excluded. const keys = new Set(["PageUp", "PageDown", "Home", "End", "ArrowUp", "ArrowDown", " ", "Spacebar"]); const onIntent = (event) => { if (!adapter || event.target?.closest?.("#speech-panel, .reader-actions")) return; if (event.type === "keydown" && !keys.has(event.key)) return; adapter.autoUntil = 0; adapter.userScrolled(); }; // Direct input overrides one of our smooth scrolls still in progress. const onIntent = () => { if (adapter) adapter.autoUntil = 0; }; for (const target of [readerContext.viewport, info.frame?.contentDocument]) { listen(target, "scroll", onScroll, { passive: true, capture: true }); for (const type of ["wheel", "touchstart", "keydown"]) listen(target, type, onIntent, { passive: true, capture: true }); const intentTargets = [document, info.frame?.contentDocument]; for (const target of intentTargets) { for (const type of ["wheel", "touchmove", "keydown", "pointerdown"]) listen(target, type, onIntent, { passive: true, capture: true }); } listen(readerContext.viewport, "scroll", onScroll, { passive: true, capture: true }); if (info.frame?.contentWindow) listen(info.frame.contentWindow, "scroll", onScroll, { passive: true }); cleanup.push(() => { clearTimeout(timer); clearTimeout(settle); }); ensureStyle(document);123345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310464 unmodified lines16917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520626 unmodified lines2332342351132362371161171181191201211221231241251261272382392402413 unmodified lines24524624724813724925013914014114214314414525125225325425516 unmodified lines27227327416827527627727818 unmodified lines297298299300301302303304305306(function (root) { "use strict"; function createNavigation(readerPath) { function createNavigation(readerPath, options = {}) { let frame = null; let returnFocus = null; let background = []; let opening = null; let releaseOpening = null; // A Reader closed while reading aloud stays alive, hidden, with a small // player on the search page; reopening the same book reuses it. let parked = null; const sessionKey = "reader-navigation-current"; function bookKey(raw) { try { const params = new URL(raw, location.origin).searchParams; return params.get("id") ? "id:" + params.get("id") : "url:" + params.get("url") + "|" + params.get("ext"); } catch (_) { return ""; } } function speech(target) { try { return target?.contentWindow?.CCRDSpeech?.state?.() || null; } catch (_) { return null; } } function dispose(target) { try { // Run lifecycle cleanup before detaching the browsing context. target.contentWindow?.dispatchEvent(new Event("voice-reader-dispose")); target.contentWindow?.postMessage({ type: "voice-reader-abort" }, location.origin); } catch (_) {} target.src = "about:blank"; target.remove(); } function releaseParked() { if (!parked) return null; const current = parked; parked = null; clearInterval(current.timer); current.bar.remove(); return current; } function disposeParked() { const current = releaseParked(); if (current) dispose(current.frame); } function inFrame(target, selector) { try { return target.contentDocument?.querySelector(selector) || null; } catch (_) { return null; } } function park(target, focus) { disposeParked(); target.classList.add("reader-overlay-parked"); target.setAttribute("inert", ""); target.setAttribute("aria-hidden", "true"); const bar = document.createElement("div"); bar.className = "reader-speech-mini"; bar.setAttribute("role", "region"); bar.setAttribute("aria-label", "后台朗读"); const label = document.createElement("span"); label.className = "reader-speech-mini-title"; const button = (text, action) => { const element = document.createElement("button"); element.type = "button"; element.textContent = text; element.addEventListener("click", action); return element; }; const back = button("返回阅读", () => { const url = target.src; if (typeof options.resume === "function") options.resume(url); else root.dispatchEvent(new CustomEvent("voice-reader-resume", { detail: url })); }); back.className = "reader-speech-mini-back"; const play = button("暂停", () => inFrame(target, "#speech-play")?.click()); const stop = button("停止", () => { inFrame(target, "#speech-stop")?.click(); disposeParked(); }); stop.setAttribute("aria-label", "停止朗读并关闭阅读器"); bar.append(label, back, play, stop); const sync = () => { const state = speech(target); if (!state?.active) { if (parked?.frame === target) disposeParked(); return; } const title = inFrame(target, "#speech-title")?.textContent?.trim() || "朗读"; const status = inFrame(target, "#speech-status")?.textContent?.trim() || ""; label.textContent = status ? `${title} · ${status}` : title; play.textContent = inFrame(target, "#speech-play")?.textContent?.trim() || (state.playing ? "暂停" : "继续"); }; document.body.append(bar); parked = { frame: target, bar, focus, key: bookKey(target.src), timer: setInterval(sync, 1000) }; sync(); } function parse(raw) { const url = new URL(raw, location.origin); if (url.origin !== location.origin || url.pathname !== readerPath)64 unmodified lines share.href ); } function shade(current) { document.body.classList.add("reader-overlay-open"); background = Array.from(document.body.children) .filter((element) => element !== current && element !== opening) .map((element) => { const state = { element, inert: element.hasAttribute("inert"), ariaHidden: element.getAttribute("aria-hidden") }; element.setAttribute("inert", ""); element.setAttribute("aria-hidden", "true"); return state; }); } function mount(url) { const key = bookKey(url.href); if (parked && key && parked.key === key) { // The same book: show the Reader that kept reading, at its reading position. const { frame: kept } = releaseParked(); returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; frame = kept; kept.classList.remove("reader-overlay-parked"); kept.removeAttribute("inert"); kept.removeAttribute("aria-hidden"); shade(kept); kept.focus(); // Show the sentence being read (not the "回到原位置" toggle of the panel button). try { kept.contentWindow.CCRDSpeech?.reveal?.(); } catch (_) {} return kept; } disposeParked(); const next = document.createElement("iframe"); next.className = "reader-overlay"; next.title = "在线阅读";26 unmodified lines }; window.addEventListener("message", onShell); releaseOpening = () => { window.removeEventListener("message", onShell); releaseOpening = null; }; document.body.classList.add("reader-overlay-open"); document.body.append(next, opening); back.focus(); background = Array.from(document.body.children) .filter((element) => element !== next && element !== opening) .map((element) => { const state = { element, inert: element.hasAttribute("inert"), ariaHidden: element.getAttribute("aria-hidden") }; element.setAttribute("inert", ""); element.setAttribute("aria-hidden", "true"); return state; }); shade(next); next.addEventListener( "load", () => {3 unmodified lines ); return next; } // `keepSpeech` parks a Reader that is reading aloud instead of disposing it. function unmount() { function unmount(keepSpeech = true) { if (!frame) return null; try { // Run lifecycle cleanup before detaching the browsing context. frame.contentWindow?.dispatchEvent(new Event("voice-reader-dispose")); frame.contentWindow?.postMessage({ type: "voice-reader-abort" }, location.origin); } catch (_) {} frame.src = "about:blank"; frame.remove(); if (keepSpeech && opening === null && speech(frame)?.active) park(frame); else dispose(frame); frame = null; opening?.remove(); opening = null;16 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(); const focus = unmount(false); mount(next); returnFocus = focus; return frame;18 unmodified lines unmount, replace, accepts, disposeBackground: disposeParked, get backgroundReader() { return parked?.frame || null; }, get returnFocus() { return returnFocus; }1991 unmodified lines19921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720281991 unmodified lines.result-item.selected { background: color-mix(in srgb, var(--primary) 15%, transparent) !important;}
/* A Reader closed while reading aloud stays alive here, hidden. */.reader-overlay-parked { visibility: hidden; pointer-events: none; }.reader-speech-mini { position: fixed; left: 50%; bottom: max(12px, env(safe-area-inset-bottom)); transform: translateX(-50%); z-index: 9000; display: flex; align-items: center; gap: 6px; width: min(560px, calc(100vw - 24px)); padding: 6px 8px 6px 14px; border-radius: 24px; background: var(--primary-container); color: var(--on-primary-container); box-shadow: 0 6px 20px rgba(0, 0, 0, .28); font-size: 13px;}.reader-speech-mini-title { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }.reader-speech-mini button { flex: 0 0 auto; min-height: 32px; padding: 0 12px; border: 0; border-radius: 16px; background: transparent; color: inherit; font: inherit; cursor: pointer;}.reader-speech-mini .reader-speech-mini-back { background: var(--primary); color: var(--on-primary); }.reader-speech-mini button:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }43 unmodified lines444546474748495037 unmodified lines88899091919293949596979899100101102103104105106107108109110111112113204 unmodified lines31831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136214 unmodified lines37737837938038138238342 unmodified lines426427428429430431432341 unmodified lines7747757767177777787797807817827837847857867877887897907917927938 unmodified lines80280380473480580680780880981085 unmodified lines89689789882689990090190217 unmodified lines92092192292392492592692792892943 unmodified lines // The fast first clip may extend to the first punctuation within 32 // characters instead of being cut mid-clause at about 16. const ceiling = offsets[Math.min(chars.length, position + (short ? 32 : 120))]; const hard = cuts.find(value => value.end > start && value.end <= ceiling && /[。!?!?;;\n.][”’"'」』))\t \r]*$/u.test(text.slice(start, value.end))); const hard = cuts.find(value => value.end > start && value.end <= ceiling && endsSentence(text, value.end)); const natural = cuts.filter(value => value.end > start + (short ? 4 : 20) && value.end <= ceiling && /[,,::、—…][”’"'」』))\t \r]*$/u.test(text.slice(start, value.end)) && !connectorOnly(text.slice(start, value.end).trim())); let end;37 unmodified lines return offset && /[\uDC00-\uDFFF]/u.test(text[offset] || "") && /[\uD800-\uDBFF]/u.test(text[offset - 1]) ? offset - 1 : offset; } function boundary(text, index) { return ending.test(text[index]) || (text[index] === "." && !ascii.test(text[index + 1] || "")); return ending.test(text[index]) || (text[index] === "." && !ascii.test(text[index + 1] || "") && !listMarker(text, index)); } // "1." / "12." / "一." / "(3)." at a line or clause start number the item that // follows; that period must not end a sentence ("1." spoken alone, then the item). function listMarker(text, index) { let cursor = index; const closed = cursor > 0 && /[))]/u.test(text[cursor - 1]); if (closed) cursor -= 1; const digits = cursor; while (cursor > 0 && digits - cursor < 4 && /[0-90-9一二三四五六七八九十百]/u.test(text[cursor - 1])) cursor -= 1; if (cursor === digits) return false; if (cursor > 0 && /[((]/u.test(text[cursor - 1])) cursor -= 1; else if (closed) return false; return cursor === 0 || /[\s。!?!?;;::,,、]/u.test(text[cursor - 1]); } // Whether text[0..end) finishes a sentence (ignoring closing quotes/space). function endsSentence(text, end) { let index = end - 1; while (index > 0 && /[”’"'」』))\t \r]/u.test(text[index])) index -= 1; return index >= 0 && boundary(text, index); } // Clause marks for natural cut points; ASCII , and : only outside numbers/times. function clause(text, index) {204 unmodified lines function tickSleep() { if (!checkSleep() && sleepDeadline) sleepTimer = setTimeout(tickSleep, Math.min(1000, sleepDeadline - Date.now())); } tickSleep(); } // "回到播放位置" <-> "回到原位置" (like a reader's "back to page N" after a jump): // after jumping, the button returns to where the reader was until the playing // sentence is no longer in view (the reader scrolled away / it moved on). let returnView = null, locateTimer = 0; function playingInView() { const value = owner || saved; if (!value || preview?.id !== value.snapshot.id) return false; if (value.snapshot.adapter) return preview.adapter === value.snapshot.adapter && !!value.snapshot.adapter.inView?.(value.position); const rect = sourceRange(Math.min(value.position, Math.max(0, preview.text.length - 1)))?.getBoundingClientRect(); const box = preview.body.getBoundingClientRect(); return !!rect?.height && rect.bottom > Math.max(0, box.top) && rect.top < Math.min(innerHeight, box.bottom); } function updateLocate() { if (returnView && performance.now() > returnView.grace && !playingInView()) returnView = null; const back = !!returnView; locate.textContent = back ? "回到原位置" : "回到播放位置"; locate.setAttribute("aria-label", back ? "回到跳转前的阅读位置" : "回到正在朗读的句子"); } function viewChanged() { clearTimeout(locateTimer); locateTimer = setTimeout(updateLocate, 120); } function saveView() { if (preview?.adapter) return preview.adapter.saveView?.() ?? null; return preview?.body ? { body: preview.body, top: preview.body.scrollTop, page: scrollY } : null; } function restoreView(view) { if (view?.body) { view.body.scrollTop = view.top; scrollTo({ top: view.page }); } else if (view !== null && view !== undefined) preview?.adapter?.restoreView?.(view); } async function toggleLocate() { if (returnView) { const view = returnView.view; returnView = null; restoreView(view); updateLocate(); return; } const view = saveView(); await locateSource(); if (view !== null && view !== undefined) returnView = { view, grace: performance.now() + 2500 }; updateLocate(); } document.addEventListener("scroll", viewChanged, { capture: true, passive: true }); function show() { const parent = preview?.host?.isConnected ? preview.host : preview?.body?.isConnected ? preview.body.parentElement : $("#preview-panel:not([hidden])") || document.body; if (panel.parentElement !== parent) parent.append(panel);14 unmodified lines next.disabled = !owner || (plan.sentence(owner.snapshot.text, owner.position).end >= owner.snapshot.text.length && !more(owner.snapshot)); visible.disabled = !preview; locate.disabled = !owner && !saved; updateLocate(); $("#speech-pitch-value").textContent = (Number(pitch.value) > 0 ? "+" : "") + pitch.value; $("#speech-speed-value").textContent = Number(speed.value).toFixed(2).replace(/0$/, "") + "×"; const button = $("[data-speech-toggle]");42 unmodified lines const realm = (range.startContainer.ownerDocument || document).defaultView || globalThis; if (realm.CSS?.highlights && realm.Highlight) { realm.CSS.highlights.set("ccrd-speech", new realm.Highlight(range)); markedRegistry = realm.CSS.highlights; } preview.adapter.follow?.(start, end); viewChanged(); return; } if (globalThis.CSS?.highlights && globalThis.Highlight) CSS.highlights.set("ccrd-speech", new Highlight(range));341 unmodified lines if (job.preloaded) advance(value); pump(value); // First POST directly; no iframe, voices or health round-trips. } function fromPreview(offset = visibleOffset()) { function fromPreview(offset) { // An adapter loads its text on demand; start() waits for it. if (!preview || (!preview.adapter && !preview.text.trim())) { if (typeof showToast === "function") showToast("请等待预览正文加载完成"); return; } if (offset === undefined && preview.adapter?.locateTop) { // Find (and load up to) the text at the reading position first, so a // paged document is not read from its first loaded unit. const token = ++starting; if (!owner) { notice("正在定位当前阅读位置…"); show(); } Promise.resolve(preview.adapter.locateTop()).catch(() => 0).then((found) => { if (token === starting && preview?.adapter) fromPreview(plan.safe(preview.text, Number(found) || 0)); }); return; } if (offset === undefined) offset = visibleOffset(); if (owner && owner.snapshot.id !== preview.id && !confirm("切换到当前预览会停止原朗读,继续吗?")) return; if (owner && sameSource(owner.snapshot, preview) && seek(owner, offset, true)) return; start(preview.adapter ? preview.snapshot : { id: preview.id, text: preview.text, title: preview.title }, offset);8 unmodified lines } function launch() { if (!owner) { if (saved?.snapshot.id === preview?.id) start(saved.snapshot, saved.position); // A host adapter resumes a stopped session only when it is the same // window; otherwise "听书" starts where the reader is looking now. if (saved?.snapshot.id === preview?.id && (!preview?.adapter || saved.snapshot.adapter === preview.adapter && !preview.adapter.locateTop)) start(saved.snapshot, saved.position); else fromPreview(); } else if (!panel.hidden) hide(); else { show(); if (!owner.wantsPlay && owner.snapshot.id === preview?.id) resume(); }85 unmodified lines previous.addEventListener("click", () => navigate(-1)); next.addEventListener("click", () => navigate(1)); visible.addEventListener("click", () => fromPreview()); locate.addEventListener("click", locateSource); locate.addEventListener("click", toggleLocate); collapse.addEventListener("click", hide); stopButton.addEventListener("click", () => { stop(); clearMark(); hide(); }); pitch.addEventListener("input", controls);17 unmodified lines // readFrom: a host adapter's double-click/selection starts at a source offset. return { launch, previewLoaded, previewPending, previewClosed, owns: node => !!node && panel.contains(node), modal: () => false, readFrom: offset => { if (preview) fromPreview(plan.sentence(preview.text, offset).start); }, // Host hooks: show the playing sentence (no "回到原位置" toggle) and report // scrolling the player cannot observe itself (e.g. inside an iframe). reveal: () => { returnView = null; return locateSource().then(updateLocate); }, viewChanged, state: () => ({ active: !!owner, playing: !!owner?.wantsPlay, adapter: owner?.snapshot.adapter || saved?.snapshot.adapter || null }), stop: () => { stop("已停止", true); clearMark(); hide(); } };})();53 unmodified lines545556575758596024 unmodified lines8586878888899091899091929394959697989910010110210310410510610710810911011111253 unmodified lines1661671681511691701711721731741751761771781791801818 unmodified lines19019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529 unmodified lines32532632732832933033133233333453 unmodified lines cls.playwright.stop() cls.server.__exit__(None, None, None)
def open(self, ext, body, content_type, viewport=None): def open(self, ext, body, content_type, viewport=None, host=False, name="sample"): context = self.browser.new_context(viewport=viewport or {"width": 1280, "height": 860}) page = context.new_page() posts, errors = [], []24 unmodified lines
page.route(SPEECH + "/**", speech) page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type=content_type, body=body)) reader = self.reader_url(ext, name) query = urllib.parse.quote(f"{SOURCE}.{ext}", safe="") page.goto(f"{self.origin}/static/reader.html?url={query}&ext={ext}&title=Speech", wait_until="domcontentloaded") wait(page, "() => document.documentElement.dataset.readerPhase === 'ready'", 30000) return context, page, posts, errors if not host: page.goto(reader, wait_until="domcontentloaded") wait(page, "() => document.documentElement.dataset.readerPhase === 'ready'", 30000) return context, page, posts, errors # A same-origin host page owning the Reader overlay through the shared navigation module. base = reader.split("reader.html")[0] page.goto(base + "search/reader-navigation.js", wait_until="domcontentloaded") # Inject as content: this host document has no charset, so a src= script would decode as Latin-1. 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)) }); window.__reader = __nav.mount(new URL(url)); }""", reader) frame = page.wait_for_selector("iframe.reader-overlay").content_frame() wait(frame, "() => document.documentElement.dataset.readerPhase === 'ready'", 30000) return context, page, posts, errors, frame
def reader_url(self, ext, name="sample"): query = urllib.parse.quote(f"{SOURCE.rsplit('/', 1)[0]}/{name}.{ext}", safe="") return f"{self.origin}/static/reader.html?url={query}&ext={ext}&title=Speech"
def play(self, page, posts): button = page.locator(".reader-actions [data-speech-toggle]")53 unmodified lines clip = page.locator("#speech-audio").evaluate("n => n.src") page.wait_for_timeout(900) self.assertEqual(viewport.evaluate("n => n.scrollTop"), away) page.locator("#speech-locate").click() locate = page.locator("#speech-locate") self.assertEqual(locate.inner_text(), "回到播放位置") locate.click() wait(page, f"() => document.querySelector('#viewport').scrollTop < {away - 2000}", 5000) # After jumping, the same button returns to where the reader was. wait(page, "() => document.querySelector('#speech-locate').textContent === '回到原位置'", 3000) locate.click() wait(page, f"() => document.querySelector('#viewport').scrollTop === {away}", 3000) wait(page, "() => document.querySelector('#speech-locate').textContent === '回到播放位置'", 3000) locate.click() wait(page, f"() => document.querySelector('#viewport').scrollTop < {away - 2000}", 5000) # The sentence being read is on screen, not merely its 32 KiB text block. self.assertTrue(page.evaluate("""() => { const range = [...CSS.highlights.get('ccrd-speech')][0], rect = range.getBoundingClientRect();8 unmodified lines finally: context.close()
def test_a_small_scroll_while_listening_is_never_undone(self): # The reader nudges the page while the sentence is still on screen; later # sentences must not pull it back (only 回到播放位置 resumes following). body = "".join(f"第{index}句。\n" for index in range(400)).encode() context, page, posts, errors = self.open("txt", body, "text/plain; charset=utf-8", viewport={"width": 1280, "height": 420}) try: self.play(page, posts) viewport = page.locator("#viewport") on_screen = """() => { const range = [...(CSS.highlights.get('ccrd-speech') || [])][0]; const box = document.querySelector('#viewport').getBoundingClientRect(), rect = range && range.getBoundingClientRect(); return !!rect && rect.top >= box.top && rect.bottom <= box.bottom; }""" clip = page.locator("#speech-audio").evaluate("n => n.src") for _ in range(4): # the playing sentence moves to the middle of the screen page.locator("#speech-next").click() wait(page, f"() => document.querySelector('#speech-audio').src !== {json.dumps(clip)}") clip = page.locator("#speech-audio").evaluate("n => n.src") box = viewport.bounding_box() page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) page.mouse.wheel(0, 40) page.wait_for_timeout(500) self.assertTrue(page.evaluate(on_screen)) # still visible after the nudge moved = viewport.evaluate("n => n.scrollTop") self.assertGreater(moved, 0) below = """() => { const range = [...(CSS.highlights.get('ccrd-speech') || [])][0]; const box = document.querySelector('#viewport').getBoundingClientRect(); return !!range && range.getBoundingClientRect().top > box.bottom; }""" passed = 0 for _ in range(40): # walk the sentence past the bottom of the viewport, then two more page.locator("#speech-next").click() wait(page, f"() => document.querySelector('#speech-audio').src !== {json.dumps(clip)}") clip = page.locator("#speech-audio").evaluate("n => n.src") page.wait_for_timeout(250) self.assertEqual(viewport.evaluate("n => n.scrollTop"), moved) passed += page.evaluate(below) if passed >= 2: break self.assertGreaterEqual(passed, 2) page.wait_for_timeout(900) self.assertEqual(viewport.evaluate("n => n.scrollTop"), moved) self.stop(page) self.assertFalse(errors, errors) finally: context.close()
def test_listening_starts_where_the_reader_is_looking(self): body = "".join(f"第{index}句。\n" for index in range(400)).encode() context, page, posts, errors = self.open("txt", body, "text/plain; charset=utf-8") try: page.locator("#viewport").evaluate("n => { n.scrollTop = 4000; }") page.wait_for_timeout(400) # The first line at the top of the viewport, measured independently. first = page.evaluate("""() => { const box = document.querySelector('#viewport').getBoundingClientRect(); const node = document.querySelector('.reader-text-block').firstChild, range = document.createRange(); for (let i = 0; i < node.length; i++) { range.setStart(node, i); range.setEnd(node, i + 1); const r = range.getClientRects()[0]; if (r && r.height && r.bottom > box.top + 4) return node.data.slice(i).match(/第(\\d+)句/)[1]; } }""") self.assertGreater(int(first), 50) job = self.play(page, posts) self.assertTrue(job["text"].lstrip().startswith(f"第{first}句") or job["text"].lstrip().startswith(f"{first}句"), (first, job["text"][:30])) self.stop(page) self.assertFalse(errors, errors) finally: context.close()
def test_closing_the_reader_keeps_reading_in_the_background(self): context, page, posts, errors, frame = self.open("txt", TEXT.encode(), "text/plain; charset=utf-8", host=True) try: self.play(frame, posts) page.evaluate("() => __nav.unmount()") bar = page.locator(".reader-speech-mini") bar.wait_for(timeout=3000) self.assertTrue(page.evaluate("() => __reader.isConnected && __nav.backgroundReader === __reader")) self.assertEqual(page.evaluate("getComputedStyle(__reader).visibility"), "hidden") before = frame.evaluate("() => [document.querySelector('#speech-audio').src, document.querySelector('#speech-audio').currentTime]") page.wait_for_timeout(1500) after = frame.evaluate("() => [document.querySelector('#speech-audio').src, document.querySelector('#speech-audio').currentTime]") self.assertNotEqual(before, after) # still reading while hidden # Pause / continue from the search page. bar.get_by_role("button", name="暂停").click() wait(frame, "() => document.querySelector('#speech-audio').paused", 5000) bar.get_by_role("button", name="继续").wait_for(timeout=3000) bar.get_by_role("button", name="继续").click() wait(frame, "() => !document.querySelector('#speech-audio').paused", 5000) # Back to the same Reader (not a reload), still reading. bar.get_by_role("button", name="返回阅读").click() 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. 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.assertEqual(page.locator(".reader-speech-mini").count(), 0) page.evaluate("() => __nav.unmount()") # A Reader that is not reading closes normally. self.assertTrue(page.evaluate("() => !__next.isConnected && !__nav.backgroundReader")) 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:29 unmodified lines payload.extend(f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode()) context, page, posts, errors = self.open("pdf", bytes(payload), "application/pdf") try: # No text near page 1: no button. It appears once the text page is in view. page.wait_for_timeout(2500) self.assertEqual(page.locator("[data-speech-toggle]").count(), 0) page.locator("#viewport").evaluate("n => { n.scrollTop = n.scrollHeight; }") job = self.play(page, posts) self.assertIn("Information Page Text", job["text"]) wait(page, "() => CSS.highlights.has('ccrd-speech')", 15000)static/app.js+4-1
static/reader/ui/reader-speech.mjs+137-21
static/search/reader-navigation.js+134-23
static/style.css+34
static/tts-client.js+82-5
tests/test_reader_speech.py+137-6