vomebook commited on
Commit ·
2b84661
1
Parent(s): ad4ff55
fix: retain nearby PDF pages and reduce Reader rendering work
Browse files- static/reader-pdf-book-search-worker.mjs +16 -7
- static/reader.css +11 -0
- static/reader.js +67 -45
- tests/test_reader_architecture.js +2 -2
- tests/test_reader_close_traffic.py +4 -1
- tests/test_reader_ocr_transport.mjs +20 -0
- tests/test_reader_optimizations.py +50 -1
- tests/test_reader_refactor.py +1 -1
static/reader-pdf-book-search-worker.mjs
CHANGED
|
@@ -20,8 +20,10 @@ function validUrl(raw) {
|
|
| 20 |
!url.search && !!prefix && bookPath.test(decodeURIComponent(url.pathname.slice(prefix[0].length)));
|
| 21 |
}
|
| 22 |
|
| 23 |
-
async function readBounded(stream, signal) {
|
| 24 |
const reader = stream.getReader(), chunks = [];
|
|
|
|
|
|
|
| 25 |
let size = 0;
|
| 26 |
const cancel = () => reader.cancel().catch(() => {});
|
| 27 |
signal.addEventListener("abort", cancel, { once: true });
|
|
@@ -32,9 +34,15 @@ async function readBounded(stream, signal) {
|
|
| 32 |
if (signal.aborted) throw aborted();
|
| 33 |
if (done) break;
|
| 34 |
size += value.byteLength;
|
| 35 |
-
if (size > limit) throw new Error("READER_RESOURCE_LIMIT");
|
| 36 |
-
|
|
|
|
| 37 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
const result = new Uint8Array(size);
|
| 39 |
let offset = 0;
|
| 40 |
for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; }
|
|
@@ -60,14 +68,15 @@ async function loadBook() {
|
|
| 60 |
pendingBook = (async () => {
|
| 61 |
const response = await fetch(configuration.url, { signal: request.signal, credentials: "omit" });
|
| 62 |
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
| 63 |
-
|
| 64 |
if (packed.byteLength !== configuration.bytes) throw new Error("PDF_OCR_SIZE_MISMATCH");
|
| 65 |
const digest = [...new Uint8Array(await crypto.subtle.digest("SHA-256", packed))]
|
| 66 |
.map(value => value.toString(16).padStart(2, "0")).join("");
|
| 67 |
if (digest !== configuration.sha256) throw new Error("PDF_OCR_HASH_MISMATCH");
|
| 68 |
-
const
|
| 69 |
-
|
| 70 |
-
const decoded = JSON.parse(
|
|
|
|
| 71 |
if (request.signal.aborted) throw aborted();
|
| 72 |
book = validateBookText(decoded, configuration.pageCount, configuration.sourceSha);
|
| 73 |
return book;
|
|
|
|
| 20 |
!url.search && !!prefix && bookPath.test(decodeURIComponent(url.pathname.slice(prefix[0].length)));
|
| 21 |
}
|
| 22 |
|
| 23 |
+
async function readBounded(stream, signal, expected = null, text = false) {
|
| 24 |
const reader = stream.getReader(), chunks = [];
|
| 25 |
+
const bytes = expected === null ? null : new Uint8Array(expected);
|
| 26 |
+
const decoder = text ? new TextDecoder() : null;
|
| 27 |
let size = 0;
|
| 28 |
const cancel = () => reader.cancel().catch(() => {});
|
| 29 |
signal.addEventListener("abort", cancel, { once: true });
|
|
|
|
| 34 |
if (signal.aborted) throw aborted();
|
| 35 |
if (done) break;
|
| 36 |
size += value.byteLength;
|
| 37 |
+
if (size > limit || (bytes && size > bytes.length)) throw new Error("READER_RESOURCE_LIMIT");
|
| 38 |
+
if (bytes) bytes.set(value, size - value.byteLength);
|
| 39 |
+
else chunks.push(decoder ? decoder.decode(value, {stream:true}) : value);
|
| 40 |
}
|
| 41 |
+
if (bytes) {
|
| 42 |
+
if (size !== expected) throw new Error("PDF_OCR_SIZE_MISMATCH");
|
| 43 |
+
return bytes;
|
| 44 |
+
}
|
| 45 |
+
if (decoder) { chunks.push(decoder.decode()); return chunks.join(""); }
|
| 46 |
const result = new Uint8Array(size);
|
| 47 |
let offset = 0;
|
| 48 |
for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; }
|
|
|
|
| 68 |
pendingBook = (async () => {
|
| 69 |
const response = await fetch(configuration.url, { signal: request.signal, credentials: "omit" });
|
| 70 |
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
| 71 |
+
let packed = await readBounded(response.body, request.signal, configuration.bytes);
|
| 72 |
if (packed.byteLength !== configuration.bytes) throw new Error("PDF_OCR_SIZE_MISMATCH");
|
| 73 |
const digest = [...new Uint8Array(await crypto.subtle.digest("SHA-256", packed))]
|
| 74 |
.map(value => value.toString(16).padStart(2, "0")).join("");
|
| 75 |
if (digest !== configuration.sha256) throw new Error("PDF_OCR_HASH_MISMATCH");
|
| 76 |
+
const stream = new ReadableStream({start(controller) {controller.enqueue(packed); controller.close();}});
|
| 77 |
+
packed = null;
|
| 78 |
+
const decoded = JSON.parse(await readBounded(
|
| 79 |
+
stream.pipeThrough(new DecompressionStream("gzip")), request.signal, null, true));
|
| 80 |
if (request.signal.aborted) throw aborted();
|
| 81 |
book = validateBookText(decoded, configuration.pageCount, configuration.sourceSha);
|
| 82 |
return book;
|
static/reader.css
CHANGED
|
@@ -1105,6 +1105,17 @@ body {
|
|
| 1105 |
monospace;
|
| 1106 |
color: #e7e9eb;
|
| 1107 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1108 |
.reader-markdown {
|
| 1109 |
margin: 0 auto;
|
| 1110 |
max-width: 76ch;
|
|
|
|
| 1105 |
monospace;
|
| 1106 |
color: #e7e9eb;
|
| 1107 |
}
|
| 1108 |
+
.reader-text-block {
|
| 1109 |
+
margin: 0;
|
| 1110 |
+
font: inherit;
|
| 1111 |
+
white-space: inherit;
|
| 1112 |
+
overflow-wrap: inherit;
|
| 1113 |
+
content-visibility: auto;
|
| 1114 |
+
contain-intrinsic-block-size: auto 1600px;
|
| 1115 |
+
}
|
| 1116 |
+
.reader-text-block:focus-within {
|
| 1117 |
+
content-visibility: visible;
|
| 1118 |
+
}
|
| 1119 |
.reader-markdown {
|
| 1120 |
margin: 0 auto;
|
| 1121 |
max-width: 76ch;
|
static/reader.js
CHANGED
|
@@ -449,6 +449,8 @@ let folderNavigationTarget = null;
|
|
| 449 |
let bookmarkInvoker = null;
|
| 450 |
const bookmarkInertSiblings = new Map();
|
| 451 |
let pdfDocument = null;
|
|
|
|
|
|
|
| 452 |
let pdfPageManifest = null;
|
| 453 |
let pdfOcrManifest = null;
|
| 454 |
let pdfOcrManifestPromise = null;
|
|
@@ -555,14 +557,14 @@ function trimPdfSurfaces(protectedShell) {
|
|
| 555 |
let canvases = shells.filter(shell => shell.querySelector("canvas.ready")).length;
|
| 556 |
let images = shells.filter(shell => shell.querySelector("img.ready")).length;
|
| 557 |
let pixels = pdfRetainedPixels();
|
| 558 |
-
|
| 559 |
-
|
|
|
|
| 560 |
Number(a.dataset.renderUsedAt || 0) - Number(b.dataset.renderUsedAt || 0));
|
| 561 |
for (const shell of shells) {
|
| 562 |
const canvas = shell.querySelector("canvas.ready"), image = shell.querySelector("img.ready");
|
| 563 |
if (pixels <= pdfPixelBudget() && !(canvas && canvases > canvasLimit) && !(image && images > 25)) continue;
|
| 564 |
-
if (shell
|
| 565 |
-
Number(shell.dataset.page) === documentState.page || pdfSelectionIntersects(shell)) continue;
|
| 566 |
shell._textEpoch = (shell._textEpoch || 0) + 1;
|
| 567 |
if (canvas) {
|
| 568 |
pixels -= pdfSurfacePixels(canvas);
|
|
@@ -581,6 +583,8 @@ function trimPdfSurfaces(protectedShell) {
|
|
| 581 |
shell._bookmarkTextItems = [];
|
| 582 |
shell.dataset.textReady = "0";
|
| 583 |
shell.dataset.renderState = "idle";
|
|
|
|
|
|
|
| 584 |
}
|
| 585 |
fullSearchActiveMarks = fullSearchActiveMarks.filter(mark => mark.isConnected);
|
| 586 |
}
|
|
@@ -2046,16 +2050,15 @@ async function renderBookmarks() {
|
|
| 2046 |
}
|
| 2047 |
function pageAtMarker() {
|
| 2048 |
const y = bookmarkRibbon.getBoundingClientRect().bottom,
|
| 2049 |
-
pages = [...content.querySelectorAll(".reader-page, .reader-docx-page")];
|
| 2050 |
if (!pages.length) return null;
|
| 2051 |
-
|
| 2052 |
-
|
| 2053 |
-
|
| 2054 |
-
|
| 2055 |
-
|
| 2056 |
-
|
| 2057 |
-
|
| 2058 |
-
);
|
| 2059 |
}
|
| 2060 |
function syncCurrentPageFromMarker() {
|
| 2061 |
if (performance.now() < pageNavigationLockUntil) return;
|
|
@@ -3577,13 +3580,16 @@ async function renderPdf(prepared) {
|
|
| 3577 |
textLayer.setAttribute("role", "document");
|
| 3578 |
textLayer.setAttribute("aria-label", `第 ${page} 页正文`);
|
| 3579 |
shell.append(canvas, textLayer);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3580 |
shell.addEventListener("focus", () => renderPdfInBackground(shell));
|
| 3581 |
observeShell(shell);
|
| 3582 |
return shell;
|
| 3583 |
};
|
| 3584 |
const firstShell = createShell(1);
|
| 3585 |
content.appendChild(firstShell);
|
| 3586 |
-
markReaderContentReady();
|
| 3587 |
pdfShellWindow = createPdfShellWindow(pdf.numPages, firstShell, createShell, (shell) => {
|
| 3588 |
observer.unobserve(shell);
|
| 3589 |
visibleObserver.unobserve(shell);
|
|
@@ -3769,7 +3775,7 @@ async function renderHybridPdfCanvas(shell, signal, priority) {
|
|
| 3769 |
acquired = true;
|
| 3770 |
}
|
| 3771 |
const base = page.getViewport({ scale: 1 });
|
| 3772 |
-
const view = page.getViewport({ scale: Math.min(3,
|
| 3773 |
const outputScale = Math.min(2, Math.max(1, Number(window.devicePixelRatio) || 1));
|
| 3774 |
canvas = document.createElement("canvas");
|
| 3775 |
canvas.setAttribute("aria-hidden", "true");
|
|
@@ -3972,7 +3978,7 @@ function renderPdfShell(shell, force = false, priority = false) {
|
|
| 3972 |
assertReaderActive();
|
| 3973 |
if (renderController.signal.aborted) throw readerAbortError();
|
| 3974 |
const base = page.getViewport({ scale: 1 }),
|
| 3975 |
-
scale = Math.min(3,
|
| 3976 |
viewport = page.getViewport({ scale }),
|
| 3977 |
outputScale = Math.min(2, Math.max(1, Number(window.devicePixelRatio) || 1));
|
| 3978 |
const canvas = shell.querySelector("canvas");
|
|
@@ -4003,6 +4009,8 @@ function renderPdfShell(shell, force = false, priority = false) {
|
|
| 4003 |
if (!isReaderGenerationCurrent("pdf", generation)) shell.dataset.pendingRerender = "1";
|
| 4004 |
} while (shell.dataset.pendingRerender);
|
| 4005 |
shell.querySelector("canvas").classList.add("ready");
|
|
|
|
|
|
|
| 4006 |
shell.dataset.renderState = "rendered";
|
| 4007 |
shell.dataset.renderUsedAt = String(Date.now());
|
| 4008 |
pdfShellWindow?.remember(shell);
|
|
@@ -4133,12 +4141,14 @@ function acquirePdfRenderSlot(priority = false, shell = null, signal = null) {
|
|
| 4133 |
function releasePdfRenderSlot() {
|
| 4134 |
pdfActiveRenders = Math.max(0, pdfActiveRenders - 1);
|
| 4135 |
if (readerAbortController.signal.aborted) return;
|
| 4136 |
-
let index = -1, best =
|
| 4137 |
for (let i = 0; i < pdfRenderWaiters.length; i++) {
|
| 4138 |
-
const waiter = pdfRenderWaiters[i], value =
|
| 4139 |
-
|
| 4140 |
-
);
|
| 4141 |
-
if (value > best
|
|
|
|
|
|
|
| 4142 |
}
|
| 4143 |
if (index < 0) index = 0;
|
| 4144 |
const waiter = pdfRenderWaiters.splice(index, 1)[0];
|
|
@@ -4442,9 +4452,28 @@ function repairHtmlContrast(frame) {
|
|
| 4442 |
}
|
| 4443 |
async function renderPlainText(response) {
|
| 4444 |
assertReaderActive();
|
| 4445 |
-
const pre = document.createElement("
|
| 4446 |
pre.className = "reader-text";
|
| 4447 |
content.appendChild(pre);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4448 |
const limit = VoiceOfMLReaderSecurity.LIMITS.documentBytes;
|
| 4449 |
VoiceOfMLReaderSecurity.assertResponseSize(response, limit);
|
| 4450 |
if (!response.body?.getReader) {
|
|
@@ -4455,9 +4484,7 @@ async function renderPlainText(response) {
|
|
| 4455 |
throw error;
|
| 4456 |
}
|
| 4457 |
assertReaderActive();
|
| 4458 |
-
|
| 4459 |
-
.decode(bytes)
|
| 4460 |
-
.replace(/\ufffd/g, "");
|
| 4461 |
return;
|
| 4462 |
}
|
| 4463 |
const reader = response.body.getReader(),
|
|
@@ -4474,14 +4501,6 @@ async function renderPlainText(response) {
|
|
| 4474 |
decoder = null,
|
| 4475 |
asciiPreviewPossible = true,
|
| 4476 |
asciiPrefixLength = 0;
|
| 4477 |
-
const appendDecoded = (value) => {
|
| 4478 |
-
const text = value.replace(/\ufffd/g, "");
|
| 4479 |
-
if (!text) return;
|
| 4480 |
-
// Search can split or normalize previous chunks while the response streams.
|
| 4481 |
-
const tail = pre.lastChild;
|
| 4482 |
-
if (tail?.nodeType === Node.TEXT_NODE) tail.appendData(text);
|
| 4483 |
-
else pre.appendChild(document.createTextNode(text));
|
| 4484 |
-
};
|
| 4485 |
const startDecoder = () => {
|
| 4486 |
const sample = new Uint8Array(sampleLength);
|
| 4487 |
let offset = 0;
|
|
@@ -4516,6 +4535,8 @@ async function renderPlainText(response) {
|
|
| 4516 |
if (value[asciiLength] === 0) {
|
| 4517 |
// A split UTF-16 prefix must not leave an ASCII preview behind.
|
| 4518 |
pre.textContent = "";
|
|
|
|
|
|
|
| 4519 |
displayedSampleSize = 0;
|
| 4520 |
asciiPrefixLength = 0;
|
| 4521 |
asciiPreviewPossible = false;
|
|
@@ -5038,6 +5059,7 @@ async function renderDocx(prepared) {
|
|
| 5038 |
throw new Error("DOCX rendered no supported content");
|
| 5039 |
}
|
| 5040 |
const pages = [...body.querySelectorAll(":scope > .reader-docx-wrapper > section.reader-docx")];
|
|
|
|
| 5041 |
if (pages.length) {
|
| 5042 |
updateDocumentState({ pageCount: pages.length });
|
| 5043 |
pageInput.max = String(documentState.pageCount);
|
|
@@ -6731,11 +6753,11 @@ function clearFullSearchMarks() {
|
|
| 6731 |
fullSearchDomSnapshot?.resume();
|
| 6732 |
}
|
| 6733 |
}
|
| 6734 |
-
async function fullSearchTextNodes(root, generation, endOffset = Infinity, checkpoint = null) {
|
| 6735 |
const nodes = [],
|
| 6736 |
walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
| 6737 |
if (checkpoint) walker.currentNode = checkpoint.target;
|
| 6738 |
-
let visited = 0, length = checkpoint?.start || 0;
|
| 6739 |
while (walker.nextNode()) {
|
| 6740 |
if (!isReaderGenerationCurrent("search", generation)) return null;
|
| 6741 |
const node = walker.currentNode;
|
|
@@ -6743,11 +6765,15 @@ async function fullSearchTextNodes(root, generation, endOffset = Infinity, check
|
|
| 6743 |
node.data &&
|
| 6744 |
!node.parentElement.closest("script,style,mark.full-search-highlight,.reader-pdf-text")
|
| 6745 |
) {
|
| 6746 |
-
|
|
|
|
| 6747 |
length += node.data.length;
|
| 6748 |
if (length >= endOffset) break;
|
| 6749 |
}
|
| 6750 |
-
if (++visited %
|
|
|
|
|
|
|
|
|
|
| 6751 |
}
|
| 6752 |
return nodes;
|
| 6753 |
}
|
|
@@ -6858,20 +6884,16 @@ async function fullSearchDomMatches(root, fallback, query, generation, progressi
|
|
| 6858 |
fullSearchDomSnapshot.value?.toc === navigationState.tocEntries ? fullSearchDomSnapshot.value : null;
|
| 6859 |
const snapshot = progressive ? (cached ? fullSearchDomSnapshot : createDomSearchSnapshot(root)) : null;
|
| 6860 |
const locator = progressive ? createFullSearchDomLocator(root, generation) : null;
|
| 6861 |
-
const nodes = cached ? [] : await fullSearchTextNodes(root, generation);
|
| 6862 |
-
if (!nodes || !isReaderGenerationCurrent("search", generation)) return [];
|
| 6863 |
const offsets = cached ? cached.offsets : [],
|
| 6864 |
chunks = [];
|
| 6865 |
let length = 0;
|
| 6866 |
-
|
| 6867 |
offsets.push({ node, parent: node.parentElement, start: length, end: length + node.data.length });
|
| 6868 |
chunks.push(node.data);
|
| 6869 |
length += node.data.length;
|
| 6870 |
-
|
| 6871 |
-
|
| 6872 |
-
|
| 6873 |
-
}
|
| 6874 |
-
}
|
| 6875 |
if (cached) locator?.seed(cached.checkpoints);
|
| 6876 |
else locator?.build(offsets);
|
| 6877 |
const headingLookup = cached ? cached.headingLookup : createFullSearchHeadingLookup(root, offsets);
|
|
|
|
| 449 |
let bookmarkInvoker = null;
|
| 450 |
const bookmarkInertSiblings = new Map();
|
| 451 |
let pdfDocument = null;
|
| 452 |
+
let docxPageNodes = [];
|
| 453 |
+
trackReaderResource(() => { docxPageNodes = []; });
|
| 454 |
let pdfPageManifest = null;
|
| 455 |
let pdfOcrManifest = null;
|
| 456 |
let pdfOcrManifestPromise = null;
|
|
|
|
| 557 |
let canvases = shells.filter(shell => shell.querySelector("canvas.ready")).length;
|
| 558 |
let images = shells.filter(shell => shell.querySelector("img.ready")).length;
|
| 559 |
let pixels = pdfRetainedPixels();
|
| 560 |
+
const retentionPage = Number(pageAtMarker()?.dataset.page) || documentState.page;
|
| 561 |
+
shells.sort((a, b) => Math.abs(Number(b.dataset.page) - retentionPage) -
|
| 562 |
+
Math.abs(Number(a.dataset.page) - retentionPage) ||
|
| 563 |
Number(a.dataset.renderUsedAt || 0) - Number(b.dataset.renderUsedAt || 0));
|
| 564 |
for (const shell of shells) {
|
| 565 |
const canvas = shell.querySelector("canvas.ready"), image = shell.querySelector("img.ready");
|
| 566 |
if (pixels <= pdfPixelBudget() && !(canvas && canvases > canvasLimit) && !(image && images > 25)) continue;
|
| 567 |
+
if (isPdfPageVisible(shell) || Number(shell.dataset.page) === retentionPage || pdfSelectionIntersects(shell)) continue;
|
|
|
|
| 568 |
shell._textEpoch = (shell._textEpoch || 0) + 1;
|
| 569 |
if (canvas) {
|
| 570 |
pixels -= pdfSurfacePixels(canvas);
|
|
|
|
| 583 |
shell._bookmarkTextItems = [];
|
| 584 |
shell.dataset.textReady = "0";
|
| 585 |
shell.dataset.renderState = "idle";
|
| 586 |
+
const pageState = shell.querySelector(".reader-page-state");
|
| 587 |
+
if (pageState) pageState.hidden = false;
|
| 588 |
}
|
| 589 |
fullSearchActiveMarks = fullSearchActiveMarks.filter(mark => mark.isConnected);
|
| 590 |
}
|
|
|
|
| 2050 |
}
|
| 2051 |
function pageAtMarker() {
|
| 2052 |
const y = bookmarkRibbon.getBoundingClientRect().bottom,
|
| 2053 |
+
pages = docxPageNodes.length ? docxPageNodes : [...content.querySelectorAll(".reader-page, .reader-docx-page")];
|
| 2054 |
if (!pages.length) return null;
|
| 2055 |
+
let low = 0, high = pages.length;
|
| 2056 |
+
while (low < high) {
|
| 2057 |
+
const middle = (low + high) >> 1;
|
| 2058 |
+
if (pages[middle].getBoundingClientRect().bottom > y) high = middle;
|
| 2059 |
+
else low = middle + 1;
|
| 2060 |
+
}
|
| 2061 |
+
return pages[Math.min(low, pages.length - 1)];
|
|
|
|
| 2062 |
}
|
| 2063 |
function syncCurrentPageFromMarker() {
|
| 2064 |
if (performance.now() < pageNavigationLockUntil) return;
|
|
|
|
| 3580 |
textLayer.setAttribute("role", "document");
|
| 3581 |
textLayer.setAttribute("aria-label", `第 ${page} 页正文`);
|
| 3582 |
shell.append(canvas, textLayer);
|
| 3583 |
+
const pageState = document.createElement("div");
|
| 3584 |
+
pageState.className = "reader-page-state";
|
| 3585 |
+
pageState.textContent = `正在加载第 ${page} 页...`;
|
| 3586 |
+
shell.appendChild(pageState);
|
| 3587 |
shell.addEventListener("focus", () => renderPdfInBackground(shell));
|
| 3588 |
observeShell(shell);
|
| 3589 |
return shell;
|
| 3590 |
};
|
| 3591 |
const firstShell = createShell(1);
|
| 3592 |
content.appendChild(firstShell);
|
|
|
|
| 3593 |
pdfShellWindow = createPdfShellWindow(pdf.numPages, firstShell, createShell, (shell) => {
|
| 3594 |
observer.unobserve(shell);
|
| 3595 |
visibleObserver.unobserve(shell);
|
|
|
|
| 3775 |
acquired = true;
|
| 3776 |
}
|
| 3777 |
const base = page.getViewport({ scale: 1 });
|
| 3778 |
+
const view = page.getViewport({ scale: Math.min(3, shell.clientWidth / base.width) });
|
| 3779 |
const outputScale = Math.min(2, Math.max(1, Number(window.devicePixelRatio) || 1));
|
| 3780 |
canvas = document.createElement("canvas");
|
| 3781 |
canvas.setAttribute("aria-hidden", "true");
|
|
|
|
| 3978 |
assertReaderActive();
|
| 3979 |
if (renderController.signal.aborted) throw readerAbortError();
|
| 3980 |
const base = page.getViewport({ scale: 1 }),
|
| 3981 |
+
scale = Math.min(3, shell.clientWidth / base.width),
|
| 3982 |
viewport = page.getViewport({ scale }),
|
| 3983 |
outputScale = Math.min(2, Math.max(1, Number(window.devicePixelRatio) || 1));
|
| 3984 |
const canvas = shell.querySelector("canvas");
|
|
|
|
| 4009 |
if (!isReaderGenerationCurrent("pdf", generation)) shell.dataset.pendingRerender = "1";
|
| 4010 |
} while (shell.dataset.pendingRerender);
|
| 4011 |
shell.querySelector("canvas").classList.add("ready");
|
| 4012 |
+
const pageState = shell.querySelector(".reader-page-state");
|
| 4013 |
+
if (pageState) pageState.hidden = true;
|
| 4014 |
shell.dataset.renderState = "rendered";
|
| 4015 |
shell.dataset.renderUsedAt = String(Date.now());
|
| 4016 |
pdfShellWindow?.remember(shell);
|
|
|
|
| 4141 |
function releasePdfRenderSlot() {
|
| 4142 |
pdfActiveRenders = Math.max(0, pdfActiveRenders - 1);
|
| 4143 |
if (readerAbortController.signal.aborted) return;
|
| 4144 |
+
let index = -1, best = -1, nearest = Infinity;
|
| 4145 |
for (let i = 0; i < pdfRenderWaiters.length; i++) {
|
| 4146 |
+
const waiter = pdfRenderWaiters[i], value = waiter.shell ? pdfPagePriority(waiter.shell) : waiter.priority;
|
| 4147 |
+
const rect = waiter.shell?.getBoundingClientRect(), bounds = viewport.getBoundingClientRect();
|
| 4148 |
+
const distance = rect ? Math.max(bounds.top - rect.bottom, rect.top - bounds.bottom, 0) : Infinity;
|
| 4149 |
+
if (value > best || (value === best && distance < nearest)) {
|
| 4150 |
+
best = value; nearest = distance; index = i;
|
| 4151 |
+
}
|
| 4152 |
}
|
| 4153 |
if (index < 0) index = 0;
|
| 4154 |
const waiter = pdfRenderWaiters.splice(index, 1)[0];
|
|
|
|
| 4452 |
}
|
| 4453 |
async function renderPlainText(response) {
|
| 4454 |
assertReaderActive();
|
| 4455 |
+
const pre = document.createElement("div");
|
| 4456 |
pre.className = "reader-text";
|
| 4457 |
content.appendChild(pre);
|
| 4458 |
+
let block = null, blockLength = 0;
|
| 4459 |
+
const appendDecoded = value => {
|
| 4460 |
+
let text = value.replace(/\ufffd/g, "");
|
| 4461 |
+
while (text) {
|
| 4462 |
+
if (!block) {
|
| 4463 |
+
block = document.createElement("pre");
|
| 4464 |
+
block.className = "reader-text-block";
|
| 4465 |
+
pre.appendChild(block);
|
| 4466 |
+
}
|
| 4467 |
+
const boundary = text.indexOf("\n", Math.max(0, 32768 - blockLength));
|
| 4468 |
+
const take = boundary < 0 ? text.length : boundary + 1;
|
| 4469 |
+
const tail = block.lastChild;
|
| 4470 |
+
if (tail?.nodeType === Node.TEXT_NODE) tail.appendData(text.slice(0, take));
|
| 4471 |
+
else block.appendChild(document.createTextNode(text.slice(0, take)));
|
| 4472 |
+
blockLength += take;
|
| 4473 |
+
text = text.slice(take);
|
| 4474 |
+
if (boundary >= 0) { block = null; blockLength = 0; }
|
| 4475 |
+
}
|
| 4476 |
+
};
|
| 4477 |
const limit = VoiceOfMLReaderSecurity.LIMITS.documentBytes;
|
| 4478 |
VoiceOfMLReaderSecurity.assertResponseSize(response, limit);
|
| 4479 |
if (!response.body?.getReader) {
|
|
|
|
| 4484 |
throw error;
|
| 4485 |
}
|
| 4486 |
assertReaderActive();
|
| 4487 |
+
appendDecoded(new TextDecoder(detectTextEncoding(bytes, documentState.title)).decode(bytes));
|
|
|
|
|
|
|
| 4488 |
return;
|
| 4489 |
}
|
| 4490 |
const reader = response.body.getReader(),
|
|
|
|
| 4501 |
decoder = null,
|
| 4502 |
asciiPreviewPossible = true,
|
| 4503 |
asciiPrefixLength = 0;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4504 |
const startDecoder = () => {
|
| 4505 |
const sample = new Uint8Array(sampleLength);
|
| 4506 |
let offset = 0;
|
|
|
|
| 4535 |
if (value[asciiLength] === 0) {
|
| 4536 |
// A split UTF-16 prefix must not leave an ASCII preview behind.
|
| 4537 |
pre.textContent = "";
|
| 4538 |
+
block = null;
|
| 4539 |
+
blockLength = 0;
|
| 4540 |
displayedSampleSize = 0;
|
| 4541 |
asciiPrefixLength = 0;
|
| 4542 |
asciiPreviewPossible = false;
|
|
|
|
| 5059 |
throw new Error("DOCX rendered no supported content");
|
| 5060 |
}
|
| 5061 |
const pages = [...body.querySelectorAll(":scope > .reader-docx-wrapper > section.reader-docx")];
|
| 5062 |
+
docxPageNodes = pages;
|
| 5063 |
if (pages.length) {
|
| 5064 |
updateDocumentState({ pageCount: pages.length });
|
| 5065 |
pageInput.max = String(documentState.pageCount);
|
|
|
|
| 6753 |
fullSearchDomSnapshot?.resume();
|
| 6754 |
}
|
| 6755 |
}
|
| 6756 |
+
async function fullSearchTextNodes(root, generation, endOffset = Infinity, checkpoint = null, collect = null) {
|
| 6757 |
const nodes = [],
|
| 6758 |
walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
| 6759 |
if (checkpoint) walker.currentNode = checkpoint.target;
|
| 6760 |
+
let visited = 0, length = checkpoint?.start || 0, deadline = performance.now() + 8;
|
| 6761 |
while (walker.nextNode()) {
|
| 6762 |
if (!isReaderGenerationCurrent("search", generation)) return null;
|
| 6763 |
const node = walker.currentNode;
|
|
|
|
| 6765 |
node.data &&
|
| 6766 |
!node.parentElement.closest("script,style,mark.full-search-highlight,.reader-pdf-text")
|
| 6767 |
) {
|
| 6768 |
+
if (collect) collect(node);
|
| 6769 |
+
else nodes.push(node);
|
| 6770 |
length += node.data.length;
|
| 6771 |
if (length >= endOffset) break;
|
| 6772 |
}
|
| 6773 |
+
if (++visited % 256 === 0 && performance.now() >= deadline) {
|
| 6774 |
+
await waitForReader();
|
| 6775 |
+
deadline = performance.now() + 8;
|
| 6776 |
+
}
|
| 6777 |
}
|
| 6778 |
return nodes;
|
| 6779 |
}
|
|
|
|
| 6884 |
fullSearchDomSnapshot.value?.toc === navigationState.tocEntries ? fullSearchDomSnapshot.value : null;
|
| 6885 |
const snapshot = progressive ? (cached ? fullSearchDomSnapshot : createDomSearchSnapshot(root)) : null;
|
| 6886 |
const locator = progressive ? createFullSearchDomLocator(root, generation) : null;
|
|
|
|
|
|
|
| 6887 |
const offsets = cached ? cached.offsets : [],
|
| 6888 |
chunks = [];
|
| 6889 |
let length = 0;
|
| 6890 |
+
const collect = node => {
|
| 6891 |
offsets.push({ node, parent: node.parentElement, start: length, end: length + node.data.length });
|
| 6892 |
chunks.push(node.data);
|
| 6893 |
length += node.data.length;
|
| 6894 |
+
};
|
| 6895 |
+
const nodes = cached ? [] : await fullSearchTextNodes(root, generation, Infinity, null, collect);
|
| 6896 |
+
if (!nodes || !isReaderGenerationCurrent("search", generation)) return [];
|
|
|
|
|
|
|
| 6897 |
if (cached) locator?.seed(cached.checkpoints);
|
| 6898 |
else locator?.build(offsets);
|
| 6899 |
const headingLookup = cached ? cached.headingLookup : createFullSearchHeadingLookup(root, offsets);
|
tests/test_reader_architecture.js
CHANGED
|
@@ -53,9 +53,9 @@ assert.match(reader, /promotePdfRenderWaiter\(shell\)/)
|
|
| 53 |
assert.match(reader, /function pdfPagePriority\(shell\)/)
|
| 54 |
assert.match(reader, /priority >= 3 \? "high" : priority >= 1 \? "auto" : "low"/)
|
| 55 |
assert.match(reader, /const waiter = \{\s*shell,\s*priority,/)
|
| 56 |
-
assert.match(reader, /waiter\.
|
| 57 |
assert.match(reader, /function cancelSpeculativePdfRenders\(protectedShell\)/)
|
| 58 |
-
assert.match(reader, /shell\
|
| 59 |
assert.match(reader, /shell\._renderCancel\?\.\(\)/)
|
| 60 |
assert.match(reader, /const PDF_MANIFEST_PREFETCH_LIMIT = 12/)
|
| 61 |
assert.match(reader, /const PDF_MANIFEST_PREFETCH_CONCURRENCY = 3/)
|
|
|
|
| 53 |
assert.match(reader, /function pdfPagePriority\(shell\)/)
|
| 54 |
assert.match(reader, /priority >= 3 \? "high" : priority >= 1 \? "auto" : "low"/)
|
| 55 |
assert.match(reader, /const waiter = \{\s*shell,\s*priority,/)
|
| 56 |
+
assert.match(reader, /waiter\.shell \? pdfPagePriority\(waiter\.shell\) : waiter\.priority/)
|
| 57 |
assert.match(reader, /function cancelSpeculativePdfRenders\(protectedShell\)/)
|
| 58 |
+
assert.match(reader, /isPdfPageVisible\(shell\)/)
|
| 59 |
assert.match(reader, /shell\._renderCancel\?\.\(\)/)
|
| 60 |
assert.match(reader, /const PDF_MANIFEST_PREFETCH_LIMIT = 12/)
|
| 61 |
assert.match(reader, /const PDF_MANIFEST_PREFETCH_CONCURRENCY = 3/)
|
tests/test_reader_close_traffic.py
CHANGED
|
@@ -145,7 +145,10 @@ class ReaderCloseTrafficTests(unittest.TestCase):
|
|
| 145 |
send('pointerdown', action==='secondary'?{isPrimary:false}:{});
|
| 146 |
if (action==='drag') send('pointermove',{clientX:120});
|
| 147 |
if (action==='cancel') send('pointercancel');
|
| 148 |
-
if (action==='changed')
|
|
|
|
|
|
|
|
|
|
| 149 |
send('pointerup');
|
| 150 |
output.push(!!selection.toString());
|
| 151 |
}
|
|
|
|
| 145 |
send('pointerdown', action==='secondary'?{isPrimary:false}:{});
|
| 146 |
if (action==='drag') send('pointermove',{clientX:120});
|
| 147 |
if (action==='cancel') send('pointercancel');
|
| 148 |
+
if (action==='changed') {
|
| 149 |
+
const text = node.ownerDocument.createTreeWalker(node, NodeFilter.SHOW_TEXT).nextNode();
|
| 150 |
+
selection.setBaseAndExtent(text, 0, text, Math.min(3, text.data.length));
|
| 151 |
+
}
|
| 152 |
send('pointerup');
|
| 153 |
output.push(!!selection.toString());
|
| 154 |
}
|
tests/test_reader_ocr_transport.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from 'node:assert/strict';
|
| 2 |
+
import fs from 'node:fs';
|
| 3 |
+
import vm from 'node:vm';
|
| 4 |
+
|
| 5 |
+
const source=fs.readFileSync(new URL('../static/reader-pdf-book-search-worker.mjs',import.meta.url),'utf8');
|
| 6 |
+
const start=source.indexOf('async function readBounded('), end=source.indexOf('\nasync function loadBook()',start);
|
| 7 |
+
const read=vm.runInNewContext('const limit=1024; const aborted=()=>new DOMException("cancelled","AbortError");'+
|
| 8 |
+
source.slice(start,end)+';readBounded',{TextDecoder,Uint8Array,DOMException});
|
| 9 |
+
const stream=chunks=>new ReadableStream({start(controller){for(const chunk of chunks)controller.enqueue(chunk);controller.close();}});
|
| 10 |
+
const signal=new AbortController().signal;
|
| 11 |
+
const text='手机 😀 كتاب';
|
| 12 |
+
const bytes=new TextEncoder().encode(text);
|
| 13 |
+
assert.equal(await read(stream([...bytes].map(byte=>Uint8Array.of(byte))),signal,null,true),text);
|
| 14 |
+
assert.deepEqual(Array.from(await read(stream([bytes.subarray(0,3),bytes.subarray(3)]),signal,bytes.length)),Array.from(bytes));
|
| 15 |
+
await assert.rejects(()=>read(stream([bytes.subarray(0,3)]),signal,bytes.length),/SIZE_MISMATCH/);
|
| 16 |
+
await assert.rejects(()=>read(stream([bytes]),signal,3),/RESOURCE_LIMIT/);
|
| 17 |
+
await assert.rejects(()=>read(stream([new Uint8Array(1025)]),signal,null,true),/RESOURCE_LIMIT/);
|
| 18 |
+
const controller=new AbortController();controller.abort();
|
| 19 |
+
await assert.rejects(()=>read(stream([bytes]),controller.signal,null,true),error=>error.name==='AbortError');
|
| 20 |
+
console.log('OCR transport byte bounds, split Unicode and cancellation passed');
|
tests/test_reader_optimizations.py
CHANGED
|
@@ -31,6 +31,7 @@ class ReaderOptimizationTests(unittest.TestCase):
|
|
| 31 |
chapterManifestCleanup = () => {''')
|
| 32 |
route.fulfill(response=response, body=script + '''
|
| 33 |
window.__snapshot = () => fullSearchDomSnapshot;
|
|
|
|
| 34 |
window.__pdfTools = {trim: trimPdfSurfaces, pixels: pdfRetainedPixels, budget: pdfPixelBudget,
|
| 35 |
prefetch: pdfManifestPrefetches, setPage: page => updateDocumentState({page})};
|
| 36 |
window.__startPdfProbe = () => {
|
|
@@ -88,6 +89,7 @@ class ReaderOptimizationTests(unittest.TestCase):
|
|
| 88 |
__pdfTools.setPage(1);
|
| 89 |
for (let page=1; page<=8; page++) {
|
| 90 |
const shell=document.createElement('div'); shell.className='reader-page';
|
|
|
|
| 91 |
shell.dataset.page=page; shell.dataset.renderState='rendered';
|
| 92 |
const canvas=document.createElement('canvas'); canvas.className='ready';
|
| 93 |
canvas.width=2400; canvas.height=3400;
|
|
@@ -108,10 +110,11 @@ class ReaderOptimizationTests(unittest.TestCase):
|
|
| 108 |
prefetched.src='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
|
| 109 |
__pdfTools.prefetch.set('fixture', {image:prefetched, url:'fixture'});
|
| 110 |
__pdfTools.trim(root.firstChild);
|
|
|
|
| 111 |
const protectedSelection=selected.querySelector('canvas').width===2400 && getSelection().getRangeAt(0).toString()==='page 2';
|
| 112 |
const prefetchedReleased=!prefetched.hasAttribute('src') && __pdfTools.prefetch.size===0;
|
| 113 |
getSelection().removeAllRanges(); __pdfTools.trim(root.firstChild);
|
| 114 |
-
return {protectedSelection,prefetchedReleased,pixels:__pdfTools.pixels(),budget:__pdfTools.budget(),
|
| 115 |
retained:root.firstChild.querySelector('canvas').width,
|
| 116 |
released:[...root.children].filter(shell=>!shell.querySelector('canvas.ready, img')).length};
|
| 117 |
}''')
|
|
@@ -120,6 +123,47 @@ class ReaderOptimizationTests(unittest.TestCase):
|
|
| 120 |
self.assertEqual(result['retained'], 2400)
|
| 121 |
self.assertGreaterEqual(result['released'], 5)
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
def test_pdf_parallel_search_reserves_demand_slot_and_cancels_stale_totals(self):
|
| 124 |
self.expose()
|
| 125 |
self.serve('search scheduling fixture')
|
|
@@ -156,6 +200,11 @@ class ReaderOptimizationTests(unittest.TestCase):
|
|
| 156 |
self.open(self.docx_url())
|
| 157 |
pages = self.page.locator('.reader-docx-page')
|
| 158 |
self.assertEqual(pages.count(), 20)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
self.assertEqual(pages.last.evaluate('e => getComputedStyle(e).contentVisibility'), 'auto')
|
| 160 |
self.page.evaluate('() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))')
|
| 161 |
self.assertFalse(pages.last.evaluate('e => e.firstElementChild.checkVisibility({contentVisibilityAuto:true})'))
|
|
|
|
| 31 |
chapterManifestCleanup = () => {''')
|
| 32 |
route.fulfill(response=response, body=script + '''
|
| 33 |
window.__snapshot = () => fullSearchDomSnapshot;
|
| 34 |
+
window.__markerPage = () => pageAtMarker()?.dataset.page;
|
| 35 |
window.__pdfTools = {trim: trimPdfSurfaces, pixels: pdfRetainedPixels, budget: pdfPixelBudget,
|
| 36 |
prefetch: pdfManifestPrefetches, setPage: page => updateDocumentState({page})};
|
| 37 |
window.__startPdfProbe = () => {
|
|
|
|
| 89 |
__pdfTools.setPage(1);
|
| 90 |
for (let page=1; page<=8; page++) {
|
| 91 |
const shell=document.createElement('div'); shell.className='reader-page';
|
| 92 |
+
shell.style.height='1200px';
|
| 93 |
shell.dataset.page=page; shell.dataset.renderState='rendered';
|
| 94 |
const canvas=document.createElement('canvas'); canvas.className='ready';
|
| 95 |
canvas.width=2400; canvas.height=3400;
|
|
|
|
| 110 |
prefetched.src='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
|
| 111 |
__pdfTools.prefetch.set('fixture', {image:prefetched, url:'fixture'});
|
| 112 |
__pdfTools.trim(root.firstChild);
|
| 113 |
+
const nearestRetained=!!root.children[2].querySelector('canvas.ready');
|
| 114 |
const protectedSelection=selected.querySelector('canvas').width===2400 && getSelection().getRangeAt(0).toString()==='page 2';
|
| 115 |
const prefetchedReleased=!prefetched.hasAttribute('src') && __pdfTools.prefetch.size===0;
|
| 116 |
getSelection().removeAllRanges(); __pdfTools.trim(root.firstChild);
|
| 117 |
+
return {protectedSelection,prefetchedReleased,nearestRetained,pixels:__pdfTools.pixels(),budget:__pdfTools.budget(),
|
| 118 |
retained:root.firstChild.querySelector('canvas').width,
|
| 119 |
released:[...root.children].filter(shell=>!shell.querySelector('canvas.ready, img')).length};
|
| 120 |
}''')
|
|
|
|
| 123 |
self.assertEqual(result['retained'], 2400)
|
| 124 |
self.assertGreaterEqual(result['released'], 5)
|
| 125 |
|
| 126 |
+
def test_mobile_large_page_pdf_keeps_nearby_canvases_at_display_resolution(self):
|
| 127 |
+
self.context.close()
|
| 128 |
+
self.context = self.browser.new_context(viewport=dict(width=390,height=844),device_scale_factor=3)
|
| 129 |
+
self.page = self.context.new_page()
|
| 130 |
+
self.page.add_init_script("Object.defineProperty(navigator,'deviceMemory',{value:2});window.__renderedPages=[];")
|
| 131 |
+
engine = '''export const GlobalWorkerOptions={};export class PDFWorker {promise=Promise.resolve();destroy(){}}
|
| 132 |
+
export function getDocument(){return {promise:Promise.resolve({numPages:40,getOutline:async()=>null,
|
| 133 |
+
getPage:async number=>({getViewport:({scale})=>({width:1274*scale,height:1828*scale}),
|
| 134 |
+
getTextContent:async()=>({items:[],styles:{}}),render:({canvasContext})=>{
|
| 135 |
+
__renderedPages.push(number);canvasContext.fillStyle='white';canvasContext.fillRect(0,0,4000,6000);
|
| 136 |
+
return {promise:Promise.resolve(),cancel(){}};}})}),destroy(){}};}'''
|
| 137 |
+
self.page.route('**/static/vendor/pdf.min.*.mjs',lambda route:route.fulfill(content_type='text/javascript',body=engine))
|
| 138 |
+
self.serve(b'pdf','application/pdf')
|
| 139 |
+
self.open(self.reader_url('pdf'))
|
| 140 |
+
self.page.wait_for_function('() => !!document.querySelector(".reader-page[data-page=\\"4\\"] canvas.ready")')
|
| 141 |
+
self.page.wait_for_timeout(150)
|
| 142 |
+
data = self.page.locator('.reader-page[data-page="1"]').evaluate('''shell=>{
|
| 143 |
+
const canvas=shell.querySelector('canvas');return {css:shell.clientWidth,backing:canvas.width,
|
| 144 |
+
next:[2,3,4].map(page=>!!document.querySelector('.reader-page[data-page="'+page+'"] canvas.ready'))};}''')
|
| 145 |
+
self.assertLessEqual(data['backing'],data['css']*2+1,data)
|
| 146 |
+
self.assertTrue(all(data['next']),data)
|
| 147 |
+
self.page.evaluate('''()=>{const shell=document.querySelector('.reader-page[data-page="3"]'),v=document.querySelector('#viewport');
|
| 148 |
+
window.__thirdCount=__renderedPages.filter(page=>page===3).length;v.scrollTop+=shell.getBoundingClientRect().top-v.getBoundingClientRect().top;}''')
|
| 149 |
+
self.page.wait_for_timeout(150)
|
| 150 |
+
self.assertEqual(self.page.evaluate('__renderedPages.filter(page=>page===3).length'),self.page.evaluate('__thirdCount'))
|
| 151 |
+
|
| 152 |
+
def test_long_txt_blocks_preserve_exact_text_cross_block_hits_and_selection(self):
|
| 153 |
+
self.expose()
|
| 154 |
+
text=('ordinary line\n'*2400)+'needle\n'+('tail line\n'*6000)+'needle\n'
|
| 155 |
+
self.serve(text)
|
| 156 |
+
self.open(self.reader_url('txt'))
|
| 157 |
+
self.assertEqual(self.page.locator('.reader-text').text_content(),text)
|
| 158 |
+
self.assertGreater(self.page.locator('.reader-text-block').count(),2)
|
| 159 |
+
self.assertEqual(self.page.evaluate('__query("needle")'),2)
|
| 160 |
+
self.search('needle')
|
| 161 |
+
self.page.locator('.full-search-result').last.click()
|
| 162 |
+
self.assertEqual(self.page.locator('mark.full-search-highlight').text_content(),'needle')
|
| 163 |
+
self.assertEqual(self.page.locator('.reader-text').text_content(),text)
|
| 164 |
+
self.assertEqual(self.page.locator('.reader-text').evaluate('''root=>{const range=document.createRange();range.selectNodeContents(root);
|
| 165 |
+
getSelection().removeAllRanges();getSelection().addRange(range);return range.toString();}'''),text)
|
| 166 |
+
|
| 167 |
def test_pdf_parallel_search_reserves_demand_slot_and_cancels_stale_totals(self):
|
| 168 |
self.expose()
|
| 169 |
self.serve('search scheduling fixture')
|
|
|
|
| 200 |
self.open(self.docx_url())
|
| 201 |
pages = self.page.locator('.reader-docx-page')
|
| 202 |
self.assertEqual(pages.count(), 20)
|
| 203 |
+
marker = self.page.evaluate('''()=>{let reads=0;const pages=[...document.querySelectorAll('.reader-docx-page')];
|
| 204 |
+
for(const page of pages){const native=page.getBoundingClientRect.bind(page);page.getBoundingClientRect=()=>{reads++;return native();};}
|
| 205 |
+
const actual=__markerPage();return {actual,reads};}''')
|
| 206 |
+
self.assertEqual(marker['actual'],'1')
|
| 207 |
+
self.assertLessEqual(marker['reads'],6)
|
| 208 |
self.assertEqual(pages.last.evaluate('e => getComputedStyle(e).contentVisibility'), 'auto')
|
| 209 |
self.page.evaluate('() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))')
|
| 210 |
self.assertFalse(pages.last.evaluate('e => e.firstElementChild.checkVisibility({contentVisibilityAuto:true})'))
|
tests/test_reader_refactor.py
CHANGED
|
@@ -1121,7 +1121,7 @@ class ReaderRefactorTest(unittest.TestCase):
|
|
| 1121 |
def test_stale_foliate_fallback_cannot_highlight_after_navigation(self):
|
| 1122 |
def hold_fallback(route):
|
| 1123 |
response = route.fetch()
|
| 1124 |
-
needle = "const nodes = cached ? [] : await fullSearchTextNodes(root, generation);"
|
| 1125 |
script = response.text()
|
| 1126 |
self.assertIn(needle, script)
|
| 1127 |
script = script.replace(needle, """if (occurrence !== null && !window.__fallbackHeld) {
|
|
|
|
| 1121 |
def test_stale_foliate_fallback_cannot_highlight_after_navigation(self):
|
| 1122 |
def hold_fallback(route):
|
| 1123 |
response = route.fetch()
|
| 1124 |
+
needle = "const nodes = cached ? [] : await fullSearchTextNodes(root, generation, Infinity, null, collect);"
|
| 1125 |
script = response.text()
|
| 1126 |
self.assertIn(needle, script)
|
| 1127 |
script = script.replace(needle, """if (occurrence !== null && !window.__fallbackHeld) {
|