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.
- static/app.js +4 -1
- static/reader/ui/reader-speech.mjs +137 -21
- static/search/reader-navigation.js +134 -23
- static/style.css +34 -0
- static/tts-client.js +82 -5
- tests/test_reader_speech.py +137 -6
static/app.js
CHANGED
|
@@ -2443,7 +2443,10 @@ const READER_RETURN_SEARCH_KEYS = Object.freeze([
|
|
| 2443 |
let readerOverlay = null;
|
| 2444 |
let readerUiState = "base";
|
| 2445 |
let readerClosing = false;
|
| 2446 |
-
const readerNavigation = VoiceOfMLReaderNavigation.createNavigation("/static/reader.html"
|
|
|
|
|
|
|
|
|
|
| 2447 |
let readerReturnScrollState = null;
|
| 2448 |
let readerReturnSnapshot = null;
|
| 2449 |
let readerReturnRestoreGeneration = 0;
|
|
|
|
| 2443 |
let readerOverlay = null;
|
| 2444 |
let readerUiState = "base";
|
| 2445 |
let readerClosing = false;
|
| 2446 |
+
const readerNavigation = VoiceOfMLReaderNavigation.createNavigation("/static/reader.html", {
|
| 2447 |
+
// "返回阅读" on the background-reading bar reopens the kept Reader.
|
| 2448 |
+
resume: (url) => navigateToReader(url)
|
| 2449 |
+
});
|
| 2450 |
let readerReturnScrollState = null;
|
| 2451 |
let readerReturnSnapshot = null;
|
| 2452 |
let readerReturnRestoreGeneration = 0;
|
static/reader/ui/reader-speech.mjs
CHANGED
|
@@ -196,6 +196,20 @@ export function createReaderSpeech(readerContext) {
|
|
| 196 |
});
|
| 197 |
return chain;
|
| 198 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
partAt(offset) {
|
| 200 |
let low = 0, high = parts.length - 1;
|
| 201 |
while (low <= high) {
|
|
@@ -235,7 +249,8 @@ export function createReaderSpeech(readerContext) {
|
|
| 235 |
const part = self.partAt(start);
|
| 236 |
if (!part) return;
|
| 237 |
self.current = start;
|
| 238 |
-
|
|
|
|
| 239 |
const range = self.range(start, start + 1);
|
| 240 |
if (!range) {
|
| 241 |
// An unrendered page/section: navigate there and wait for its text.
|
|
@@ -261,10 +276,23 @@ export function createReaderSpeech(readerContext) {
|
|
| 261 |
const top = rect.top + shift, bottom = rect.bottom + shift;
|
| 262 |
return { inside: top >= box.top && bottom <= box.bottom - 24, overlaps: bottom > box.top && top < box.bottom };
|
| 263 |
},
|
| 264 |
-
//
|
|
|
|
|
|
|
| 265 |
userScrolled() {
|
| 266 |
-
if (
|
| 267 |
-
self.following =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
},
|
| 269 |
async reveal(offset) {
|
| 270 |
const part = self.partAt(offset);
|
|
@@ -322,20 +350,47 @@ export function createReaderSpeech(readerContext) {
|
|
| 322 |
}
|
| 323 |
const root = info.root(unit);
|
| 324 |
if (!root) return { unit, offset: 0 };
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
const
|
| 329 |
-
const
|
| 330 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
let total = 0;
|
| 332 |
for (const node of textNodes(root)) {
|
| 333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
total += node.length;
|
| 335 |
}
|
| 336 |
return { unit, offset: 0 };
|
| 337 |
}
|
| 338 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
// ---- Publication to the shared player --------------------------------------
|
| 340 |
function publish(next) {
|
| 341 |
adapter = next;
|
|
@@ -354,6 +409,7 @@ export function createReaderSpeech(readerContext) {
|
|
| 354 |
}
|
| 355 |
|
| 356 |
function syncToView() {
|
|
|
|
| 357 |
if (!adapter || adapter.source.units <= 1) return;
|
| 358 |
const state = speech()?.state?.();
|
| 359 |
if (state?.active) return; // Never re-base under active playback.
|
|
@@ -377,6 +433,7 @@ export function createReaderSpeech(readerContext) {
|
|
| 377 |
global = next.offsetFromNode(node, offset);
|
| 378 |
if (global === null || global === undefined) return;
|
| 379 |
}
|
|
|
|
| 380 |
speech()?.readFrom(global);
|
| 381 |
}
|
| 382 |
|
|
@@ -390,7 +447,56 @@ export function createReaderSpeech(readerContext) {
|
|
| 390 |
}
|
| 391 |
|
| 392 |
// ---- Lifecycle ---------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
function detach() {
|
|
|
|
|
|
|
| 394 |
for (const off of cleanup.splice(0)) off();
|
| 395 |
adapter = null;
|
| 396 |
speech()?.previewClosed();
|
|
@@ -402,10 +508,11 @@ export function createReaderSpeech(readerContext) {
|
|
| 402 |
if (!player) return;
|
| 403 |
document.querySelector("[data-speech-toggle]")?.remove();
|
| 404 |
if (!hasText()) return;
|
| 405 |
-
const
|
| 406 |
-
if (!
|
| 407 |
-
const
|
| 408 |
-
|
|
|
|
| 409 |
const listen = (target, type, handler, options) => {
|
| 410 |
if (!target) return;
|
| 411 |
target.addEventListener(type, handler, options);
|
|
@@ -416,14 +523,23 @@ export function createReaderSpeech(readerContext) {
|
|
| 416 |
let timer = 0, settle = 0;
|
| 417 |
const onScroll = () => {
|
| 418 |
clearTimeout(timer); timer = setTimeout(syncToView, 250);
|
| 419 |
-
clearTimeout(settle); settle = setTimeout(() =>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 420 |
};
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
listen(target, "scroll", onScroll, { passive: true, capture: true });
|
| 425 |
-
for (const type of ["wheel", "touchstart", "keydown"]) listen(target, type, onIntent, { passive: true, capture: true });
|
| 426 |
}
|
|
|
|
| 427 |
if (info.frame?.contentWindow) listen(info.frame.contentWindow, "scroll", onScroll, { passive: true });
|
| 428 |
cleanup.push(() => { clearTimeout(timer); clearTimeout(settle); });
|
| 429 |
ensureStyle(document);
|
|
|
|
| 196 |
});
|
| 197 |
return chain;
|
| 198 |
},
|
| 199 |
+
// Load through `unit` (the unit the reader is looking at).
|
| 200 |
+
ensureUnit(unit) {
|
| 201 |
+
chain = chain.then(async () => {
|
| 202 |
+
for (let guard = 0; !done && next <= unit && guard < 400; guard++) await loadNext();
|
| 203 |
+
});
|
| 204 |
+
return chain;
|
| 205 |
+
},
|
| 206 |
+
// Offset of a unit-local position; past an empty unit, the next text.
|
| 207 |
+
offsetOf(position) {
|
| 208 |
+
const part = parts.find((item) => item.unit === position.unit);
|
| 209 |
+
if (part) return part.start + Math.min(position.offset, part.raw.length);
|
| 210 |
+
return parts.find((item) => item.unit > position.unit)?.start ?? text.length;
|
| 211 |
+
},
|
| 212 |
+
locateTop: () => locateTop(),
|
| 213 |
partAt(offset) {
|
| 214 |
let low = 0, high = parts.length - 1;
|
| 215 |
while (low <= high) {
|
|
|
|
| 249 |
const part = self.partAt(start);
|
| 250 |
if (!part) return;
|
| 251 |
self.current = start;
|
| 252 |
+
// Parked in the background (Reader closed while reading): no layout to follow.
|
| 253 |
+
if (!self.following || !readerContext.viewport.getClientRects().length) return;
|
| 254 |
const range = self.range(start, start + 1);
|
| 255 |
if (!range) {
|
| 256 |
// An unrendered page/section: navigate there and wait for its text.
|
|
|
|
| 276 |
const top = rect.top + shift, bottom = rect.bottom + shift;
|
| 277 |
return { inside: top >= box.top && bottom <= box.bottom - 24, overlaps: bottom > box.top && top < box.bottom };
|
| 278 |
},
|
| 279 |
+
// Any scroll the reader starts (wheel, touch, scroll keys, scrollbar,
|
| 280 |
+
// TOC/progress navigation) stops following; only "回到播放位置" or a new
|
| 281 |
+
// start resumes it (Readwise Reader / Spotify "Sync" model, no timeout).
|
| 282 |
userScrolled() {
|
| 283 |
+
if (performance.now() < self.autoUntil) return;
|
| 284 |
+
self.following = false;
|
| 285 |
+
},
|
| 286 |
+
inView(offset) { return !!self.visible(offset)?.overlaps; },
|
| 287 |
+
saveView() {
|
| 288 |
+
const win = sourceInfo.frame?.contentWindow;
|
| 289 |
+
return { top: readerContext.viewport.scrollTop, frame: win ? win.scrollY : null };
|
| 290 |
+
},
|
| 291 |
+
restoreView(view) {
|
| 292 |
+
self.following = false;
|
| 293 |
+
self.autoUntil = performance.now() + 600;
|
| 294 |
+
readerContext.viewport.scrollTop = view.top;
|
| 295 |
+
if (view.frame !== null) sourceInfo.frame?.contentWindow?.scrollTo(0, view.frame);
|
| 296 |
},
|
| 297 |
async reveal(offset) {
|
| 298 |
const part = self.partAt(offset);
|
|
|
|
| 350 |
}
|
| 351 |
const root = info.root(unit);
|
| 352 |
if (!root) return { unit, offset: 0 };
|
| 353 |
+
// First character whose line reaches below the viewport top. Rendered
|
| 354 |
+
// characters are in reading order, so a binary search over each text node
|
| 355 |
+
// is exact even for one 32 KiB TXT text node (no hit-testing guesswork).
|
| 356 |
+
const shift = info.frame ? info.frame.getBoundingClientRect().top : 0;
|
| 357 |
+
const limit = box.top + 4 - shift;
|
| 358 |
+
const doc = root.ownerDocument || document, range = doc.createRange();
|
| 359 |
+
const bottom = (node, index) => {
|
| 360 |
+
range.setStart(node, index); range.setEnd(node, Math.min(node.length, index + 1));
|
| 361 |
+
const rect = [...range.getClientRects()].find((item) => item.height) || range.getBoundingClientRect();
|
| 362 |
+
return rect.height ? rect.bottom : null;
|
| 363 |
+
};
|
| 364 |
let total = 0;
|
| 365 |
for (const node of textNodes(root)) {
|
| 366 |
+
const last = bottom(node, Math.max(0, node.length - 1));
|
| 367 |
+
if (last !== null && last > limit) {
|
| 368 |
+
let low = 0, high = node.length - 1;
|
| 369 |
+
while (low < high) {
|
| 370 |
+
const middle = (low + high) >> 1, value = bottom(node, middle);
|
| 371 |
+
if (value !== null && value > limit) high = middle; else low = middle + 1;
|
| 372 |
+
}
|
| 373 |
+
return { unit, offset: total + low };
|
| 374 |
+
}
|
| 375 |
total += node.length;
|
| 376 |
}
|
| 377 |
return { unit, offset: 0 };
|
| 378 |
}
|
| 379 |
|
| 380 |
+
// Exact start for "听书"/"从当前阅读位置开始": the window is re-based to the
|
| 381 |
+
// unit in view when it is not loaded (or would need many earlier units).
|
| 382 |
+
async function locateTop() {
|
| 383 |
+
const position = topPosition();
|
| 384 |
+
if (!adapter || !position) return 0;
|
| 385 |
+
let target = adapter;
|
| 386 |
+
if (target.source.units > 1 && (position.unit < target.base || !target.covers(position.unit) && position.unit - target.base > 2)) {
|
| 387 |
+
target = rebase(position.unit);
|
| 388 |
+
}
|
| 389 |
+
await target.ensureUnit(position.unit);
|
| 390 |
+
target.following = true; // Reading starts where the reader looks: follow it.
|
| 391 |
+
return target.offsetOf(position);
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
// ---- Publication to the shared player --------------------------------------
|
| 395 |
function publish(next) {
|
| 396 |
adapter = next;
|
|
|
|
| 409 |
}
|
| 410 |
|
| 411 |
function syncToView() {
|
| 412 |
+
if (!adapter && offerSource) { offer(offerSource); return; }
|
| 413 |
if (!adapter || adapter.source.units <= 1) return;
|
| 414 |
const state = speech()?.state?.();
|
| 415 |
if (state?.active) return; // Never re-base under active playback.
|
|
|
|
| 433 |
global = next.offsetFromNode(node, offset);
|
| 434 |
if (global === null || global === undefined) return;
|
| 435 |
}
|
| 436 |
+
if (adapter) adapter.following = true;
|
| 437 |
speech()?.readFrom(global);
|
| 438 |
}
|
| 439 |
|
|
|
|
| 447 |
}
|
| 448 |
|
| 449 |
// ---- Lifecycle ---------------------------------------------------------------
|
| 450 |
+
// Formats whose text may be absent (scanned PDF, comic books, empty files)
|
| 451 |
+
// only get the button once text is found at/near the reading position.
|
| 452 |
+
const probeText = new Map(), probeSeen = new Map();
|
| 453 |
+
let generation = 0, probing = null, offerSource = null;
|
| 454 |
+
|
| 455 |
+
function withProbeCache(info) {
|
| 456 |
+
const load = info.load;
|
| 457 |
+
return { ...info, load: (unit) => {
|
| 458 |
+
const hit = probeText.get(unit);
|
| 459 |
+
if (hit) { probeText.delete(unit); return hit; }
|
| 460 |
+
return load(unit);
|
| 461 |
+
} };
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
function needsProbe(info) {
|
| 465 |
+
const current = mode();
|
| 466 |
+
if (current === "epub-chapters") return false;
|
| 467 |
+
if (current === "pdf-pages" && (readerContext.ocrManifestUrl || readerContext.pdfOcrManifest)) return false;
|
| 468 |
+
return true;
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
async function probe(info, owner) {
|
| 472 |
+
const from = info.units > 1 ? (topPosition()?.unit ?? info.first) : info.first;
|
| 473 |
+
for (let unit = Math.max(info.first, from - 1); unit < Math.min(info.units, from + 12); unit++) {
|
| 474 |
+
if (!probeSeen.has(unit)) {
|
| 475 |
+
const text = Promise.resolve(info.load(unit)).then((value) => String(value || ""), () => "");
|
| 476 |
+
probeText.set(unit, text);
|
| 477 |
+
probeSeen.set(unit, text.then((value) => !!value.trim()));
|
| 478 |
+
}
|
| 479 |
+
const found = await probeSeen.get(unit);
|
| 480 |
+
if (owner !== generation) return null;
|
| 481 |
+
if (found) return from;
|
| 482 |
+
}
|
| 483 |
+
return null;
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
function offer(info) {
|
| 487 |
+
if (adapter || probing) return;
|
| 488 |
+
const owner = generation;
|
| 489 |
+
probing = probe(info, owner).then((from) => {
|
| 490 |
+
if (owner !== generation) return;
|
| 491 |
+
probing = null;
|
| 492 |
+
if (from === null || adapter) return;
|
| 493 |
+
publish(createAdapter(info, info.units > 1 ? Math.max(info.first, from - 1) : info.first));
|
| 494 |
+
}, () => { if (owner === generation) probing = null; });
|
| 495 |
+
}
|
| 496 |
+
|
| 497 |
function detach() {
|
| 498 |
+
generation++;
|
| 499 |
+
probing = null; offerSource = null; probeText.clear(); probeSeen.clear();
|
| 500 |
for (const off of cleanup.splice(0)) off();
|
| 501 |
adapter = null;
|
| 502 |
speech()?.previewClosed();
|
|
|
|
| 508 |
if (!player) return;
|
| 509 |
document.querySelector("[data-speech-toggle]")?.remove();
|
| 510 |
if (!hasText()) return;
|
| 511 |
+
const raw = source();
|
| 512 |
+
if (!raw || raw.units <= raw.first) return;
|
| 513 |
+
const info = withProbeCache(raw);
|
| 514 |
+
if (needsProbe(info)) { offerSource = info; offer(info); }
|
| 515 |
+
else publish(createAdapter(info, info.units > 1 ? Math.max(info.first, (topPosition()?.unit ?? info.first) - 1) : info.first));
|
| 516 |
const listen = (target, type, handler, options) => {
|
| 517 |
if (!target) return;
|
| 518 |
target.addEventListener(type, handler, options);
|
|
|
|
| 523 |
let timer = 0, settle = 0;
|
| 524 |
const onScroll = () => {
|
| 525 |
clearTimeout(timer); timer = setTimeout(syncToView, 250);
|
| 526 |
+
clearTimeout(settle); settle = setTimeout(() => speech()?.viewChanged?.(), 150);
|
| 527 |
+
};
|
| 528 |
+
// Reader-initiated movement stops auto-follow at once, including during one
|
| 529 |
+
// of our own smooth scrolls. Scroll events alone (layout shifts, lazy pages,
|
| 530 |
+
// our own follow) never do. The player panel's buttons are excluded.
|
| 531 |
+
const keys = new Set(["PageUp", "PageDown", "Home", "End", "ArrowUp", "ArrowDown", " ", "Spacebar"]);
|
| 532 |
+
const onIntent = (event) => {
|
| 533 |
+
if (!adapter || event.target?.closest?.("#speech-panel, .reader-actions")) return;
|
| 534 |
+
if (event.type === "keydown" && !keys.has(event.key)) return;
|
| 535 |
+
adapter.autoUntil = 0;
|
| 536 |
+
adapter.userScrolled();
|
| 537 |
};
|
| 538 |
+
const intentTargets = [document, info.frame?.contentDocument];
|
| 539 |
+
for (const target of intentTargets) {
|
| 540 |
+
for (const type of ["wheel", "touchmove", "keydown", "pointerdown"]) listen(target, type, onIntent, { passive: true, capture: true });
|
|
|
|
|
|
|
| 541 |
}
|
| 542 |
+
listen(readerContext.viewport, "scroll", onScroll, { passive: true, capture: true });
|
| 543 |
if (info.frame?.contentWindow) listen(info.frame.contentWindow, "scroll", onScroll, { passive: true });
|
| 544 |
cleanup.push(() => { clearTimeout(timer); clearTimeout(settle); });
|
| 545 |
ensureStyle(document);
|
static/search/reader-navigation.js
CHANGED
|
@@ -1,12 +1,104 @@
|
|
| 1 |
(function (root) {
|
| 2 |
"use strict";
|
| 3 |
-
function createNavigation(readerPath) {
|
| 4 |
let frame = null;
|
| 5 |
let returnFocus = null;
|
| 6 |
let background = [];
|
| 7 |
let opening = null;
|
| 8 |
let releaseOpening = null;
|
|
|
|
|
|
|
|
|
|
| 9 |
const sessionKey = "reader-navigation-current";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
function parse(raw) {
|
| 11 |
const url = new URL(raw, location.origin);
|
| 12 |
if (url.origin !== location.origin || url.pathname !== readerPath)
|
|
@@ -77,7 +169,38 @@
|
|
| 77 |
share.href
|
| 78 |
);
|
| 79 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
function mount(url) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
const next = document.createElement("iframe");
|
| 82 |
next.className = "reader-overlay";
|
| 83 |
next.title = "在线阅读";
|
|
@@ -110,21 +233,9 @@
|
|
| 110 |
};
|
| 111 |
window.addEventListener("message", onShell);
|
| 112 |
releaseOpening = () => { window.removeEventListener("message", onShell); releaseOpening = null; };
|
| 113 |
-
document.body.classList.add("reader-overlay-open");
|
| 114 |
document.body.append(next, opening);
|
| 115 |
back.focus();
|
| 116 |
-
|
| 117 |
-
.filter((element) => element !== next && element !== opening)
|
| 118 |
-
.map((element) => {
|
| 119 |
-
const state = {
|
| 120 |
-
element,
|
| 121 |
-
inert: element.hasAttribute("inert"),
|
| 122 |
-
ariaHidden: element.getAttribute("aria-hidden")
|
| 123 |
-
};
|
| 124 |
-
element.setAttribute("inert", "");
|
| 125 |
-
element.setAttribute("aria-hidden", "true");
|
| 126 |
-
return state;
|
| 127 |
-
});
|
| 128 |
next.addEventListener(
|
| 129 |
"load",
|
| 130 |
() => {
|
|
@@ -134,15 +245,11 @@
|
|
| 134 |
);
|
| 135 |
return next;
|
| 136 |
}
|
| 137 |
-
|
|
|
|
| 138 |
if (!frame) return null;
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
frame.contentWindow?.dispatchEvent(new Event("voice-reader-dispose"));
|
| 142 |
-
frame.contentWindow?.postMessage({ type: "voice-reader-abort" }, location.origin);
|
| 143 |
-
} catch (_) {}
|
| 144 |
-
frame.src = "about:blank";
|
| 145 |
-
frame.remove();
|
| 146 |
frame = null;
|
| 147 |
opening?.remove();
|
| 148 |
opening = null;
|
|
@@ -165,7 +272,7 @@
|
|
| 165 |
if (!next.searchParams.get(key) && current.searchParams.get(key))
|
| 166 |
next.searchParams.set(key, current.searchParams.get(key));
|
| 167 |
remember(next, returnScroll, true);
|
| 168 |
-
const focus = unmount();
|
| 169 |
mount(next);
|
| 170 |
returnFocus = focus;
|
| 171 |
return frame;
|
|
@@ -190,6 +297,10 @@
|
|
| 190 |
unmount,
|
| 191 |
replace,
|
| 192 |
accepts,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
get returnFocus() {
|
| 194 |
return returnFocus;
|
| 195 |
}
|
|
|
|
| 1 |
(function (root) {
|
| 2 |
"use strict";
|
| 3 |
+
function createNavigation(readerPath, options = {}) {
|
| 4 |
let frame = null;
|
| 5 |
let returnFocus = null;
|
| 6 |
let background = [];
|
| 7 |
let opening = null;
|
| 8 |
let releaseOpening = null;
|
| 9 |
+
// A Reader closed while reading aloud stays alive, hidden, with a small
|
| 10 |
+
// player on the search page; reopening the same book reuses it.
|
| 11 |
+
let parked = null;
|
| 12 |
const sessionKey = "reader-navigation-current";
|
| 13 |
+
function bookKey(raw) {
|
| 14 |
+
try {
|
| 15 |
+
const params = new URL(raw, location.origin).searchParams;
|
| 16 |
+
return params.get("id") ? "id:" + params.get("id") : "url:" + params.get("url") + "|" + params.get("ext");
|
| 17 |
+
} catch (_) {
|
| 18 |
+
return "";
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
function speech(target) {
|
| 22 |
+
try {
|
| 23 |
+
return target?.contentWindow?.CCRDSpeech?.state?.() || null;
|
| 24 |
+
} catch (_) {
|
| 25 |
+
return null;
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
function dispose(target) {
|
| 29 |
+
try {
|
| 30 |
+
// Run lifecycle cleanup before detaching the browsing context.
|
| 31 |
+
target.contentWindow?.dispatchEvent(new Event("voice-reader-dispose"));
|
| 32 |
+
target.contentWindow?.postMessage({ type: "voice-reader-abort" }, location.origin);
|
| 33 |
+
} catch (_) {}
|
| 34 |
+
target.src = "about:blank";
|
| 35 |
+
target.remove();
|
| 36 |
+
}
|
| 37 |
+
function releaseParked() {
|
| 38 |
+
if (!parked) return null;
|
| 39 |
+
const current = parked;
|
| 40 |
+
parked = null;
|
| 41 |
+
clearInterval(current.timer);
|
| 42 |
+
current.bar.remove();
|
| 43 |
+
return current;
|
| 44 |
+
}
|
| 45 |
+
function disposeParked() {
|
| 46 |
+
const current = releaseParked();
|
| 47 |
+
if (current) dispose(current.frame);
|
| 48 |
+
}
|
| 49 |
+
function inFrame(target, selector) {
|
| 50 |
+
try {
|
| 51 |
+
return target.contentDocument?.querySelector(selector) || null;
|
| 52 |
+
} catch (_) {
|
| 53 |
+
return null;
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
function park(target, focus) {
|
| 57 |
+
disposeParked();
|
| 58 |
+
target.classList.add("reader-overlay-parked");
|
| 59 |
+
target.setAttribute("inert", "");
|
| 60 |
+
target.setAttribute("aria-hidden", "true");
|
| 61 |
+
const bar = document.createElement("div");
|
| 62 |
+
bar.className = "reader-speech-mini";
|
| 63 |
+
bar.setAttribute("role", "region");
|
| 64 |
+
bar.setAttribute("aria-label", "后台朗读");
|
| 65 |
+
const label = document.createElement("span");
|
| 66 |
+
label.className = "reader-speech-mini-title";
|
| 67 |
+
const button = (text, action) => {
|
| 68 |
+
const element = document.createElement("button");
|
| 69 |
+
element.type = "button";
|
| 70 |
+
element.textContent = text;
|
| 71 |
+
element.addEventListener("click", action);
|
| 72 |
+
return element;
|
| 73 |
+
};
|
| 74 |
+
const back = button("返回阅读", () => {
|
| 75 |
+
const url = target.src;
|
| 76 |
+
if (typeof options.resume === "function") options.resume(url);
|
| 77 |
+
else root.dispatchEvent(new CustomEvent("voice-reader-resume", { detail: url }));
|
| 78 |
+
});
|
| 79 |
+
back.className = "reader-speech-mini-back";
|
| 80 |
+
const play = button("暂停", () => inFrame(target, "#speech-play")?.click());
|
| 81 |
+
const stop = button("停止", () => {
|
| 82 |
+
inFrame(target, "#speech-stop")?.click();
|
| 83 |
+
disposeParked();
|
| 84 |
+
});
|
| 85 |
+
stop.setAttribute("aria-label", "停止朗读并关闭阅读器");
|
| 86 |
+
bar.append(label, back, play, stop);
|
| 87 |
+
const sync = () => {
|
| 88 |
+
const state = speech(target);
|
| 89 |
+
if (!state?.active) {
|
| 90 |
+
if (parked?.frame === target) disposeParked();
|
| 91 |
+
return;
|
| 92 |
+
}
|
| 93 |
+
const title = inFrame(target, "#speech-title")?.textContent?.trim() || "朗读";
|
| 94 |
+
const status = inFrame(target, "#speech-status")?.textContent?.trim() || "";
|
| 95 |
+
label.textContent = status ? `${title} · ${status}` : title;
|
| 96 |
+
play.textContent = inFrame(target, "#speech-play")?.textContent?.trim() || (state.playing ? "暂停" : "继续");
|
| 97 |
+
};
|
| 98 |
+
document.body.append(bar);
|
| 99 |
+
parked = { frame: target, bar, focus, key: bookKey(target.src), timer: setInterval(sync, 1000) };
|
| 100 |
+
sync();
|
| 101 |
+
}
|
| 102 |
function parse(raw) {
|
| 103 |
const url = new URL(raw, location.origin);
|
| 104 |
if (url.origin !== location.origin || url.pathname !== readerPath)
|
|
|
|
| 169 |
share.href
|
| 170 |
);
|
| 171 |
}
|
| 172 |
+
function shade(current) {
|
| 173 |
+
document.body.classList.add("reader-overlay-open");
|
| 174 |
+
background = Array.from(document.body.children)
|
| 175 |
+
.filter((element) => element !== current && element !== opening)
|
| 176 |
+
.map((element) => {
|
| 177 |
+
const state = {
|
| 178 |
+
element,
|
| 179 |
+
inert: element.hasAttribute("inert"),
|
| 180 |
+
ariaHidden: element.getAttribute("aria-hidden")
|
| 181 |
+
};
|
| 182 |
+
element.setAttribute("inert", "");
|
| 183 |
+
element.setAttribute("aria-hidden", "true");
|
| 184 |
+
return state;
|
| 185 |
+
});
|
| 186 |
+
}
|
| 187 |
function mount(url) {
|
| 188 |
+
const key = bookKey(url.href);
|
| 189 |
+
if (parked && key && parked.key === key) {
|
| 190 |
+
// The same book: show the Reader that kept reading, at its reading position.
|
| 191 |
+
const { frame: kept } = releaseParked();
|
| 192 |
+
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
| 193 |
+
frame = kept;
|
| 194 |
+
kept.classList.remove("reader-overlay-parked");
|
| 195 |
+
kept.removeAttribute("inert");
|
| 196 |
+
kept.removeAttribute("aria-hidden");
|
| 197 |
+
shade(kept);
|
| 198 |
+
kept.focus();
|
| 199 |
+
// Show the sentence being read (not the "回到原位置" toggle of the panel button).
|
| 200 |
+
try { kept.contentWindow.CCRDSpeech?.reveal?.(); } catch (_) {}
|
| 201 |
+
return kept;
|
| 202 |
+
}
|
| 203 |
+
disposeParked();
|
| 204 |
const next = document.createElement("iframe");
|
| 205 |
next.className = "reader-overlay";
|
| 206 |
next.title = "在线阅读";
|
|
|
|
| 233 |
};
|
| 234 |
window.addEventListener("message", onShell);
|
| 235 |
releaseOpening = () => { window.removeEventListener("message", onShell); releaseOpening = null; };
|
|
|
|
| 236 |
document.body.append(next, opening);
|
| 237 |
back.focus();
|
| 238 |
+
shade(next);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
next.addEventListener(
|
| 240 |
"load",
|
| 241 |
() => {
|
|
|
|
| 245 |
);
|
| 246 |
return next;
|
| 247 |
}
|
| 248 |
+
// `keepSpeech` parks a Reader that is reading aloud instead of disposing it.
|
| 249 |
+
function unmount(keepSpeech = true) {
|
| 250 |
if (!frame) return null;
|
| 251 |
+
if (keepSpeech && opening === null && speech(frame)?.active) park(frame);
|
| 252 |
+
else dispose(frame);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
frame = null;
|
| 254 |
opening?.remove();
|
| 255 |
opening = null;
|
|
|
|
| 272 |
if (!next.searchParams.get(key) && current.searchParams.get(key))
|
| 273 |
next.searchParams.set(key, current.searchParams.get(key));
|
| 274 |
remember(next, returnScroll, true);
|
| 275 |
+
const focus = unmount(false);
|
| 276 |
mount(next);
|
| 277 |
returnFocus = focus;
|
| 278 |
return frame;
|
|
|
|
| 297 |
unmount,
|
| 298 |
replace,
|
| 299 |
accepts,
|
| 300 |
+
disposeBackground: disposeParked,
|
| 301 |
+
get backgroundReader() {
|
| 302 |
+
return parked?.frame || null;
|
| 303 |
+
},
|
| 304 |
get returnFocus() {
|
| 305 |
return returnFocus;
|
| 306 |
}
|
static/style.css
CHANGED
|
@@ -1992,3 +1992,37 @@ body.multiselect .result-file-icon { display: none; }
|
|
| 1992 |
.result-item.selected {
|
| 1993 |
background: color-mix(in srgb, var(--primary) 15%, transparent) !important;
|
| 1994 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1992 |
.result-item.selected {
|
| 1993 |
background: color-mix(in srgb, var(--primary) 15%, transparent) !important;
|
| 1994 |
}
|
| 1995 |
+
|
| 1996 |
+
/* A Reader closed while reading aloud stays alive here, hidden. */
|
| 1997 |
+
.reader-overlay-parked { visibility: hidden; pointer-events: none; }
|
| 1998 |
+
.reader-speech-mini {
|
| 1999 |
+
position: fixed;
|
| 2000 |
+
left: 50%;
|
| 2001 |
+
bottom: max(12px, env(safe-area-inset-bottom));
|
| 2002 |
+
transform: translateX(-50%);
|
| 2003 |
+
z-index: 9000;
|
| 2004 |
+
display: flex;
|
| 2005 |
+
align-items: center;
|
| 2006 |
+
gap: 6px;
|
| 2007 |
+
width: min(560px, calc(100vw - 24px));
|
| 2008 |
+
padding: 6px 8px 6px 14px;
|
| 2009 |
+
border-radius: 24px;
|
| 2010 |
+
background: var(--primary-container);
|
| 2011 |
+
color: var(--on-primary-container);
|
| 2012 |
+
box-shadow: 0 6px 20px rgba(0, 0, 0, .28);
|
| 2013 |
+
font-size: 13px;
|
| 2014 |
+
}
|
| 2015 |
+
.reader-speech-mini-title { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
| 2016 |
+
.reader-speech-mini button {
|
| 2017 |
+
flex: 0 0 auto;
|
| 2018 |
+
min-height: 32px;
|
| 2019 |
+
padding: 0 12px;
|
| 2020 |
+
border: 0;
|
| 2021 |
+
border-radius: 16px;
|
| 2022 |
+
background: transparent;
|
| 2023 |
+
color: inherit;
|
| 2024 |
+
font: inherit;
|
| 2025 |
+
cursor: pointer;
|
| 2026 |
+
}
|
| 2027 |
+
.reader-speech-mini .reader-speech-mini-back { background: var(--primary); color: var(--on-primary); }
|
| 2028 |
+
.reader-speech-mini button:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
|
static/tts-client.js
CHANGED
|
@@ -44,7 +44,7 @@ globalThis.CCRDSpeechPlan = (() => {
|
|
| 44 |
// The fast first clip may extend to the first punctuation within 32
|
| 45 |
// characters instead of being cut mid-clause at about 16.
|
| 46 |
const ceiling = offsets[Math.min(chars.length, position + (short ? 32 : 120))];
|
| 47 |
-
const hard = cuts.find(value => value.end > start && value.end <= ceiling &&
|
| 48 |
const natural = cuts.filter(value => value.end > start + (short ? 4 : 20) && value.end <= ceiling &&
|
| 49 |
/[,,::、—…][”’"'」』))\t \r]*$/u.test(text.slice(start, value.end)) && !connectorOnly(text.slice(start, value.end).trim()));
|
| 50 |
let end;
|
|
@@ -88,7 +88,26 @@ globalThis.CCRDSpeechPlan = (() => {
|
|
| 88 |
return offset && /[\uDC00-\uDFFF]/u.test(text[offset] || "") && /[\uD800-\uDBFF]/u.test(text[offset - 1]) ? offset - 1 : offset;
|
| 89 |
}
|
| 90 |
function boundary(text, index) {
|
| 91 |
-
return ending.test(text[index]) || (text[index] === "." && !ascii.test(text[index + 1] || ""));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
}
|
| 93 |
// Clause marks for natural cut points; ASCII , and : only outside numbers/times.
|
| 94 |
function clause(text, index) {
|
|
@@ -299,6 +318,45 @@ if (typeof document !== "undefined") window.CCRDSpeech = (() => {
|
|
| 299 |
function tickSleep() { if (!checkSleep() && sleepDeadline) sleepTimer = setTimeout(tickSleep, Math.min(1000, sleepDeadline - Date.now())); }
|
| 300 |
tickSleep();
|
| 301 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
function show() {
|
| 303 |
const parent = preview?.host?.isConnected ? preview.host : preview?.body?.isConnected ? preview.body.parentElement : $("#preview-panel:not([hidden])") || document.body;
|
| 304 |
if (panel.parentElement !== parent) parent.append(panel);
|
|
@@ -319,6 +377,7 @@ if (typeof document !== "undefined") window.CCRDSpeech = (() => {
|
|
| 319 |
next.disabled = !owner || (plan.sentence(owner.snapshot.text, owner.position).end >= owner.snapshot.text.length && !more(owner.snapshot));
|
| 320 |
visible.disabled = !preview;
|
| 321 |
locate.disabled = !owner && !saved;
|
|
|
|
| 322 |
$("#speech-pitch-value").textContent = (Number(pitch.value) > 0 ? "+" : "") + pitch.value;
|
| 323 |
$("#speech-speed-value").textContent = Number(speed.value).toFixed(2).replace(/0$/, "") + "×";
|
| 324 |
const button = $("[data-speech-toggle]");
|
|
@@ -367,6 +426,7 @@ if (typeof document !== "undefined") window.CCRDSpeech = (() => {
|
|
| 367 |
const realm = (range.startContainer.ownerDocument || document).defaultView || globalThis;
|
| 368 |
if (realm.CSS?.highlights && realm.Highlight) { realm.CSS.highlights.set("ccrd-speech", new realm.Highlight(range)); markedRegistry = realm.CSS.highlights; }
|
| 369 |
preview.adapter.follow?.(start, end);
|
|
|
|
| 370 |
return;
|
| 371 |
}
|
| 372 |
if (globalThis.CSS?.highlights && globalThis.Highlight) CSS.highlights.set("ccrd-speech", new Highlight(range));
|
|
@@ -714,9 +774,20 @@ if (typeof document !== "undefined") window.CCRDSpeech = (() => {
|
|
| 714 |
if (job.preloaded) advance(value);
|
| 715 |
pump(value); // First POST directly; no iframe, voices or health round-trips.
|
| 716 |
}
|
| 717 |
-
function fromPreview(offset
|
| 718 |
// An adapter loads its text on demand; start() waits for it.
|
| 719 |
if (!preview || (!preview.adapter && !preview.text.trim())) { if (typeof showToast === "function") showToast("请等待预览正文加载完成"); return; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 720 |
if (owner && owner.snapshot.id !== preview.id && !confirm("切换到当前预览会停止原朗读,继续吗?")) return;
|
| 721 |
if (owner && sameSource(owner.snapshot, preview) && seek(owner, offset, true)) return;
|
| 722 |
start(preview.adapter ? preview.snapshot : { id: preview.id, text: preview.text, title: preview.title }, offset);
|
|
@@ -731,7 +802,9 @@ if (typeof document !== "undefined") window.CCRDSpeech = (() => {
|
|
| 731 |
}
|
| 732 |
function launch() {
|
| 733 |
if (!owner) {
|
| 734 |
-
|
|
|
|
|
|
|
| 735 |
else fromPreview();
|
| 736 |
} else if (!panel.hidden) hide();
|
| 737 |
else { show(); if (!owner.wantsPlay && owner.snapshot.id === preview?.id) resume(); }
|
|
@@ -823,7 +896,7 @@ if (typeof document !== "undefined") window.CCRDSpeech = (() => {
|
|
| 823 |
previous.addEventListener("click", () => navigate(-1));
|
| 824 |
next.addEventListener("click", () => navigate(1));
|
| 825 |
visible.addEventListener("click", () => fromPreview());
|
| 826 |
-
locate.addEventListener("click",
|
| 827 |
collapse.addEventListener("click", hide);
|
| 828 |
stopButton.addEventListener("click", () => { stop(); clearMark(); hide(); });
|
| 829 |
pitch.addEventListener("input", controls);
|
|
@@ -847,6 +920,10 @@ if (typeof document !== "undefined") window.CCRDSpeech = (() => {
|
|
| 847 |
// readFrom: a host adapter's double-click/selection starts at a source offset.
|
| 848 |
return { launch, previewLoaded, previewPending, previewClosed, owns: node => !!node && panel.contains(node), modal: () => false,
|
| 849 |
readFrom: offset => { if (preview) fromPreview(plan.sentence(preview.text, offset).start); },
|
|
|
|
|
|
|
|
|
|
|
|
|
| 850 |
state: () => ({ active: !!owner, playing: !!owner?.wantsPlay, adapter: owner?.snapshot.adapter || saved?.snapshot.adapter || null }),
|
| 851 |
stop: () => { stop("已停止", true); clearMark(); hide(); } };
|
| 852 |
})();
|
|
|
|
| 44 |
// The fast first clip may extend to the first punctuation within 32
|
| 45 |
// characters instead of being cut mid-clause at about 16.
|
| 46 |
const ceiling = offsets[Math.min(chars.length, position + (short ? 32 : 120))];
|
| 47 |
+
const hard = cuts.find(value => value.end > start && value.end <= ceiling && endsSentence(text, value.end));
|
| 48 |
const natural = cuts.filter(value => value.end > start + (short ? 4 : 20) && value.end <= ceiling &&
|
| 49 |
/[,,::、—…][”’"'」』))\t \r]*$/u.test(text.slice(start, value.end)) && !connectorOnly(text.slice(start, value.end).trim()));
|
| 50 |
let end;
|
|
|
|
| 88 |
return offset && /[\uDC00-\uDFFF]/u.test(text[offset] || "") && /[\uD800-\uDBFF]/u.test(text[offset - 1]) ? offset - 1 : offset;
|
| 89 |
}
|
| 90 |
function boundary(text, index) {
|
| 91 |
+
return ending.test(text[index]) || (text[index] === "." && !ascii.test(text[index + 1] || "") && !listMarker(text, index));
|
| 92 |
+
}
|
| 93 |
+
// "1." / "12." / "一." / "(3)." at a line or clause start number the item that
|
| 94 |
+
// follows; that period must not end a sentence ("1." spoken alone, then the item).
|
| 95 |
+
function listMarker(text, index) {
|
| 96 |
+
let cursor = index;
|
| 97 |
+
const closed = cursor > 0 && /[))]/u.test(text[cursor - 1]);
|
| 98 |
+
if (closed) cursor -= 1;
|
| 99 |
+
const digits = cursor;
|
| 100 |
+
while (cursor > 0 && digits - cursor < 4 && /[0-90-9一二三四五六七八九十百]/u.test(text[cursor - 1])) cursor -= 1;
|
| 101 |
+
if (cursor === digits) return false;
|
| 102 |
+
if (cursor > 0 && /[((]/u.test(text[cursor - 1])) cursor -= 1;
|
| 103 |
+
else if (closed) return false;
|
| 104 |
+
return cursor === 0 || /[\s。!?!?;;::,,、]/u.test(text[cursor - 1]);
|
| 105 |
+
}
|
| 106 |
+
// Whether text[0..end) finishes a sentence (ignoring closing quotes/space).
|
| 107 |
+
function endsSentence(text, end) {
|
| 108 |
+
let index = end - 1;
|
| 109 |
+
while (index > 0 && /[”’"'」』))\t \r]/u.test(text[index])) index -= 1;
|
| 110 |
+
return index >= 0 && boundary(text, index);
|
| 111 |
}
|
| 112 |
// Clause marks for natural cut points; ASCII , and : only outside numbers/times.
|
| 113 |
function clause(text, index) {
|
|
|
|
| 318 |
function tickSleep() { if (!checkSleep() && sleepDeadline) sleepTimer = setTimeout(tickSleep, Math.min(1000, sleepDeadline - Date.now())); }
|
| 319 |
tickSleep();
|
| 320 |
}
|
| 321 |
+
// "回到播放位置" <-> "回到原位置" (like a reader's "back to page N" after a jump):
|
| 322 |
+
// after jumping, the button returns to where the reader was until the playing
|
| 323 |
+
// sentence is no longer in view (the reader scrolled away / it moved on).
|
| 324 |
+
let returnView = null, locateTimer = 0;
|
| 325 |
+
function playingInView() {
|
| 326 |
+
const value = owner || saved;
|
| 327 |
+
if (!value || preview?.id !== value.snapshot.id) return false;
|
| 328 |
+
if (value.snapshot.adapter) return preview.adapter === value.snapshot.adapter && !!value.snapshot.adapter.inView?.(value.position);
|
| 329 |
+
const rect = sourceRange(Math.min(value.position, Math.max(0, preview.text.length - 1)))?.getBoundingClientRect();
|
| 330 |
+
const box = preview.body.getBoundingClientRect();
|
| 331 |
+
return !!rect?.height && rect.bottom > Math.max(0, box.top) && rect.top < Math.min(innerHeight, box.bottom);
|
| 332 |
+
}
|
| 333 |
+
function updateLocate() {
|
| 334 |
+
if (returnView && performance.now() > returnView.grace && !playingInView()) returnView = null;
|
| 335 |
+
const back = !!returnView;
|
| 336 |
+
locate.textContent = back ? "回到原位置" : "回到播放位置";
|
| 337 |
+
locate.setAttribute("aria-label", back ? "回到跳转前的阅读位置" : "回到正在朗读的句子");
|
| 338 |
+
}
|
| 339 |
+
function viewChanged() { clearTimeout(locateTimer); locateTimer = setTimeout(updateLocate, 120); }
|
| 340 |
+
function saveView() {
|
| 341 |
+
if (preview?.adapter) return preview.adapter.saveView?.() ?? null;
|
| 342 |
+
return preview?.body ? { body: preview.body, top: preview.body.scrollTop, page: scrollY } : null;
|
| 343 |
+
}
|
| 344 |
+
function restoreView(view) {
|
| 345 |
+
if (view?.body) { view.body.scrollTop = view.top; scrollTo({ top: view.page }); }
|
| 346 |
+
else if (view !== null && view !== undefined) preview?.adapter?.restoreView?.(view);
|
| 347 |
+
}
|
| 348 |
+
async function toggleLocate() {
|
| 349 |
+
if (returnView) {
|
| 350 |
+
const view = returnView.view; returnView = null;
|
| 351 |
+
restoreView(view); updateLocate();
|
| 352 |
+
return;
|
| 353 |
+
}
|
| 354 |
+
const view = saveView();
|
| 355 |
+
await locateSource();
|
| 356 |
+
if (view !== null && view !== undefined) returnView = { view, grace: performance.now() + 2500 };
|
| 357 |
+
updateLocate();
|
| 358 |
+
}
|
| 359 |
+
document.addEventListener("scroll", viewChanged, { capture: true, passive: true });
|
| 360 |
function show() {
|
| 361 |
const parent = preview?.host?.isConnected ? preview.host : preview?.body?.isConnected ? preview.body.parentElement : $("#preview-panel:not([hidden])") || document.body;
|
| 362 |
if (panel.parentElement !== parent) parent.append(panel);
|
|
|
|
| 377 |
next.disabled = !owner || (plan.sentence(owner.snapshot.text, owner.position).end >= owner.snapshot.text.length && !more(owner.snapshot));
|
| 378 |
visible.disabled = !preview;
|
| 379 |
locate.disabled = !owner && !saved;
|
| 380 |
+
updateLocate();
|
| 381 |
$("#speech-pitch-value").textContent = (Number(pitch.value) > 0 ? "+" : "") + pitch.value;
|
| 382 |
$("#speech-speed-value").textContent = Number(speed.value).toFixed(2).replace(/0$/, "") + "×";
|
| 383 |
const button = $("[data-speech-toggle]");
|
|
|
|
| 426 |
const realm = (range.startContainer.ownerDocument || document).defaultView || globalThis;
|
| 427 |
if (realm.CSS?.highlights && realm.Highlight) { realm.CSS.highlights.set("ccrd-speech", new realm.Highlight(range)); markedRegistry = realm.CSS.highlights; }
|
| 428 |
preview.adapter.follow?.(start, end);
|
| 429 |
+
viewChanged();
|
| 430 |
return;
|
| 431 |
}
|
| 432 |
if (globalThis.CSS?.highlights && globalThis.Highlight) CSS.highlights.set("ccrd-speech", new Highlight(range));
|
|
|
|
| 774 |
if (job.preloaded) advance(value);
|
| 775 |
pump(value); // First POST directly; no iframe, voices or health round-trips.
|
| 776 |
}
|
| 777 |
+
function fromPreview(offset) {
|
| 778 |
// An adapter loads its text on demand; start() waits for it.
|
| 779 |
if (!preview || (!preview.adapter && !preview.text.trim())) { if (typeof showToast === "function") showToast("请等待预览正文加载完成"); return; }
|
| 780 |
+
if (offset === undefined && preview.adapter?.locateTop) {
|
| 781 |
+
// Find (and load up to) the text at the reading position first, so a
|
| 782 |
+
// paged document is not read from its first loaded unit.
|
| 783 |
+
const token = ++starting;
|
| 784 |
+
if (!owner) { notice("正在定位当前阅读位置…"); show(); }
|
| 785 |
+
Promise.resolve(preview.adapter.locateTop()).catch(() => 0).then((found) => {
|
| 786 |
+
if (token === starting && preview?.adapter) fromPreview(plan.safe(preview.text, Number(found) || 0));
|
| 787 |
+
});
|
| 788 |
+
return;
|
| 789 |
+
}
|
| 790 |
+
if (offset === undefined) offset = visibleOffset();
|
| 791 |
if (owner && owner.snapshot.id !== preview.id && !confirm("切换到当前预览会停止原朗读,继续吗?")) return;
|
| 792 |
if (owner && sameSource(owner.snapshot, preview) && seek(owner, offset, true)) return;
|
| 793 |
start(preview.adapter ? preview.snapshot : { id: preview.id, text: preview.text, title: preview.title }, offset);
|
|
|
|
| 802 |
}
|
| 803 |
function launch() {
|
| 804 |
if (!owner) {
|
| 805 |
+
// A host adapter resumes a stopped session only when it is the same
|
| 806 |
+
// window; otherwise "听书" starts where the reader is looking now.
|
| 807 |
+
if (saved?.snapshot.id === preview?.id && (!preview?.adapter || saved.snapshot.adapter === preview.adapter && !preview.adapter.locateTop)) start(saved.snapshot, saved.position);
|
| 808 |
else fromPreview();
|
| 809 |
} else if (!panel.hidden) hide();
|
| 810 |
else { show(); if (!owner.wantsPlay && owner.snapshot.id === preview?.id) resume(); }
|
|
|
|
| 896 |
previous.addEventListener("click", () => navigate(-1));
|
| 897 |
next.addEventListener("click", () => navigate(1));
|
| 898 |
visible.addEventListener("click", () => fromPreview());
|
| 899 |
+
locate.addEventListener("click", toggleLocate);
|
| 900 |
collapse.addEventListener("click", hide);
|
| 901 |
stopButton.addEventListener("click", () => { stop(); clearMark(); hide(); });
|
| 902 |
pitch.addEventListener("input", controls);
|
|
|
|
| 920 |
// readFrom: a host adapter's double-click/selection starts at a source offset.
|
| 921 |
return { launch, previewLoaded, previewPending, previewClosed, owns: node => !!node && panel.contains(node), modal: () => false,
|
| 922 |
readFrom: offset => { if (preview) fromPreview(plan.sentence(preview.text, offset).start); },
|
| 923 |
+
// Host hooks: show the playing sentence (no "回到原位置" toggle) and report
|
| 924 |
+
// scrolling the player cannot observe itself (e.g. inside an iframe).
|
| 925 |
+
reveal: () => { returnView = null; return locateSource().then(updateLocate); },
|
| 926 |
+
viewChanged,
|
| 927 |
state: () => ({ active: !!owner, playing: !!owner?.wantsPlay, adapter: owner?.snapshot.adapter || saved?.snapshot.adapter || null }),
|
| 928 |
stop: () => { stop("已停止", true); clearMark(); hide(); } };
|
| 929 |
})();
|
tests/test_reader_speech.py
CHANGED
|
@@ -54,7 +54,7 @@ class ReaderSpeechTest(unittest.TestCase):
|
|
| 54 |
cls.playwright.stop()
|
| 55 |
cls.server.__exit__(None, None, None)
|
| 56 |
|
| 57 |
-
def open(self, ext, body, content_type, viewport=None):
|
| 58 |
context = self.browser.new_context(viewport=viewport or {"width": 1280, "height": 860})
|
| 59 |
page = context.new_page()
|
| 60 |
posts, errors = [], []
|
|
@@ -85,10 +85,28 @@ class ReaderSpeechTest(unittest.TestCase):
|
|
| 85 |
|
| 86 |
page.route(SPEECH + "/**", speech)
|
| 87 |
page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type=content_type, body=body))
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
def play(self, page, posts):
|
| 94 |
button = page.locator(".reader-actions [data-speech-toggle]")
|
|
@@ -148,7 +166,16 @@ class ReaderSpeechTest(unittest.TestCase):
|
|
| 148 |
clip = page.locator("#speech-audio").evaluate("n => n.src")
|
| 149 |
page.wait_for_timeout(900)
|
| 150 |
self.assertEqual(viewport.evaluate("n => n.scrollTop"), away)
|
| 151 |
-
page.locator("#speech-locate")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
wait(page, f"() => document.querySelector('#viewport').scrollTop < {away - 2000}", 5000)
|
| 153 |
# The sentence being read is on screen, not merely its 32 KiB text block.
|
| 154 |
self.assertTrue(page.evaluate("""() => { const range = [...CSS.highlights.get('ccrd-speech')][0], rect = range.getBoundingClientRect();
|
|
@@ -163,6 +190,106 @@ class ReaderSpeechTest(unittest.TestCase):
|
|
| 163 |
finally:
|
| 164 |
context.close()
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
def test_native_pdf_text_layer_is_read_and_image_is_not_offered(self):
|
| 167 |
context, page, posts, errors = self.open("pdf", minimal_pdf(), "application/pdf")
|
| 168 |
try:
|
|
@@ -198,6 +325,10 @@ class ReaderSpeechTest(unittest.TestCase):
|
|
| 198 |
payload.extend(f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode())
|
| 199 |
context, page, posts, errors = self.open("pdf", bytes(payload), "application/pdf")
|
| 200 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
job = self.play(page, posts)
|
| 202 |
self.assertIn("Information Page Text", job["text"])
|
| 203 |
wait(page, "() => CSS.highlights.has('ccrd-speech')", 15000)
|
|
|
|
| 54 |
cls.playwright.stop()
|
| 55 |
cls.server.__exit__(None, None, None)
|
| 56 |
|
| 57 |
+
def open(self, ext, body, content_type, viewport=None, host=False, name="sample"):
|
| 58 |
context = self.browser.new_context(viewport=viewport or {"width": 1280, "height": 860})
|
| 59 |
page = context.new_page()
|
| 60 |
posts, errors = [], []
|
|
|
|
| 85 |
|
| 86 |
page.route(SPEECH + "/**", speech)
|
| 87 |
page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type=content_type, body=body))
|
| 88 |
+
reader = self.reader_url(ext, name)
|
| 89 |
+
if not host:
|
| 90 |
+
page.goto(reader, wait_until="domcontentloaded")
|
| 91 |
+
wait(page, "() => document.documentElement.dataset.readerPhase === 'ready'", 30000)
|
| 92 |
+
return context, page, posts, errors
|
| 93 |
+
# A same-origin host page owning the Reader overlay through the shared navigation module.
|
| 94 |
+
base = reader.split("reader.html")[0]
|
| 95 |
+
page.goto(base + "search/reader-navigation.js", wait_until="domcontentloaded")
|
| 96 |
+
# Inject as content: this host document has no charset, so a src= script would decode as Latin-1.
|
| 97 |
+
page.add_style_tag(content=(ROOT / "static/style.css").read_text(encoding="utf-8"))
|
| 98 |
+
page.add_script_tag(content=(ROOT / "static/search/reader-navigation.js").read_text(encoding="utf-8"))
|
| 99 |
+
page.evaluate("""url => {
|
| 100 |
+
window.__nav = VoiceOfMLReaderNavigation.createNavigation(new URL(url).pathname, { resume: next => __nav.mount(new URL(next)) });
|
| 101 |
+
window.__reader = __nav.mount(new URL(url));
|
| 102 |
+
}""", reader)
|
| 103 |
+
frame = page.wait_for_selector("iframe.reader-overlay").content_frame()
|
| 104 |
+
wait(frame, "() => document.documentElement.dataset.readerPhase === 'ready'", 30000)
|
| 105 |
+
return context, page, posts, errors, frame
|
| 106 |
+
|
| 107 |
+
def reader_url(self, ext, name="sample"):
|
| 108 |
+
query = urllib.parse.quote(f"{SOURCE.rsplit('/', 1)[0]}/{name}.{ext}", safe="")
|
| 109 |
+
return f"{self.origin}/static/reader.html?url={query}&ext={ext}&title=Speech"
|
| 110 |
|
| 111 |
def play(self, page, posts):
|
| 112 |
button = page.locator(".reader-actions [data-speech-toggle]")
|
|
|
|
| 166 |
clip = page.locator("#speech-audio").evaluate("n => n.src")
|
| 167 |
page.wait_for_timeout(900)
|
| 168 |
self.assertEqual(viewport.evaluate("n => n.scrollTop"), away)
|
| 169 |
+
locate = page.locator("#speech-locate")
|
| 170 |
+
self.assertEqual(locate.inner_text(), "回到播放位置")
|
| 171 |
+
locate.click()
|
| 172 |
+
wait(page, f"() => document.querySelector('#viewport').scrollTop < {away - 2000}", 5000)
|
| 173 |
+
# After jumping, the same button returns to where the reader was.
|
| 174 |
+
wait(page, "() => document.querySelector('#speech-locate').textContent === '回到原位置'", 3000)
|
| 175 |
+
locate.click()
|
| 176 |
+
wait(page, f"() => document.querySelector('#viewport').scrollTop === {away}", 3000)
|
| 177 |
+
wait(page, "() => document.querySelector('#speech-locate').textContent === '回到播放位置'", 3000)
|
| 178 |
+
locate.click()
|
| 179 |
wait(page, f"() => document.querySelector('#viewport').scrollTop < {away - 2000}", 5000)
|
| 180 |
# The sentence being read is on screen, not merely its 32 KiB text block.
|
| 181 |
self.assertTrue(page.evaluate("""() => { const range = [...CSS.highlights.get('ccrd-speech')][0], rect = range.getBoundingClientRect();
|
|
|
|
| 190 |
finally:
|
| 191 |
context.close()
|
| 192 |
|
| 193 |
+
def test_a_small_scroll_while_listening_is_never_undone(self):
|
| 194 |
+
# The reader nudges the page while the sentence is still on screen; later
|
| 195 |
+
# sentences must not pull it back (only 回到播放位置 resumes following).
|
| 196 |
+
body = "".join(f"第{index}句。\n" for index in range(400)).encode()
|
| 197 |
+
context, page, posts, errors = self.open("txt", body, "text/plain; charset=utf-8", viewport={"width": 1280, "height": 420})
|
| 198 |
+
try:
|
| 199 |
+
self.play(page, posts)
|
| 200 |
+
viewport = page.locator("#viewport")
|
| 201 |
+
on_screen = """() => { const range = [...(CSS.highlights.get('ccrd-speech') || [])][0];
|
| 202 |
+
const box = document.querySelector('#viewport').getBoundingClientRect(), rect = range && range.getBoundingClientRect();
|
| 203 |
+
return !!rect && rect.top >= box.top && rect.bottom <= box.bottom; }"""
|
| 204 |
+
clip = page.locator("#speech-audio").evaluate("n => n.src")
|
| 205 |
+
for _ in range(4): # the playing sentence moves to the middle of the screen
|
| 206 |
+
page.locator("#speech-next").click()
|
| 207 |
+
wait(page, f"() => document.querySelector('#speech-audio').src !== {json.dumps(clip)}")
|
| 208 |
+
clip = page.locator("#speech-audio").evaluate("n => n.src")
|
| 209 |
+
box = viewport.bounding_box()
|
| 210 |
+
page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
|
| 211 |
+
page.mouse.wheel(0, 40)
|
| 212 |
+
page.wait_for_timeout(500)
|
| 213 |
+
self.assertTrue(page.evaluate(on_screen)) # still visible after the nudge
|
| 214 |
+
moved = viewport.evaluate("n => n.scrollTop")
|
| 215 |
+
self.assertGreater(moved, 0)
|
| 216 |
+
below = """() => { const range = [...(CSS.highlights.get('ccrd-speech') || [])][0];
|
| 217 |
+
const box = document.querySelector('#viewport').getBoundingClientRect();
|
| 218 |
+
return !!range && range.getBoundingClientRect().top > box.bottom; }"""
|
| 219 |
+
passed = 0
|
| 220 |
+
for _ in range(40): # walk the sentence past the bottom of the viewport, then two more
|
| 221 |
+
page.locator("#speech-next").click()
|
| 222 |
+
wait(page, f"() => document.querySelector('#speech-audio').src !== {json.dumps(clip)}")
|
| 223 |
+
clip = page.locator("#speech-audio").evaluate("n => n.src")
|
| 224 |
+
page.wait_for_timeout(250)
|
| 225 |
+
self.assertEqual(viewport.evaluate("n => n.scrollTop"), moved)
|
| 226 |
+
passed += page.evaluate(below)
|
| 227 |
+
if passed >= 2:
|
| 228 |
+
break
|
| 229 |
+
self.assertGreaterEqual(passed, 2)
|
| 230 |
+
page.wait_for_timeout(900)
|
| 231 |
+
self.assertEqual(viewport.evaluate("n => n.scrollTop"), moved)
|
| 232 |
+
self.stop(page)
|
| 233 |
+
self.assertFalse(errors, errors)
|
| 234 |
+
finally:
|
| 235 |
+
context.close()
|
| 236 |
+
|
| 237 |
+
def test_listening_starts_where_the_reader_is_looking(self):
|
| 238 |
+
body = "".join(f"第{index}句。\n" for index in range(400)).encode()
|
| 239 |
+
context, page, posts, errors = self.open("txt", body, "text/plain; charset=utf-8")
|
| 240 |
+
try:
|
| 241 |
+
page.locator("#viewport").evaluate("n => { n.scrollTop = 4000; }")
|
| 242 |
+
page.wait_for_timeout(400)
|
| 243 |
+
# The first line at the top of the viewport, measured independently.
|
| 244 |
+
first = page.evaluate("""() => { const box = document.querySelector('#viewport').getBoundingClientRect();
|
| 245 |
+
const node = document.querySelector('.reader-text-block').firstChild, range = document.createRange();
|
| 246 |
+
for (let i = 0; i < node.length; i++) { range.setStart(node, i); range.setEnd(node, i + 1);
|
| 247 |
+
const r = range.getClientRects()[0]; if (r && r.height && r.bottom > box.top + 4) return node.data.slice(i).match(/第(\\d+)句/)[1]; } }""")
|
| 248 |
+
self.assertGreater(int(first), 50)
|
| 249 |
+
job = self.play(page, posts)
|
| 250 |
+
self.assertTrue(job["text"].lstrip().startswith(f"第{first}句") or job["text"].lstrip().startswith(f"{first}句"), (first, job["text"][:30]))
|
| 251 |
+
self.stop(page)
|
| 252 |
+
self.assertFalse(errors, errors)
|
| 253 |
+
finally:
|
| 254 |
+
context.close()
|
| 255 |
+
|
| 256 |
+
def test_closing_the_reader_keeps_reading_in_the_background(self):
|
| 257 |
+
context, page, posts, errors, frame = self.open("txt", TEXT.encode(), "text/plain; charset=utf-8", host=True)
|
| 258 |
+
try:
|
| 259 |
+
self.play(frame, posts)
|
| 260 |
+
page.evaluate("() => __nav.unmount()")
|
| 261 |
+
bar = page.locator(".reader-speech-mini")
|
| 262 |
+
bar.wait_for(timeout=3000)
|
| 263 |
+
self.assertTrue(page.evaluate("() => __reader.isConnected && __nav.backgroundReader === __reader"))
|
| 264 |
+
self.assertEqual(page.evaluate("getComputedStyle(__reader).visibility"), "hidden")
|
| 265 |
+
before = frame.evaluate("() => [document.querySelector('#speech-audio').src, document.querySelector('#speech-audio').currentTime]")
|
| 266 |
+
page.wait_for_timeout(1500)
|
| 267 |
+
after = frame.evaluate("() => [document.querySelector('#speech-audio').src, document.querySelector('#speech-audio').currentTime]")
|
| 268 |
+
self.assertNotEqual(before, after) # still reading while hidden
|
| 269 |
+
# Pause / continue from the search page.
|
| 270 |
+
bar.get_by_role("button", name="暂停").click()
|
| 271 |
+
wait(frame, "() => document.querySelector('#speech-audio').paused", 5000)
|
| 272 |
+
bar.get_by_role("button", name="继续").wait_for(timeout=3000)
|
| 273 |
+
bar.get_by_role("button", name="继续").click()
|
| 274 |
+
wait(frame, "() => !document.querySelector('#speech-audio').paused", 5000)
|
| 275 |
+
# Back to the same Reader (not a reload), still reading.
|
| 276 |
+
bar.get_by_role("button", name="返回阅读").click()
|
| 277 |
+
self.assertEqual(page.locator(".reader-speech-mini").count(), 0)
|
| 278 |
+
self.assertTrue(page.evaluate("() => document.querySelector('iframe.reader-overlay') === __reader && !__nav.backgroundReader && getComputedStyle(__reader).visibility === 'visible'"))
|
| 279 |
+
self.assertFalse(frame.evaluate("() => document.querySelector('#speech-audio').paused"))
|
| 280 |
+
# Opening another book stops background reading and releases its Reader.
|
| 281 |
+
page.evaluate("() => __nav.unmount()")
|
| 282 |
+
bar.wait_for(timeout=3000)
|
| 283 |
+
page.evaluate("url => { window.__next = __nav.mount(new URL(url)); }", self.reader_url("txt", "other"))
|
| 284 |
+
self.assertTrue(page.evaluate("() => !__reader.isConnected && __next !== __reader && !__nav.backgroundReader"))
|
| 285 |
+
self.assertEqual(page.locator(".reader-speech-mini").count(), 0)
|
| 286 |
+
page.evaluate("() => __nav.unmount()")
|
| 287 |
+
# A Reader that is not reading closes normally.
|
| 288 |
+
self.assertTrue(page.evaluate("() => !__next.isConnected && !__nav.backgroundReader"))
|
| 289 |
+
self.assertFalse(errors, errors)
|
| 290 |
+
finally:
|
| 291 |
+
context.close()
|
| 292 |
+
|
| 293 |
def test_native_pdf_text_layer_is_read_and_image_is_not_offered(self):
|
| 294 |
context, page, posts, errors = self.open("pdf", minimal_pdf(), "application/pdf")
|
| 295 |
try:
|
|
|
|
| 325 |
payload.extend(f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode())
|
| 326 |
context, page, posts, errors = self.open("pdf", bytes(payload), "application/pdf")
|
| 327 |
try:
|
| 328 |
+
# No text near page 1: no button. It appears once the text page is in view.
|
| 329 |
+
page.wait_for_timeout(2500)
|
| 330 |
+
self.assertEqual(page.locator("[data-speech-toggle]").count(), 0)
|
| 331 |
+
page.locator("#viewport").evaluate("n => { n.scrollTop = n.scrollHeight; }")
|
| 332 |
job = self.play(page, posts)
|
| 333 |
self.assertIn("Information Page Text", job["text"])
|
| 334 |
wait(page, "() => CSS.highlights.has('ccrd-speech')", 15000)
|