vomebook commited on
Commit ·
d6f7739
1
Parent(s): d3655e4
Normalize TXT paragraph spacing and build a chapter outline
Browse filesFiles changed (10)
- scripts/reader/check_reader_text_coverage.mjs+2
- static/reader.css+5-3
- static/reader/formats/reader-html-format.mjs-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
- tests/reader/dom-search/contracts.mjs+9
- tests/reader/text/test_reader_text_baseline.mjs+40-1
3 unmodified lines4567893 unmodified linesconst minimum = [100, 91.89, 90.91];const required = ['encoding detection handles BOMs, valid UTF-8, UTF-16 heuristics and legacy hints','plain fallback preserves Unicode replacement characters and enforces actual byte limit','stream handles split UTF-8 BOM and codepoints and releases its resource',3 unmodified lines45678910113 unmodified linesconst minimum = [100, 91.89, 90.91];const required = ['TXT layout retains raw text across streaming chunks, including hidden whitespace and chapters','TXT layout leaves ordinary indents and one or two blank lines alone, and caps decoration','encoding detection handles BOMs, valid UTF-8, UTF-16 heuristics and legacy hints','plain fallback preserves Unicode replacement characters and enforces actual byte limit','stream handles split UTF-8 BOM and codepoints and releases its resource',
1227 unmodified lines1228122912301231123212331234123512361227 unmodified lines.reader-text-block:focus-within {content-visibility: visible;}.reader-content--compact-text .reader-text {white-space: pre-line;line-height: 1.55;}.reader-markdown {margin: 0 auto;1227 unmodified lines122812291230123112321233123412351236123712381227 unmodified lines.reader-text-block:focus-within {content-visibility: visible;}.reader-text .reader-text-padding {display: none;}.reader-text .reader-text-chapter-title {font-weight: 700;}.reader-markdown {margin: 0 auto;
486 unmodified lines487488489490491492493494495496497498499500501502503504505506507508509510486 unmodified lines});}function readingAssetPath() {try {const url = new URL(readerContext.sourceUrl, location.href);return url.searchParams.get("path") || url.pathname.replace(/^\//, "");} catch (_) { return ""; }}/** @param {boolean} markdown @param {import('../../../typings/reader-html-format-strict').PreparedText} prepared */async function renderText(markdown, prepared) {let response = await prepared.response;if (!response.ok) response = await readerContext.fetchReaderResponse();if (!response.ok) throw new Error(`HTTP ${response.status}`);if (!markdown) {// This legacy article pads nearly every line with 12–26 spaces. Compact// only its presentation, keeping search, text offsets and download intact.readerContext.content.classList.toggle("reader-content--compact-text", readingAssetPath() ==="documents/text/txt/63fa4ecf73e28346a33704c8adbacebaec293f6f649d96590f066fd42187d97c/document.txt");await readerContext.renderPlainText(response);} else {const bytes = await readerContext.readPreparedBytes(response, prepared.engines);486 unmodified lines487488489490491492493494495496497498486 unmodified lines});}/** @param {boolean} markdown @param {import('../../../typings/reader-html-format-strict').PreparedText} prepared */async function renderText(markdown, prepared) {let response = await prepared.response;if (!response.ok) response = await readerContext.fetchReaderResponse();if (!response.ok) throw new Error(`HTTP ${response.status}`);if (!markdown) {await readerContext.renderPlainText(response);} else {const bytes = await readerContext.readPreparedBytes(response, prepared.engines);
14 unmodified lines1516171819202122232425262728293047 unmodified lines78798081828340 unmodified lines12412512612712812913031 unmodified lines162163164165166167168152 unmodified lines32132232332432532632714 unmodified lines* @property {(bytes: Uint8Array, hint?: string, leading?: boolean) => string} detectTextEncoding* @property {{title: string}} documentState* @property {ReaderTextRenderer} renderText* @typedef {ReaderTextHost & ReaderOriginalFormat} ReaderTextContext*/const VCARD_PREVIEW_BYTES = 64 * 1024;/** @param {ReaderOriginalFormat} context */export function isReaderVCard(context) {const original = context.resolvedReaderData?.original_extension;const extension = typeof original === "string" && original ? original : context.extension;return extension?.toLowerCase().replace(/^\./, "") === "vcf";}const vCardLabels = new Map([47 unmodified linesreturn fields.filter(field => !hasFullName || field.key !== "N").map(field => field.text).join("\n");}/** @param {ReaderTextContext} readerContext */export function createReaderTextFormat(readerContext) {/** @param {Response} response */40 unmodified lines}}};const finishVCard = async () => {readerContext.assertReaderActive();const summary = formatVCard(pre.textContent ?? "");if (summary !== null) {31 unmodified linesconst decoder = new TextDecoder(readerContext.detectTextEncoding(bytes.subarray(start, start + sampleLimit),readerContext.documentState.title, start === 0));await appendDecoded(decoder.decode(bytes), decoder.encoding);if (vCard) await finishVCard();return;}const reader = response.body.getReader(),152 unmodified lines// startDecoder assigns one even for an empty sample. A failure is caught.if (!decoder) await startDecoder();await appendDecoded((/** @type {TextDecoder} */ (/** @type {unknown} */ (decoder))).decode(), (/** @type {TextDecoder} */ (/** @type {unknown} */ (decoder))).encoding);if (vCard) await finishVCard();} catch (reason) {clearUtf8Preview();try {14 unmodified lines1516171819202122232425262728293031323334353647 unmodified lines8485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117240 unmodified lines21321421521621721821922022122222322422522622731 unmodified lines259260261262263264265152 unmodified lines41841942042142242342414 unmodified lines* @property {(bytes: Uint8Array, hint?: string, leading?: boolean) => string} detectTextEncoding* @property {{title: string}} documentState* @property {ReaderTextRenderer} renderText* @property {(entries: {label: string; depth: number; target: HTMLElement; activate(): void}[]) => void} setToc* @typedef {ReaderTextHost & ReaderOriginalFormat} ReaderTextContext*/const VCARD_PREVIEW_BYTES = 64 * 1024;/** @param {ReaderOriginalFormat} context */function originalTextExtension(context) {const original = context.resolvedReaderData?.original_extension;const extension = typeof original === "string" && original ? original : context.extension;return extension?.toLowerCase().replace(/^\./, "");}/** @param {ReaderOriginalFormat} context */export function isReaderVCard(context) {return originalTextExtension(context) === "vcf";}const vCardLabels = new Map([47 unmodified linesreturn fields.filter(field => !hasFullName || field.key !== "N").map(field => field.text).join("\n");}// Apply layout only to bounded TXT documents, after decoding and before restoring// the position. Never replace the text used by search, speech or the original download.const TXT_LAYOUT_BYTES = 128 * 1024;const TXT_LAYOUT_EDITS = 1024;const TXT_CHAPTER = /^第[ \u3000]*[\d0-9〇零一二三四五六七八九十百千万两]+[ \u3000]*([卷部篇章节回])(?:$|[ \t\u3000..::、—–-]+[^\r\n]+$)/u;/** @typedef {{ start: number; end: number; heading?: string; depth?: number }} TextLayoutEdit *//** @param {string} text */function planTextLayout(text) {/** @type {TextLayoutEdit[]} */const indents = [], gaps = [], headings = [];let total = 0, padded = 0, prose = 0, blankLines = 0;/** @type {TextLayoutEdit | null} */let gap = null;for (const line of text.matchAll(/[^\r\n]*(?:\r\n|\r|\n|$)/g)) {const raw = line[0], start = line.index;if (!raw) break;const label = raw.trim();if (!label) {if (gap) gap.end = start + raw.length;else if (++blankLines === 3) {gap = { start, end: start + raw.length };gaps.push(gap);}} else {blankLines = 0;gap = null;total++;if (label.length >= 16 && /[。!?;,、]|[.!?;](?:\s|$)/u.test(label)) prose++;const indent = /^[ \u3000]{8,}/u.exec(raw)?.[0];if (indent) {padded++;indents.push({ start: start + 2, end: start + indent.length });}const kind = label.length <= 72 ? TXT_CHAPTER.exec(label)?.[1] : null;if (kind && !/[。!?;!?]$/u.test(label)) {const titleStart = start + raw.indexOf(label);headings.push({ start: titleStart, end: titleStart + label.length, heading: label, depth: kind === "节" ? 1 : 0 });}}if (indents.length + gaps.length + headings.length > TXT_LAYOUT_EDITS) return [];}// A few indented lines are not a padding convention. Require recurring long// indents and sentence-like prose; keep meaningful whitespace in code/tables.const compact = total >= 8 && padded * 4 >= total * 3 && prose >= 3;return [...(compact ? indents : []), ...gaps, ...headings].sort((a, b) => a.start - b.start);}/** @param {HTMLElement} root */function typesetPlainText(root) {const edits = planTextLayout(root.textContent ?? "");/** @type {{label: string; depth: number; target: HTMLElement; activate(): void}[]} */const toc = [];let from = 0, editIndex = 0;for (const block of root.children) {const text = block.textContent ?? "", to = from + text.length;if ((edits[editIndex]?.start ?? Infinity) < to) {/** @type {Node[]} */const nodes = [];let cursor = from;for (let edit; (edit = edits[editIndex]) && edit.start < to;) {const begin = Math.max(from, edit.start), end = Math.min(to, edit.end);if (cursor < begin) nodes.push(document.createTextNode(text.slice(cursor - from, begin - from)));const span = document.createElement("span");span.className = edit.heading ? "reader-text-chapter-title" : "reader-text-padding";span.textContent = text.slice(begin - from, end - from);nodes.push(span);if (edit.heading && edit.start >= from) {toc.push({ label: edit.heading, depth: edit.depth ?? 0, target: span,activate: () => span.scrollIntoView({ block: "start" }) });}cursor = end;if (edit.end > to) break;editIndex++;}if (cursor < to) nodes.push(document.createTextNode(text.slice(cursor - from)));block.replaceChildren(...nodes);}from = to;}return toc;}/** @param {ReaderTextContext} readerContext */export function createReaderTextFormat(readerContext) {/** @param {Response} response */40 unmodified lines}}};/** @param {number} length */const finishText = async (length) => {if (!vCard) {if (length <= TXT_LAYOUT_BYTES && originalTextExtension(readerContext) === "txt") {const toc = typesetPlainText(pre);if (toc.length) readerContext.setToc(toc);}return;}readerContext.assertReaderActive();const summary = formatVCard(pre.textContent ?? "");if (summary !== null) {31 unmodified linesconst decoder = new TextDecoder(readerContext.detectTextEncoding(bytes.subarray(start, start + sampleLimit),readerContext.documentState.title, start === 0));await appendDecoded(decoder.decode(bytes), decoder.encoding);await finishText(bytes.byteLength);return;}const reader = response.body.getReader(),152 unmodified lines// startDecoder assigns one even for an empty sample. A failure is caught.if (!decoder) await startDecoder();await appendDecoded((/** @type {TextDecoder} */ (/** @type {unknown} */ (decoder))).decode(), (/** @type {TextDecoder} */ (/** @type {unknown} */ (decoder))).encoding);await finishText(length);} catch (reason) {clearUtf8Preview();try {
38 unmodified lines394041424344435 unmodified lines48048148248348448548648748850 unmodified lines53954054154254354454538 unmodified lines)) * pageSize;}/** @param {DomSearch.Options} options */export function createReaderDomSearch({content, runtime, isCurrent, yieldTask, getTocEntries, unwrapRoot, publishPage435 unmodified linesif (!currentNodes || !isCurrent("search", searchGeneration) ||!isCurrent("navigation", navigationGeneration)) return false;if (parts.map(part => part.node.data.slice(part.start, part.end)).join("") !== match.value) return false;const [target] = highlightTextParts(parts);target?.scrollIntoView({ block: "center" });return !!target;}};};50 unmodified linesconst matchedPage = page(occurrence);const result = matchedPage.results[occurrence - matchedPage.offset];if (!result || !await result.activate(navigationGeneration)) return [];return [{ target: fullSearchActiveMarks[0] }];}const fallbackResults = progressive ? null : firstHits.map(resultFor);if (cached && !/** @type {DomSearch.Snapshot} */ (snapshot).current())38 unmodified lines3940414243444546474849435 unmodified lines48548648748848949049149249350 unmodified lines54454554654754854955038 unmodified lines)) * pageSize;}/** @param {HTMLElement} mark */function visibleTextMark(mark) {return !mark.closest(".reader-text-padding");}/** @param {DomSearch.Options} options */export function createReaderDomSearch({content, runtime, isCurrent, yieldTask, getTocEntries, unwrapRoot, publishPage435 unmodified linesif (!currentNodes || !isCurrent("search", searchGeneration) ||!isCurrent("navigation", navigationGeneration)) return false;if (parts.map(part => part.node.data.slice(part.start, part.end)).join("") !== match.value) return false;const marks = highlightTextParts(parts);marks.find(visibleTextMark)?.scrollIntoView({ block: "center" });return marks.length > 0;}};};50 unmodified linesconst matchedPage = page(occurrence);const result = matchedPage.results[occurrence - matchedPage.offset];if (!result || !await result.activate(navigationGeneration)) return [];return [{ target: fullSearchActiveMarks.find(visibleTextMark) }];}const fallbackResults = progressive ? null : firstHits.map(resultFor);if (cached && !/** @type {DomSearch.Snapshot} */ (snapshot).current())
242 unmodified lines24324424524624724875 unmodified lines32432532632732832933010 unmodified lines34134234334434534634726 unmodified lines374375376377378379380242 unmodified linesif (next >= sourceInfo.units) done = true;});}/** @type {import('../../../typings/reader-speech-strict').SpeechAdapter} */const self = {base, source: sourceInfo,75 unmodified linesself.current = start;// Parked in the background (Reader closed while reading): no layout to follow.if (!self.following || !readerContext.viewport.getClientRects().length) return undefined;const range = self.range(start, start + 1);if (!range) {// An unrendered page/section: navigate there and wait for its text.if (sourceInfo.root(part.unit) || !sourceInfo.locate) return undefined;10 unmodified lines},following: true, current: null, autoUntil: 0,// null when the clip has no rendered range; otherwise whether it is in view.visible(start, range = self.range(start, start + 1)) {const rect = range?.getBoundingClientRect();if (!rect || !rect.height) return null;const box = readerContext.viewport.getBoundingClientRect();26 unmodified linestry {await sourceInfo.locate?.(part.unit);if (adapter !== self) publish(self);const range = self.range(offset, offset + 1);if (range) scrollToRange(range, "auto");self.following = true;} finally { self.autoUntil = performance.now() + 600; }242 unmodified lines24324424524624724824925025125225325425525625725825926026126226326426526626726826975 unmodified lines34534634734834935035110 unmodified lines36236336436536636736826 unmodified lines395396397398399400401242 unmodified linesif (next >= sourceInfo.units) done = true;});}/** @param {number} offset */function positionRange(offset) {const range = self.range(offset, offset + 1);const padding = range?.startContainer.parentElement?.closest(".reader-text-padding");if (!range || !padding) return range;// Keep saved/spoken offsets exact. Only the scrolling rectangle needs a// painted character; follow the next text after any hidden padding.const root = self.root;if (!root) return range;const walker = padding.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);walker.currentNode = range.startContainer;for (let node; (node = walker.nextNode());) {if (node.parentElement?.closest(".reader-text-padding") || !node.textContent?.trim()) continue;const target = padding.ownerDocument.createRange();const start = node.textContent.search(/\S/u);target.setStart(node, start);target.setEnd(node, start + 1);return target;}return range;}/** @type {import('../../../typings/reader-speech-strict').SpeechAdapter} */const self = {base, source: sourceInfo,75 unmodified linesself.current = start;// Parked in the background (Reader closed while reading): no layout to follow.if (!self.following || !readerContext.viewport.getClientRects().length) return undefined;const range = positionRange(start);if (!range) {// An unrendered page/section: navigate there and wait for its text.if (sourceInfo.root(part.unit) || !sourceInfo.locate) return undefined;10 unmodified lines},following: true, current: null, autoUntil: 0,// null when the clip has no rendered range; otherwise whether it is in view.visible(start, range = positionRange(start)) {const rect = range?.getBoundingClientRect();if (!rect || !rect.height) return null;const box = readerContext.viewport.getBoundingClientRect();26 unmodified linestry {await sourceInfo.locate?.(part.unit);if (adapter !== self) publish(self);const range = positionRange(offset);if (range) scrollToRange(range, "auto");self.following = true;} finally { self.autoUntil = performance.now() + 600; }
3054 unmodified lines30553056305730583059306030613062306330643065306630673068306930703071307230733054 unmodified linesself.assertEqual(frame.locator('script').count(), 0)self.assertNotIn('legacyPayload', frame.locator('body').inner_text())def test_legacy_txt_compacts_only_the_view(self):path = 'documents/text/txt/63fa4ecf73e28346a33704c8adbacebaec293f6f649d96590f066fd42187d97c/document.txt'source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + urllib.parse.quote(path, safe='')text = '正文\r\n 旧网页导出的段落\r\n\r\n 第二段'self.page.route('https://voiceofml-search.hf.space/api/reader-bucket-resource**',lambda route: route.fulfill(content_type='text/plain', body=text))self.serve(text)for url, expected in [(source, 'pre-line'), (None, 'pre-wrap')]:with self.subTest(white_space=expected):self.open(self.reader_url('txt', **({'url': url} if url else {})))block = self.page.locator('.reader-text-block')self.assertEqual(block.text_content(), text)self.assertEqual(block.evaluate('n => getComputedStyle(n).whiteSpace'), expected)def test_offline_html_keeps_layout_attributes_and_enforces_frame_csp(self):dot = ("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8"3054 unmodified lines3055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023054 unmodified linesself.assertEqual(frame.locator('script').count(), 0)self.assertNotIn('legacyPayload', frame.locator('body').inner_text())def test_txt_layout_preserves_text_spaces_and_two_blank_lines_and_builds_toc(self):path = 'documents/text/txt/' + '2' * 64 + '/document.txt'source = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?path=' + urllib.parse.quote(path, safe='')line = ' 这是一段完整的正文。保留行内 空格。'text = ('第一卷 总览\r\n' + (line + '\r\n') * 5 + ' \r\n\r\n \r\n\t\r\n' +'第二节 续读\r\n' + (line + '\r\n') * 8 + '第一章结束了。')self.page.route('https://voiceofml-search.hf.space/api/reader-bucket-resource**',lambda route: route.fulfill(content_type='text/plain', body=text))self.serve(text)for url in (source, None):with self.subTest(url=url):self.open(self.reader_url('txt', **({'url': url} if url else {})))root = self.page.locator('.reader-text')self.assertEqual(root.text_content(), text)rendered = root.inner_text().replace('\r\n', '\n')self.assertIn('\n 这是一段完整的正文。保留行内 空格。', rendered)self.assertIn('空格。\n \n\n第二节 续读', rendered)if self.page.locator('#history').get_attribute('aria-expanded') != 'true':support.open_reader_panel(self.page)self.page.locator('.toc-item', has_text='第二节 续读').click()self.assertEqual(root.locator('.reader-text-chapter-title').last.inner_text(), '第二节 续读')self.search('行内 空格')self.page.locator('.full-search-result').first.click()self.assertEqual(root.locator('.full-search-highlight').inner_text(), '行内 空格')self.assertEqual(root.text_content(), text)def test_txt_layout_does_not_reformat_preformatted_lines_or_invent_headings(self):text = '配置说明\n 第一行\n\n第二行\n\n\n col value\n第一章结束了。'self.serve(text)self.open(self.reader_url('txt'))root = self.page.locator('.reader-text')self.assertEqual(root.text_content(), text)self.assertEqual(root.inner_text(), text)self.assertEqual(root.locator('.reader-text-padding, .reader-text-chapter-title').count(), 0)def test_markdown_uses_authored_heading_levels_for_chapter_navigation(self):self.serve('# 第一卷\n\n开头\n\n## 第一节\n\n正文\n\n```text\n# 不是章节\n```')self.open(self.reader_url('md'))support.open_reader_panel(self.page)self.assertEqual(self.page.locator('.toc-item').all_inner_texts(), ['第一卷', '第一节'])self.page.locator('.toc-item', has_text='第一节').click()self.assertTrue(self.page.locator('.reader-markdown h2').is_visible())def test_offline_html_keeps_layout_attributes_and_enforces_frame_csp(self):dot = ("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8"
504 unmodified lines505506507508509510504 unmodified linesfinally:context.close()def test_scrolling_away_is_not_undone_by_the_next_sentence(self):body = "".join(f"第{index}句。\n" for index in range(400)).encode()context, page, posts, errors = self.open("txt", body, "text/plain; charset=utf-8")504 unmodified lines505506507508509510511512513514515516517518519520521522523524525526527528529530531532533504 unmodified linesfinally:context.close()def test_txt_reveal_inside_hidden_indent_uses_visible_sentence_without_changing_offset(self):line = ' 这是正常段落,朗读时必须能找到可见的一行。\n'text = line * 180context, page, posts, errors = self.open('txt', text.encode(), 'text/plain; charset=utf-8')try:offset = len(line) * 120 + 5self.play(page, posts)self.stop(page)before, after, raw, painted = page.evaluate('''async offset => {const a = CCRDSpeech.state().adapter;await a.ensure(offset + 1);const viewport = document.querySelector('#viewport');const before = viewport.scrollTop;await a.reveal(offset);return [before, viewport.scrollTop, a.range(offset, offset + 1).toString(), a.inView(offset)];}''', offset)self.assertEqual(raw, ' ')self.assertGreater(after, before + 500)self.assertTrue(painted)self.assertFalse(errors, errors)finally:context.close()def test_scrolling_away_is_not_undone_by_the_next_sentence(self):body = "".join(f"第{index}句。\n" for index in range(400)).encode()context, page, posts, errors = self.open("txt", body, "text/plain; charset=utf-8")
394 unmodified lines395396397398399394 unmodified linesf.search.clearMarks(); f.nextNavigation();const stale = await f.search.search(f.root, '', 'needle', f.generation, true, 1, f.navigation - 1);ensure(stale.length === 0 && !f.root.querySelector('mark'), 'stale occurrence selection');} finally { f.finish(); }}394 unmodified lines395396397398399400401402403404405406407408394 unmodified linesf.search.clearMarks(); f.nextNavigation();const stale = await f.search.search(f.root, '', 'needle', f.generation, true, 1, f.navigation - 1);ensure(stale.length === 0 && !f.root.querySelector('mark'), 'stale occurrence selection');f.root.innerHTML = '<span class="reader-text-padding" hidden> </span>needle';const raw = f.root.textContent;for (let i = 0; i < 2; i++) {const matches = await f.search.search(f.root, '', ' needle', f.generation, true, 0, f.navigation);ensure(matches.length === 1 && matches[0].target?.textContent === 'needle', 'visible part owns navigation');ensure(f.root.querySelector('.reader-text-padding mark')?.textContent === ' ', 'exact whitespace matched');f.search.clearMarks();ensure(f.root.textContent === raw && !f.root.querySelector('mark'), 'padding survives highlight cleanup');}} finally { f.finish(); }}
11 unmodified lines12131415161710 unmodified lines282930313233343 unmodified lines38394041424311 unmodified linesclass FakeElement {constructor(tag) { this.tag=tag;this.children=[];this.className='';this.dataset={}; }appendChild(node) { this.children.push(node);return node; }get lastChild() { return this.children.at(-1) ?? null; }get textContent() { return this.children.map(child=>child.textContent).join(''); }set textContent(value) { this.children=value ? [new FakeText(value)] : []; }10 unmodified linesassertReaderActive(){},markReaderContentReady(){events.push('ready');},waitForReader:waits,trackReaderResource(cleanup){events.push('track');this.cleanup=cleanup;return()=>events.push('untrack');},readerAbortError:()=>new DOMException('closed','AbortError'),awaitReader:promise=>Promise.resolve(promise),renderText:(mode,prepared)=>({mode,prepared})};Object.assign(context,createReaderTextFormat(context));return {context,events,restore(){globalThis.document=old.document;globalThis.Node=old.Node;globalThis.VoiceOfMLReaderSecurity=old.security;}};3 unmodified linesreturn new Response(stream);}const vCard = ['BEGIN:VCARD', 'VERSION:3.0', 'N:Example;Test;;;', 'FN:测试 Example', 'TITLE:Example role','ORG:Team\\;A;Division', 'EMAIL;TYPE=WORK,INTERNET:work@example.invalid',11 unmodified lines1213141516171810 unmodified lines293031323334353 unmodified lines394041424344454647484950515253545556575859606162636465666768697071727374757677787980818211 unmodified linesclass FakeElement {constructor(tag) { this.tag=tag;this.children=[];this.className='';this.dataset={}; }appendChild(node) { this.children.push(node);return node; }replaceChildren(...nodes) { this.children=nodes; }get lastChild() { return this.children.at(-1) ?? null; }get textContent() { return this.children.map(child=>child.textContent).join(''); }set textContent(value) { this.children=value ? [new FakeText(value)] : []; }10 unmodified linesassertReaderActive(){},markReaderContentReady(){events.push('ready');},waitForReader:waits,trackReaderResource(cleanup){events.push('track');this.cleanup=cleanup;return()=>events.push('untrack');},readerAbortError:()=>new DOMException('closed','AbortError'),awaitReader:promise=>Promise.resolve(promise),renderText:(mode,prepared)=>({mode,prepared}), setToc(toc){this.toc=toc;}};Object.assign(context,createReaderTextFormat(context));return {context,events,restore(){globalThis.document=old.document;globalThis.Node=old.Node;globalThis.VoiceOfMLReaderSecurity=old.security;}};3 unmodified linesreturn new Response(stream);}test('TXT layout retains raw text across streaming chunks, including hidden whitespace and chapters', async t => {const f=fixture(); t.after(f.restore);f.context.extension='txt';const line=' 这是一段完整的正文。保留行内 空格。\r\n';const text='第一卷 总览\r\n'+line.repeat(5)+' \r\n\r\n \r\n\t\r\n'+'第二节 续读\r\n'+line.repeat(8)+'第一章结束了。';const raw=encode(text), chunks=[];for(let i=0;i<raw.length;i+=43) chunks.push(raw.subarray(i,i+43));await f.context.renderPlainText(responseChunks(chunks));const root=f.context.content.children[0];assert.equal(root.textContent,text);const pieces=root.children.flatMap(block=>block.children);const hidden=pieces.filter(node=>node.className==='reader-text-padding');assert.equal(hidden.filter(node=>node.textContent===' '.repeat(10)).length,13);assert.ok(hidden.some(node=>node.textContent===' \r\n\t\r\n'));assert.deepEqual(f.context.toc.map(({label,depth})=>[label,depth]),[['第一卷 总览',0],['第二节 续读',1]]);let activated=false;f.context.toc[1].target.scrollIntoView=()=>{activated=true;};f.context.toc[1].activate(); assert.ok(activated);});test('TXT layout leaves ordinary indents and one or two blank lines alone, and caps decoration', async t => {const f=fixture(); t.after(f.restore);f.context.extension='txt';const ordinary='标题\n 第一段。\n\n第二段\n\n\n 单行对齐';const large='第一章 绪论\n'+('字'.repeat(45000))+'\n\n\n\n结束';const dense='第一章 绪论\n'+(' 这是测试段落。\n'.repeat(1030));const crossBlock='第一段\n'+'\n'.repeat(32800)+'第二段\n';for (const raw of [ordinary,large,dense,crossBlock]) {await f.context.renderPlainText(buffered(raw));const root=f.context.content.children.at(-1);assert.equal(root.textContent,raw);const hidden=root.children.flatMap(block=>block.children).filter(node=>node.className==='reader-text-padding');assert.equal(hidden.map(node=>node.textContent).join(''),raw===crossBlock?'\n'.repeat(32798):'');}assert.equal(f.context.toc,undefined);});const vCard = ['BEGIN:VCARD', 'VERSION:3.0', 'N:Example;Test;;;', 'FN:测试 Example', 'TITLE:Example role','ORG:Team\\;A;Division', 'EMAIL;TYPE=WORK,INTERNET:work@example.invalid',
scripts/reader/check_reader_text_coverage.mjs+2
static/reader.css+5-3
static/reader/formats/reader-html-format.mjs-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
tests/reader/dom-search/contracts.mjs+9
tests/reader/text/test_reader_text_baseline.mjs+40-1