vomebook commited on
Commit ·
d6f7739
1
Parent(s): d3655e4
Normalize TXT paragraph spacing and build a chapter outline
Browse files- scripts/reader/check_reader_text_coverage.mjs +2 -0
- static/reader.css +5 -3
- static/reader/formats/reader-html-format.mjs +0 -12
- static/reader/formats/reader-text-format.mjs +102 -5
- static/reader/search/reader-dom-search.mjs +9 -4
- static/reader/ui/reader-speech.mjs +24 -3
- tests/reader/browser/test_reader_refactor.py +37 -8
- tests/reader/browser/test_reader_speech.py +23 -0
- tests/reader/dom-search/contracts.mjs +9 -0
- tests/reader/text/test_reader_text_baseline.mjs +40 -1
scripts/reader/check_reader_text_coverage.mjs
CHANGED
|
@@ -4,6 +4,8 @@ import {hasCompleteFlatTapReport, hasPassingTapContracts} from '../check_tap_con
|
|
| 4 |
|
| 5 |
const minimum = [100, 91.89, 90.91];
|
| 6 |
const required = [
|
|
|
|
|
|
|
| 7 |
'encoding detection handles BOMs, valid UTF-8, UTF-16 heuristics and legacy hints',
|
| 8 |
'plain fallback preserves Unicode replacement characters and enforces actual byte limit',
|
| 9 |
'stream handles split UTF-8 BOM and codepoints and releases its resource',
|
|
|
|
| 4 |
|
| 5 |
const minimum = [100, 91.89, 90.91];
|
| 6 |
const required = [
|
| 7 |
+
'TXT layout retains raw text across streaming chunks, including hidden whitespace and chapters',
|
| 8 |
+
'TXT layout leaves ordinary indents and one or two blank lines alone, and caps decoration',
|
| 9 |
'encoding detection handles BOMs, valid UTF-8, UTF-16 heuristics and legacy hints',
|
| 10 |
'plain fallback preserves Unicode replacement characters and enforces actual byte limit',
|
| 11 |
'stream handles split UTF-8 BOM and codepoints and releases its resource',
|
static/reader.css
CHANGED
|
@@ -1228,9 +1228,11 @@ body {
|
|
| 1228 |
.reader-text-block:focus-within {
|
| 1229 |
content-visibility: visible;
|
| 1230 |
}
|
| 1231 |
-
.reader-
|
| 1232 |
-
|
| 1233 |
-
|
|
|
|
|
|
|
| 1234 |
}
|
| 1235 |
.reader-markdown {
|
| 1236 |
margin: 0 auto;
|
|
|
|
| 1228 |
.reader-text-block:focus-within {
|
| 1229 |
content-visibility: visible;
|
| 1230 |
}
|
| 1231 |
+
.reader-text .reader-text-padding {
|
| 1232 |
+
display: none;
|
| 1233 |
+
}
|
| 1234 |
+
.reader-text .reader-text-chapter-title {
|
| 1235 |
+
font-weight: 700;
|
| 1236 |
}
|
| 1237 |
.reader-markdown {
|
| 1238 |
margin: 0 auto;
|
static/reader/formats/reader-html-format.mjs
CHANGED
|
@@ -487,24 +487,12 @@ export function createReaderHtmlFormat(readerContext) {
|
|
| 487 |
});
|
| 488 |
}
|
| 489 |
|
| 490 |
-
function readingAssetPath() {
|
| 491 |
-
try {
|
| 492 |
-
const url = new URL(readerContext.sourceUrl, location.href);
|
| 493 |
-
return url.searchParams.get("path") || url.pathname.replace(/^\//, "");
|
| 494 |
-
} catch (_) { return ""; }
|
| 495 |
-
}
|
| 496 |
-
|
| 497 |
/** @param {boolean} markdown @param {import('../../../typings/reader-html-format-strict').PreparedText} prepared */
|
| 498 |
async function renderText(markdown, prepared) {
|
| 499 |
let response = await prepared.response;
|
| 500 |
if (!response.ok) response = await readerContext.fetchReaderResponse();
|
| 501 |
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
| 502 |
if (!markdown) {
|
| 503 |
-
// This legacy article pads nearly every line with 12–26 spaces. Compact
|
| 504 |
-
// only its presentation, keeping search, text offsets and download intact.
|
| 505 |
-
readerContext.content.classList.toggle("reader-content--compact-text", readingAssetPath() ===
|
| 506 |
-
"documents/text/txt/63fa4ecf73e28346a33704c8adbacebaec293f6f649d96590f066fd42187d97c/document.txt"
|
| 507 |
-
);
|
| 508 |
await readerContext.renderPlainText(response);
|
| 509 |
} else {
|
| 510 |
const bytes = await readerContext.readPreparedBytes(response, prepared.engines);
|
|
|
|
| 487 |
});
|
| 488 |
}
|
| 489 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 490 |
/** @param {boolean} markdown @param {import('../../../typings/reader-html-format-strict').PreparedText} prepared */
|
| 491 |
async function renderText(markdown, prepared) {
|
| 492 |
let response = await prepared.response;
|
| 493 |
if (!response.ok) response = await readerContext.fetchReaderResponse();
|
| 494 |
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
| 495 |
if (!markdown) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 496 |
await readerContext.renderPlainText(response);
|
| 497 |
} else {
|
| 498 |
const bytes = await readerContext.readPreparedBytes(response, prepared.engines);
|
static/reader/formats/reader-text-format.mjs
CHANGED
|
@@ -15,16 +15,22 @@
|
|
| 15 |
* @property {(bytes: Uint8Array, hint?: string, leading?: boolean) => string} detectTextEncoding
|
| 16 |
* @property {{title: string}} documentState
|
| 17 |
* @property {ReaderTextRenderer} renderText
|
|
|
|
| 18 |
* @typedef {ReaderTextHost & ReaderOriginalFormat} ReaderTextContext
|
| 19 |
*/
|
| 20 |
|
| 21 |
const VCARD_PREVIEW_BYTES = 64 * 1024;
|
| 22 |
|
| 23 |
/** @param {ReaderOriginalFormat} context */
|
| 24 |
-
|
| 25 |
const original = context.resolvedReaderData?.original_extension;
|
| 26 |
const extension = typeof original === "string" && original ? original : context.extension;
|
| 27 |
-
return extension?.toLowerCase().replace(/^\./, "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
}
|
| 29 |
|
| 30 |
const vCardLabels = new Map([
|
|
@@ -78,6 +84,89 @@ function formatVCard(text) {
|
|
| 78 |
return fields.filter(field => !hasFullName || field.key !== "N").map(field => field.text).join("\n");
|
| 79 |
}
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
/** @param {ReaderTextContext} readerContext */
|
| 82 |
export function createReaderTextFormat(readerContext) {
|
| 83 |
/** @param {Response} response */
|
|
@@ -124,7 +213,15 @@ export function createReaderTextFormat(readerContext) {
|
|
| 124 |
}
|
| 125 |
}
|
| 126 |
};
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
readerContext.assertReaderActive();
|
| 129 |
const summary = formatVCard(pre.textContent ?? "");
|
| 130 |
if (summary !== null) {
|
|
@@ -162,7 +259,7 @@ export function createReaderTextFormat(readerContext) {
|
|
| 162 |
const decoder = new TextDecoder(readerContext.detectTextEncoding(bytes.subarray(start, start + sampleLimit),
|
| 163 |
readerContext.documentState.title, start === 0));
|
| 164 |
await appendDecoded(decoder.decode(bytes), decoder.encoding);
|
| 165 |
-
|
| 166 |
return;
|
| 167 |
}
|
| 168 |
const reader = response.body.getReader(),
|
|
@@ -321,7 +418,7 @@ export function createReaderTextFormat(readerContext) {
|
|
| 321 |
// startDecoder assigns one even for an empty sample. A failure is caught.
|
| 322 |
if (!decoder) await startDecoder();
|
| 323 |
await appendDecoded((/** @type {TextDecoder} */ (/** @type {unknown} */ (decoder))).decode(), (/** @type {TextDecoder} */ (/** @type {unknown} */ (decoder))).encoding);
|
| 324 |
-
|
| 325 |
} catch (reason) {
|
| 326 |
clearUtf8Preview();
|
| 327 |
try {
|
|
|
|
| 15 |
* @property {(bytes: Uint8Array, hint?: string, leading?: boolean) => string} detectTextEncoding
|
| 16 |
* @property {{title: string}} documentState
|
| 17 |
* @property {ReaderTextRenderer} renderText
|
| 18 |
+
* @property {(entries: {label: string; depth: number; target: HTMLElement; activate(): void}[]) => void} setToc
|
| 19 |
* @typedef {ReaderTextHost & ReaderOriginalFormat} ReaderTextContext
|
| 20 |
*/
|
| 21 |
|
| 22 |
const VCARD_PREVIEW_BYTES = 64 * 1024;
|
| 23 |
|
| 24 |
/** @param {ReaderOriginalFormat} context */
|
| 25 |
+
function originalTextExtension(context) {
|
| 26 |
const original = context.resolvedReaderData?.original_extension;
|
| 27 |
const extension = typeof original === "string" && original ? original : context.extension;
|
| 28 |
+
return extension?.toLowerCase().replace(/^\./, "");
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
/** @param {ReaderOriginalFormat} context */
|
| 32 |
+
export function isReaderVCard(context) {
|
| 33 |
+
return originalTextExtension(context) === "vcf";
|
| 34 |
}
|
| 35 |
|
| 36 |
const vCardLabels = new Map([
|
|
|
|
| 84 |
return fields.filter(field => !hasFullName || field.key !== "N").map(field => field.text).join("\n");
|
| 85 |
}
|
| 86 |
|
| 87 |
+
// Apply layout only to bounded TXT documents, after decoding and before restoring
|
| 88 |
+
// the position. Never replace the text used by search, speech or the original download.
|
| 89 |
+
const TXT_LAYOUT_BYTES = 128 * 1024;
|
| 90 |
+
const TXT_LAYOUT_EDITS = 1024;
|
| 91 |
+
const TXT_CHAPTER = /^第[ \u3000]*[\d0-9〇零一二三四五六七八九十百千万两]+[ \u3000]*([卷部篇章节回])(?:$|[ \t\u3000..::、—–-]+[^\r\n]+$)/u;
|
| 92 |
+
|
| 93 |
+
/** @typedef {{ start: number; end: number; heading?: string; depth?: number }} TextLayoutEdit */
|
| 94 |
+
/** @param {string} text */
|
| 95 |
+
function planTextLayout(text) {
|
| 96 |
+
/** @type {TextLayoutEdit[]} */
|
| 97 |
+
const indents = [], gaps = [], headings = [];
|
| 98 |
+
let total = 0, padded = 0, prose = 0, blankLines = 0;
|
| 99 |
+
/** @type {TextLayoutEdit | null} */
|
| 100 |
+
let gap = null;
|
| 101 |
+
for (const line of text.matchAll(/[^\r\n]*(?:\r\n|\r|\n|$)/g)) {
|
| 102 |
+
const raw = line[0], start = line.index;
|
| 103 |
+
if (!raw) break;
|
| 104 |
+
const label = raw.trim();
|
| 105 |
+
if (!label) {
|
| 106 |
+
if (gap) gap.end = start + raw.length;
|
| 107 |
+
else if (++blankLines === 3) {
|
| 108 |
+
gap = { start, end: start + raw.length };
|
| 109 |
+
gaps.push(gap);
|
| 110 |
+
}
|
| 111 |
+
} else {
|
| 112 |
+
blankLines = 0;
|
| 113 |
+
gap = null;
|
| 114 |
+
total++;
|
| 115 |
+
if (label.length >= 16 && /[。!?;,、]|[.!?;](?:\s|$)/u.test(label)) prose++;
|
| 116 |
+
const indent = /^[ \u3000]{8,}/u.exec(raw)?.[0];
|
| 117 |
+
if (indent) {
|
| 118 |
+
padded++;
|
| 119 |
+
indents.push({ start: start + 2, end: start + indent.length });
|
| 120 |
+
}
|
| 121 |
+
const kind = label.length <= 72 ? TXT_CHAPTER.exec(label)?.[1] : null;
|
| 122 |
+
if (kind && !/[。!?;!?]$/u.test(label)) {
|
| 123 |
+
const titleStart = start + raw.indexOf(label);
|
| 124 |
+
headings.push({ start: titleStart, end: titleStart + label.length, heading: label, depth: kind === "节" ? 1 : 0 });
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
if (indents.length + gaps.length + headings.length > TXT_LAYOUT_EDITS) return [];
|
| 128 |
+
}
|
| 129 |
+
// A few indented lines are not a padding convention. Require recurring long
|
| 130 |
+
// indents and sentence-like prose; keep meaningful whitespace in code/tables.
|
| 131 |
+
const compact = total >= 8 && padded * 4 >= total * 3 && prose >= 3;
|
| 132 |
+
return [...(compact ? indents : []), ...gaps, ...headings].sort((a, b) => a.start - b.start);
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
/** @param {HTMLElement} root */
|
| 136 |
+
function typesetPlainText(root) {
|
| 137 |
+
const edits = planTextLayout(root.textContent ?? "");
|
| 138 |
+
/** @type {{label: string; depth: number; target: HTMLElement; activate(): void}[]} */
|
| 139 |
+
const toc = [];
|
| 140 |
+
let from = 0, editIndex = 0;
|
| 141 |
+
for (const block of root.children) {
|
| 142 |
+
const text = block.textContent ?? "", to = from + text.length;
|
| 143 |
+
if ((edits[editIndex]?.start ?? Infinity) < to) {
|
| 144 |
+
/** @type {Node[]} */
|
| 145 |
+
const nodes = [];
|
| 146 |
+
let cursor = from;
|
| 147 |
+
for (let edit; (edit = edits[editIndex]) && edit.start < to;) {
|
| 148 |
+
const begin = Math.max(from, edit.start), end = Math.min(to, edit.end);
|
| 149 |
+
if (cursor < begin) nodes.push(document.createTextNode(text.slice(cursor - from, begin - from)));
|
| 150 |
+
const span = document.createElement("span");
|
| 151 |
+
span.className = edit.heading ? "reader-text-chapter-title" : "reader-text-padding";
|
| 152 |
+
span.textContent = text.slice(begin - from, end - from);
|
| 153 |
+
nodes.push(span);
|
| 154 |
+
if (edit.heading && edit.start >= from) {
|
| 155 |
+
toc.push({ label: edit.heading, depth: edit.depth ?? 0, target: span,
|
| 156 |
+
activate: () => span.scrollIntoView({ block: "start" }) });
|
| 157 |
+
}
|
| 158 |
+
cursor = end;
|
| 159 |
+
if (edit.end > to) break;
|
| 160 |
+
editIndex++;
|
| 161 |
+
}
|
| 162 |
+
if (cursor < to) nodes.push(document.createTextNode(text.slice(cursor - from)));
|
| 163 |
+
block.replaceChildren(...nodes);
|
| 164 |
+
}
|
| 165 |
+
from = to;
|
| 166 |
+
}
|
| 167 |
+
return toc;
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
/** @param {ReaderTextContext} readerContext */
|
| 171 |
export function createReaderTextFormat(readerContext) {
|
| 172 |
/** @param {Response} response */
|
|
|
|
| 213 |
}
|
| 214 |
}
|
| 215 |
};
|
| 216 |
+
/** @param {number} length */
|
| 217 |
+
const finishText = async (length) => {
|
| 218 |
+
if (!vCard) {
|
| 219 |
+
if (length <= TXT_LAYOUT_BYTES && originalTextExtension(readerContext) === "txt") {
|
| 220 |
+
const toc = typesetPlainText(pre);
|
| 221 |
+
if (toc.length) readerContext.setToc(toc);
|
| 222 |
+
}
|
| 223 |
+
return;
|
| 224 |
+
}
|
| 225 |
readerContext.assertReaderActive();
|
| 226 |
const summary = formatVCard(pre.textContent ?? "");
|
| 227 |
if (summary !== null) {
|
|
|
|
| 259 |
const decoder = new TextDecoder(readerContext.detectTextEncoding(bytes.subarray(start, start + sampleLimit),
|
| 260 |
readerContext.documentState.title, start === 0));
|
| 261 |
await appendDecoded(decoder.decode(bytes), decoder.encoding);
|
| 262 |
+
await finishText(bytes.byteLength);
|
| 263 |
return;
|
| 264 |
}
|
| 265 |
const reader = response.body.getReader(),
|
|
|
|
| 418 |
// startDecoder assigns one even for an empty sample. A failure is caught.
|
| 419 |
if (!decoder) await startDecoder();
|
| 420 |
await appendDecoded((/** @type {TextDecoder} */ (/** @type {unknown} */ (decoder))).decode(), (/** @type {TextDecoder} */ (/** @type {unknown} */ (decoder))).encoding);
|
| 421 |
+
await finishText(length);
|
| 422 |
} catch (reason) {
|
| 423 |
clearUtf8Preview();
|
| 424 |
try {
|
static/reader/search/reader-dom-search.mjs
CHANGED
|
@@ -39,6 +39,11 @@ export function fullSearchPageOffset(total, requestedOffset, pageSize = 50) {
|
|
| 39 |
)) * pageSize;
|
| 40 |
}
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
/** @param {DomSearch.Options} options */
|
| 43 |
export function createReaderDomSearch({
|
| 44 |
content, runtime, isCurrent, yieldTask, getTocEntries, unwrapRoot, publishPage
|
|
@@ -480,9 +485,9 @@ export function createReaderDomSearch({
|
|
| 480 |
if (!currentNodes || !isCurrent("search", searchGeneration) ||
|
| 481 |
!isCurrent("navigation", navigationGeneration)) return false;
|
| 482 |
if (parts.map(part => part.node.data.slice(part.start, part.end)).join("") !== match.value) return false;
|
| 483 |
-
const
|
| 484 |
-
|
| 485 |
-
return
|
| 486 |
}
|
| 487 |
};
|
| 488 |
};
|
|
@@ -539,7 +544,7 @@ export function createReaderDomSearch({
|
|
| 539 |
const matchedPage = page(occurrence);
|
| 540 |
const result = matchedPage.results[occurrence - matchedPage.offset];
|
| 541 |
if (!result || !await result.activate(navigationGeneration)) return [];
|
| 542 |
-
return [{ target: fullSearchActiveMarks
|
| 543 |
}
|
| 544 |
const fallbackResults = progressive ? null : firstHits.map(resultFor);
|
| 545 |
if (cached && !/** @type {DomSearch.Snapshot} */ (snapshot).current())
|
|
|
|
| 39 |
)) * pageSize;
|
| 40 |
}
|
| 41 |
|
| 42 |
+
/** @param {HTMLElement} mark */
|
| 43 |
+
function visibleTextMark(mark) {
|
| 44 |
+
return !mark.closest(".reader-text-padding");
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
/** @param {DomSearch.Options} options */
|
| 48 |
export function createReaderDomSearch({
|
| 49 |
content, runtime, isCurrent, yieldTask, getTocEntries, unwrapRoot, publishPage
|
|
|
|
| 485 |
if (!currentNodes || !isCurrent("search", searchGeneration) ||
|
| 486 |
!isCurrent("navigation", navigationGeneration)) return false;
|
| 487 |
if (parts.map(part => part.node.data.slice(part.start, part.end)).join("") !== match.value) return false;
|
| 488 |
+
const marks = highlightTextParts(parts);
|
| 489 |
+
marks.find(visibleTextMark)?.scrollIntoView({ block: "center" });
|
| 490 |
+
return marks.length > 0;
|
| 491 |
}
|
| 492 |
};
|
| 493 |
};
|
|
|
|
| 544 |
const matchedPage = page(occurrence);
|
| 545 |
const result = matchedPage.results[occurrence - matchedPage.offset];
|
| 546 |
if (!result || !await result.activate(navigationGeneration)) return [];
|
| 547 |
+
return [{ target: fullSearchActiveMarks.find(visibleTextMark) }];
|
| 548 |
}
|
| 549 |
const fallbackResults = progressive ? null : firstHits.map(resultFor);
|
| 550 |
if (cached && !/** @type {DomSearch.Snapshot} */ (snapshot).current())
|
static/reader/ui/reader-speech.mjs
CHANGED
|
@@ -243,6 +243,27 @@ export function createReaderSpeech(readerContext, loadPlayer, handoffPayload) {
|
|
| 243 |
if (next >= sourceInfo.units) done = true;
|
| 244 |
});
|
| 245 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
/** @type {import('../../../typings/reader-speech-strict').SpeechAdapter} */
|
| 247 |
const self = {
|
| 248 |
base, source: sourceInfo,
|
|
@@ -324,7 +345,7 @@ export function createReaderSpeech(readerContext, loadPlayer, handoffPayload) {
|
|
| 324 |
self.current = start;
|
| 325 |
// Parked in the background (Reader closed while reading): no layout to follow.
|
| 326 |
if (!self.following || !readerContext.viewport.getClientRects().length) return undefined;
|
| 327 |
-
const range =
|
| 328 |
if (!range) {
|
| 329 |
// An unrendered page/section: navigate there and wait for its text.
|
| 330 |
if (sourceInfo.root(part.unit) || !sourceInfo.locate) return undefined;
|
|
@@ -341,7 +362,7 @@ export function createReaderSpeech(readerContext, loadPlayer, handoffPayload) {
|
|
| 341 |
},
|
| 342 |
following: true, current: null, autoUntil: 0,
|
| 343 |
// null when the clip has no rendered range; otherwise whether it is in view.
|
| 344 |
-
visible(start, range =
|
| 345 |
const rect = range?.getBoundingClientRect();
|
| 346 |
if (!rect || !rect.height) return null;
|
| 347 |
const box = readerContext.viewport.getBoundingClientRect();
|
|
@@ -374,7 +395,7 @@ export function createReaderSpeech(readerContext, loadPlayer, handoffPayload) {
|
|
| 374 |
try {
|
| 375 |
await sourceInfo.locate?.(part.unit);
|
| 376 |
if (adapter !== self) publish(self);
|
| 377 |
-
const range =
|
| 378 |
if (range) scrollToRange(range, "auto");
|
| 379 |
self.following = true;
|
| 380 |
} finally { self.autoUntil = performance.now() + 600; }
|
|
|
|
| 243 |
if (next >= sourceInfo.units) done = true;
|
| 244 |
});
|
| 245 |
}
|
| 246 |
+
/** @param {number} offset */
|
| 247 |
+
function positionRange(offset) {
|
| 248 |
+
const range = self.range(offset, offset + 1);
|
| 249 |
+
const padding = range?.startContainer.parentElement?.closest(".reader-text-padding");
|
| 250 |
+
if (!range || !padding) return range;
|
| 251 |
+
// Keep saved/spoken offsets exact. Only the scrolling rectangle needs a
|
| 252 |
+
// painted character; follow the next text after any hidden padding.
|
| 253 |
+
const root = self.root;
|
| 254 |
+
if (!root) return range;
|
| 255 |
+
const walker = padding.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
| 256 |
+
walker.currentNode = range.startContainer;
|
| 257 |
+
for (let node; (node = walker.nextNode());) {
|
| 258 |
+
if (node.parentElement?.closest(".reader-text-padding") || !node.textContent?.trim()) continue;
|
| 259 |
+
const target = padding.ownerDocument.createRange();
|
| 260 |
+
const start = node.textContent.search(/\S/u);
|
| 261 |
+
target.setStart(node, start);
|
| 262 |
+
target.setEnd(node, start + 1);
|
| 263 |
+
return target;
|
| 264 |
+
}
|
| 265 |
+
return range;
|
| 266 |
+
}
|
| 267 |
/** @type {import('../../../typings/reader-speech-strict').SpeechAdapter} */
|
| 268 |
const self = {
|
| 269 |
base, source: sourceInfo,
|
|
|
|
| 345 |
self.current = start;
|
| 346 |
// Parked in the background (Reader closed while reading): no layout to follow.
|
| 347 |
if (!self.following || !readerContext.viewport.getClientRects().length) return undefined;
|
| 348 |
+
const range = positionRange(start);
|
| 349 |
if (!range) {
|
| 350 |
// An unrendered page/section: navigate there and wait for its text.
|
| 351 |
if (sourceInfo.root(part.unit) || !sourceInfo.locate) return undefined;
|
|
|
|
| 362 |
},
|
| 363 |
following: true, current: null, autoUntil: 0,
|
| 364 |
// null when the clip has no rendered range; otherwise whether it is in view.
|
| 365 |
+
visible(start, range = positionRange(start)) {
|
| 366 |
const rect = range?.getBoundingClientRect();
|
| 367 |
if (!rect || !rect.height) return null;
|
| 368 |
const box = readerContext.viewport.getBoundingClientRect();
|
|
|
|
| 395 |
try {
|
| 396 |
await sourceInfo.locate?.(part.unit);
|
| 397 |
if (adapter !== self) publish(self);
|
| 398 |
+
const range = positionRange(offset);
|
| 399 |
if (range) scrollToRange(range, "auto");
|
| 400 |
self.following = true;
|
| 401 |
} finally { self.autoUntil = performance.now() + 600; }
|
tests/reader/browser/test_reader_refactor.py
CHANGED
|
@@ -3055,19 +3055,48 @@ class ReaderRefactorTest(unittest.TestCase):
|
|
| 3055 |
self.assertEqual(frame.locator('script').count(), 0)
|
| 3056 |
self.assertNotIn('legacyPayload', frame.locator('body').inner_text())
|
| 3057 |
|
| 3058 |
-
def
|
| 3059 |
-
path = 'documents/text/txt/
|
| 3060 |
source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + urllib.parse.quote(path, safe='')
|
| 3061 |
-
|
|
|
|
|
|
|
| 3062 |
self.page.route('https://voiceofml-search.hf.space/api/reader-bucket-resource**',
|
| 3063 |
lambda route: route.fulfill(content_type='text/plain', body=text))
|
| 3064 |
self.serve(text)
|
| 3065 |
-
for url
|
| 3066 |
-
with self.subTest(
|
| 3067 |
self.open(self.reader_url('txt', **({'url': url} if url else {})))
|
| 3068 |
-
|
| 3069 |
-
self.assertEqual(
|
| 3070 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3071 |
|
| 3072 |
def test_offline_html_keeps_layout_attributes_and_enforces_frame_csp(self):
|
| 3073 |
dot = ("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8"
|
|
|
|
| 3055 |
self.assertEqual(frame.locator('script').count(), 0)
|
| 3056 |
self.assertNotIn('legacyPayload', frame.locator('body').inner_text())
|
| 3057 |
|
| 3058 |
+
def test_txt_layout_preserves_text_spaces_and_two_blank_lines_and_builds_toc(self):
|
| 3059 |
+
path = 'documents/text/txt/' + '2' * 64 + '/document.txt'
|
| 3060 |
source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + urllib.parse.quote(path, safe='')
|
| 3061 |
+
line = ' 这是一段完整的正文。保留行内 空格。'
|
| 3062 |
+
text = ('第一卷 总览\r\n' + (line + '\r\n') * 5 + ' \r\n\r\n \r\n\t\r\n' +
|
| 3063 |
+
'第二节 续读\r\n' + (line + '\r\n') * 8 + '第一章结束了。')
|
| 3064 |
self.page.route('https://voiceofml-search.hf.space/api/reader-bucket-resource**',
|
| 3065 |
lambda route: route.fulfill(content_type='text/plain', body=text))
|
| 3066 |
self.serve(text)
|
| 3067 |
+
for url in (source, None):
|
| 3068 |
+
with self.subTest(url=url):
|
| 3069 |
self.open(self.reader_url('txt', **({'url': url} if url else {})))
|
| 3070 |
+
root = self.page.locator('.reader-text')
|
| 3071 |
+
self.assertEqual(root.text_content(), text)
|
| 3072 |
+
rendered = root.inner_text().replace('\r\n', '\n')
|
| 3073 |
+
self.assertIn('\n 这是一段完整的正文。保留行内 空格。', rendered)
|
| 3074 |
+
self.assertIn('空格。\n \n\n第二节 续读', rendered)
|
| 3075 |
+
if self.page.locator('#history').get_attribute('aria-expanded') != 'true':
|
| 3076 |
+
support.open_reader_panel(self.page)
|
| 3077 |
+
self.page.locator('.toc-item', has_text='第二节 续读').click()
|
| 3078 |
+
self.assertEqual(root.locator('.reader-text-chapter-title').last.inner_text(), '第二节 续读')
|
| 3079 |
+
self.search('行内 空格')
|
| 3080 |
+
self.page.locator('.full-search-result').first.click()
|
| 3081 |
+
self.assertEqual(root.locator('.full-search-highlight').inner_text(), '行内 空格')
|
| 3082 |
+
self.assertEqual(root.text_content(), text)
|
| 3083 |
+
|
| 3084 |
+
def test_txt_layout_does_not_reformat_preformatted_lines_or_invent_headings(self):
|
| 3085 |
+
text = '配置说明\n 第一行\n\n第二行\n\n\n col value\n第一章结束了。'
|
| 3086 |
+
self.serve(text)
|
| 3087 |
+
self.open(self.reader_url('txt'))
|
| 3088 |
+
root = self.page.locator('.reader-text')
|
| 3089 |
+
self.assertEqual(root.text_content(), text)
|
| 3090 |
+
self.assertEqual(root.inner_text(), text)
|
| 3091 |
+
self.assertEqual(root.locator('.reader-text-padding, .reader-text-chapter-title').count(), 0)
|
| 3092 |
+
|
| 3093 |
+
def test_markdown_uses_authored_heading_levels_for_chapter_navigation(self):
|
| 3094 |
+
self.serve('# 第一卷\n\n开头\n\n## 第一节\n\n正文\n\n```text\n# 不是章节\n```')
|
| 3095 |
+
self.open(self.reader_url('md'))
|
| 3096 |
+
support.open_reader_panel(self.page)
|
| 3097 |
+
self.assertEqual(self.page.locator('.toc-item').all_inner_texts(), ['第一卷', '第一节'])
|
| 3098 |
+
self.page.locator('.toc-item', has_text='第一节').click()
|
| 3099 |
+
self.assertTrue(self.page.locator('.reader-markdown h2').is_visible())
|
| 3100 |
|
| 3101 |
def test_offline_html_keeps_layout_attributes_and_enforces_frame_csp(self):
|
| 3102 |
dot = ("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8"
|
tests/reader/browser/test_reader_speech.py
CHANGED
|
@@ -505,6 +505,29 @@ class ReaderSpeechTest(unittest.TestCase):
|
|
| 505 |
finally:
|
| 506 |
context.close()
|
| 507 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
def test_scrolling_away_is_not_undone_by_the_next_sentence(self):
|
| 509 |
body = "".join(f"第{index}句。\n" for index in range(400)).encode()
|
| 510 |
context, page, posts, errors = self.open("txt", body, "text/plain; charset=utf-8")
|
|
|
|
| 505 |
finally:
|
| 506 |
context.close()
|
| 507 |
|
| 508 |
+
def test_txt_reveal_inside_hidden_indent_uses_visible_sentence_without_changing_offset(self):
|
| 509 |
+
line = ' 这是正常段落,朗读时必须能找到可见的一行。\n'
|
| 510 |
+
text = line * 180
|
| 511 |
+
context, page, posts, errors = self.open('txt', text.encode(), 'text/plain; charset=utf-8')
|
| 512 |
+
try:
|
| 513 |
+
offset = len(line) * 120 + 5
|
| 514 |
+
self.play(page, posts)
|
| 515 |
+
self.stop(page)
|
| 516 |
+
before, after, raw, painted = page.evaluate('''async offset => {
|
| 517 |
+
const a = CCRDSpeech.state().adapter;
|
| 518 |
+
await a.ensure(offset + 1);
|
| 519 |
+
const viewport = document.querySelector('#viewport');
|
| 520 |
+
const before = viewport.scrollTop;
|
| 521 |
+
await a.reveal(offset);
|
| 522 |
+
return [before, viewport.scrollTop, a.range(offset, offset + 1).toString(), a.inView(offset)];
|
| 523 |
+
}''', offset)
|
| 524 |
+
self.assertEqual(raw, ' ')
|
| 525 |
+
self.assertGreater(after, before + 500)
|
| 526 |
+
self.assertTrue(painted)
|
| 527 |
+
self.assertFalse(errors, errors)
|
| 528 |
+
finally:
|
| 529 |
+
context.close()
|
| 530 |
+
|
| 531 |
def test_scrolling_away_is_not_undone_by_the_next_sentence(self):
|
| 532 |
body = "".join(f"第{index}句。\n" for index in range(400)).encode()
|
| 533 |
context, page, posts, errors = self.open("txt", body, "text/plain; charset=utf-8")
|
tests/reader/dom-search/contracts.mjs
CHANGED
|
@@ -395,5 +395,14 @@ export async function occurrenceSelection() {
|
|
| 395 |
f.search.clearMarks(); f.nextNavigation();
|
| 396 |
const stale = await f.search.search(f.root, '', 'needle', f.generation, true, 1, f.navigation - 1);
|
| 397 |
ensure(stale.length === 0 && !f.root.querySelector('mark'), 'stale occurrence selection');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
} finally { f.finish(); }
|
| 399 |
}
|
|
|
|
| 395 |
f.search.clearMarks(); f.nextNavigation();
|
| 396 |
const stale = await f.search.search(f.root, '', 'needle', f.generation, true, 1, f.navigation - 1);
|
| 397 |
ensure(stale.length === 0 && !f.root.querySelector('mark'), 'stale occurrence selection');
|
| 398 |
+
f.root.innerHTML = '<span class="reader-text-padding" hidden> </span>needle';
|
| 399 |
+
const raw = f.root.textContent;
|
| 400 |
+
for (let i = 0; i < 2; i++) {
|
| 401 |
+
const matches = await f.search.search(f.root, '', ' needle', f.generation, true, 0, f.navigation);
|
| 402 |
+
ensure(matches.length === 1 && matches[0].target?.textContent === 'needle', 'visible part owns navigation');
|
| 403 |
+
ensure(f.root.querySelector('.reader-text-padding mark')?.textContent === ' ', 'exact whitespace matched');
|
| 404 |
+
f.search.clearMarks();
|
| 405 |
+
ensure(f.root.textContent === raw && !f.root.querySelector('mark'), 'padding survives highlight cleanup');
|
| 406 |
+
}
|
| 407 |
} finally { f.finish(); }
|
| 408 |
}
|
tests/reader/text/test_reader_text_baseline.mjs
CHANGED
|
@@ -12,6 +12,7 @@ class FakeText {
|
|
| 12 |
class FakeElement {
|
| 13 |
constructor(tag) { this.tag=tag;this.children=[];this.className='';this.dataset={}; }
|
| 14 |
appendChild(node) { this.children.push(node);return node; }
|
|
|
|
| 15 |
get lastChild() { return this.children.at(-1) ?? null; }
|
| 16 |
get textContent() { return this.children.map(child=>child.textContent).join(''); }
|
| 17 |
set textContent(value) { this.children=value ? [new FakeText(value)] : []; }
|
|
@@ -28,7 +29,7 @@ function fixture({limit=1_000_000, waits=()=>Promise.resolve()}={}) {
|
|
| 28 |
assertReaderActive(){},markReaderContentReady(){events.push('ready');},waitForReader:waits,
|
| 29 |
trackReaderResource(cleanup){events.push('track');this.cleanup=cleanup;return()=>events.push('untrack');},
|
| 30 |
readerAbortError:()=>new DOMException('closed','AbortError'),awaitReader:promise=>Promise.resolve(promise),
|
| 31 |
-
renderText:(mode,prepared)=>({mode,prepared})};
|
| 32 |
Object.assign(context,createReaderTextFormat(context));
|
| 33 |
return {context,events,restore(){globalThis.document=old.document;globalThis.Node=old.Node;
|
| 34 |
globalThis.VoiceOfMLReaderSecurity=old.security;}};
|
|
@@ -38,6 +39,44 @@ function responseChunks(chunks) {
|
|
| 38 |
return new Response(stream);
|
| 39 |
}
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
const vCard = [
|
| 42 |
'BEGIN:VCARD', 'VERSION:3.0', 'N:Example;Test;;;', 'FN:测试 Example', 'TITLE:Example role',
|
| 43 |
'ORG:Team\\;A;Division', 'EMAIL;TYPE=WORK,INTERNET:work@example.invalid',
|
|
|
|
| 12 |
class FakeElement {
|
| 13 |
constructor(tag) { this.tag=tag;this.children=[];this.className='';this.dataset={}; }
|
| 14 |
appendChild(node) { this.children.push(node);return node; }
|
| 15 |
+
replaceChildren(...nodes) { this.children=nodes; }
|
| 16 |
get lastChild() { return this.children.at(-1) ?? null; }
|
| 17 |
get textContent() { return this.children.map(child=>child.textContent).join(''); }
|
| 18 |
set textContent(value) { this.children=value ? [new FakeText(value)] : []; }
|
|
|
|
| 29 |
assertReaderActive(){},markReaderContentReady(){events.push('ready');},waitForReader:waits,
|
| 30 |
trackReaderResource(cleanup){events.push('track');this.cleanup=cleanup;return()=>events.push('untrack');},
|
| 31 |
readerAbortError:()=>new DOMException('closed','AbortError'),awaitReader:promise=>Promise.resolve(promise),
|
| 32 |
+
renderText:(mode,prepared)=>({mode,prepared}), setToc(toc){this.toc=toc;}};
|
| 33 |
Object.assign(context,createReaderTextFormat(context));
|
| 34 |
return {context,events,restore(){globalThis.document=old.document;globalThis.Node=old.Node;
|
| 35 |
globalThis.VoiceOfMLReaderSecurity=old.security;}};
|
|
|
|
| 39 |
return new Response(stream);
|
| 40 |
}
|
| 41 |
|
| 42 |
+
test('TXT layout retains raw text across streaming chunks, including hidden whitespace and chapters', async t => {
|
| 43 |
+
const f=fixture(); t.after(f.restore);
|
| 44 |
+
f.context.extension='txt';
|
| 45 |
+
const line=' 这是一段完整的正文。保留行内 空格。\r\n';
|
| 46 |
+
const text='第一卷 总览\r\n'+line.repeat(5)+' \r\n\r\n \r\n\t\r\n'+
|
| 47 |
+
'第二节 续读\r\n'+line.repeat(8)+'第一章结束了。';
|
| 48 |
+
const raw=encode(text), chunks=[];
|
| 49 |
+
for(let i=0;i<raw.length;i+=43) chunks.push(raw.subarray(i,i+43));
|
| 50 |
+
await f.context.renderPlainText(responseChunks(chunks));
|
| 51 |
+
const root=f.context.content.children[0];
|
| 52 |
+
assert.equal(root.textContent,text);
|
| 53 |
+
const pieces=root.children.flatMap(block=>block.children);
|
| 54 |
+
const hidden=pieces.filter(node=>node.className==='reader-text-padding');
|
| 55 |
+
assert.equal(hidden.filter(node=>node.textContent===' '.repeat(10)).length,13);
|
| 56 |
+
assert.ok(hidden.some(node=>node.textContent===' \r\n\t\r\n'));
|
| 57 |
+
assert.deepEqual(f.context.toc.map(({label,depth})=>[label,depth]),[['第一卷 总览',0],['第二节 续读',1]]);
|
| 58 |
+
let activated=false;
|
| 59 |
+
f.context.toc[1].target.scrollIntoView=()=>{activated=true;};
|
| 60 |
+
f.context.toc[1].activate(); assert.ok(activated);
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
test('TXT layout leaves ordinary indents and one or two blank lines alone, and caps decoration', async t => {
|
| 64 |
+
const f=fixture(); t.after(f.restore);
|
| 65 |
+
f.context.extension='txt';
|
| 66 |
+
const ordinary='标题\n 第一段。\n\n第二段\n\n\n 单行对齐';
|
| 67 |
+
const large='第一章 绪论\n'+('字'.repeat(45000))+'\n\n\n\n结束';
|
| 68 |
+
const dense='第一章 绪论\n'+(' 这是测试段落。\n'.repeat(1030));
|
| 69 |
+
const crossBlock='第一段\n'+'\n'.repeat(32800)+'第二段\n';
|
| 70 |
+
for (const raw of [ordinary,large,dense,crossBlock]) {
|
| 71 |
+
await f.context.renderPlainText(buffered(raw));
|
| 72 |
+
const root=f.context.content.children.at(-1);
|
| 73 |
+
assert.equal(root.textContent,raw);
|
| 74 |
+
const hidden=root.children.flatMap(block=>block.children).filter(node=>node.className==='reader-text-padding');
|
| 75 |
+
assert.equal(hidden.map(node=>node.textContent).join(''),raw===crossBlock?'\n'.repeat(32798):'');
|
| 76 |
+
}
|
| 77 |
+
assert.equal(f.context.toc,undefined);
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
const vCard = [
|
| 81 |
'BEGIN:VCARD', 'VERSION:3.0', 'N:Example;Test;;;', 'FN:测试 Example', 'TITLE:Example role',
|
| 82 |
'ORG:Team\\;A;Division', 'EMAIL;TYPE=WORK,INTERNET:work@example.invalid',
|