vomebook commited on
Commit ·
7bd7f90
1
Parent(s): 2f99653
fix: repair Reader media playback and toolbar compatibility
Browse filesExtract shared full-text search control and cancel pending input on disposal.
Files changed (14)
- app.py+20-9
- scripts/check_reader_release.mjs+1
- static/icons/LICENSE-lucideAdded+15
- static/reader-resources.js+1
- static/reader-search-controller.mjsAdded+335
- static/reader.css+21
- static/reader.html+12-2
- static/reader.js+97-442
- tests/test_async_proxy.py+86-4
- tests/test_reader_architecture.js+9-2
- tests/test_reader_optimizations.py+4-4
- tests/test_reader_refactor.py+34-2
- tests/test_reader_style.py+45-1
- tests/test_static_contract.py+6-4
2098 unmodified lines2099210021012102210321042105277 unmodified lines23832384238523862387238850 unmodified lines243924402441244224432444244546 unmodified lines249224932494249524962497249810 unmodified lines25092510251125122513251425157 unmodified lines25232524252525262527252825294 unmodified lines2534253525362537253825392540254125422543254410 unmodified lines2555255625572558255925602561345 unmodified lines29072908290929102098 unmodified linesurl_validator=lambda url: validate_reader_bucket_redirect_url(url, source_url),validation_scope=(validate_reader_bucket_redirect_url, source_url),cache_control=reader_bucket_cache_control(resource_path),max_bytes=READER_DOCUMENT_MAX_BYTES if suffix == "pdf" else READER_RESOURCE_MAX_BYTES,media_type=media_type,)try:277 unmodified linestarget_url = validate_reader_source_url(url)except ValueError as exc:return JSONResponse({"error": str(exc)}, status_code=403)return await stream_reader_document(request, target_url)50 unmodified linesurl_validator=validate_reader_redirect_url, cache_control: str | None = None,max_bytes: int | None = None, media_type: str | None = None, validation_scope=None, _share_range: bool = True,):if max_bytes is None:max_bytes = READER_DOCUMENT_MAX_BYTESforwarded_headers = {name: request.headers[name]46 unmodified linesupstream = lease.response = await open_download_response(app.state.http_session,target_url,aiohttp.ClientTimeout(total=180, connect=15, sock_read=60),method=request.method,request_headers=forwarded_headers,url_validator=url_validator,10 unmodified linesif is_immutable_reader_asset(target_url)else headers.get("Cache-Control", "public, max-age=300"))headers["Content-Encoding"] = "identity"if media_type:headers["Content-Type"] = media_typestatus = upstream.status7 unmodified lineslength = int(declared_length)except (TypeError, ValueError):return JSONResponse({"error": "上游阅读文件长度无效"}, status_code=502)if length < 0 or length > max_bytes:return JSONResponse({"error": "阅读文件过大"}, status_code=413)content_range = upstream.headers.get("Content-Range")if status == 206:4 unmodified linesif (range_start > range_end or range_end >= total_lengthor (length is not None and length != range_end - range_start + 1)):return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)if total_length > max_bytes:return JSONResponse({"error": "阅读文件过大"}, status_code=413)elif status == 416:match = re.fullmatch(r"bytes\s+\*/([0-9]{1,20})", str(content_range or ""))if match and int(match.group(1)) > max_bytes:return JSONResponse({"error": "阅读文件过大"}, status_code=413)if request.method == "HEAD" or status == 304:return Response(status_code=status, headers=headers)10 unmodified linestry:async for chunk in upstream.content.iter_chunked(65536):total += len(chunk)if total > max_bytes:raise ReaderDocumentLimitError("阅读文件过大")if cacheable:chunks.append(chunk)345 unmodified linesfinally:if not transferred:await subscription.release()2098 unmodified lines20992100210121022103210421052106277 unmodified lines23842385238623872388238923902391239250 unmodified lines244324442445244624472448244924502451245246 unmodified lines249925002501250225032504250510 unmodified lines2516251725182519252025212522252325242525252625277 unmodified lines25352536253725382539254025414 unmodified lines2546254725482549255025512552255325542555255610 unmodified lines2567256825692570257125722573345 unmodified lines2919292029212098 unmodified linesurl_validator=lambda url: validate_reader_bucket_redirect_url(url, source_url),validation_scope=(validate_reader_bucket_redirect_url, source_url),cache_control=reader_bucket_cache_control(resource_path),max_bytes=(None if media_type.startswith(("audio/", "video/")) elseREADER_DOCUMENT_MAX_BYTES if suffix == "pdf" else READER_RESOURCE_MAX_BYTES),media_type=media_type,)try:277 unmodified linestarget_url = validate_reader_source_url(url)except ValueError as exc:return JSONResponse({"error": str(exc)}, status_code=403)source_type = READER_RESOURCE_TYPES.get(unquote(urlparse(target_url).path).rsplit(".", 1)[-1].lower(), "")if source_type.startswith(("audio/", "video/")):return await stream_reader_document(request, target_url, media_type=source_type)return await stream_reader_document(request, target_url)50 unmodified linesurl_validator=validate_reader_redirect_url, cache_control: str | None = None,max_bytes: int | None = None, media_type: str | None = None, validation_scope=None, _share_range: bool = True,):# Native media is streamed, not parsed or buffered as a complete document.# Bound transport memory and idle time instead of rejecting large recordings.is_media_stream = bool(media_type and media_type.startswith(("audio/", "video/")))if max_bytes is None and not is_media_stream:max_bytes = READER_DOCUMENT_MAX_BYTESforwarded_headers = {name: request.headers[name]46 unmodified linesupstream = lease.response = await open_download_response(app.state.http_session,target_url,aiohttp.ClientTimeout(total=None if is_media_stream else 180, connect=15, sock_read=60),method=request.method,request_headers=forwarded_headers,url_validator=url_validator,10 unmodified linesif is_immutable_reader_asset(target_url)else headers.get("Cache-Control", "public, max-age=300"))# Gecko treats any Content-Encoding header as compressed media and# disables length/range seeking. GZipMiddleware already excludes media.if is_media_stream:headers.pop("Content-Encoding", None)else:headers["Content-Encoding"] = "identity"if media_type:headers["Content-Type"] = media_typestatus = upstream.status7 unmodified lineslength = int(declared_length)except (TypeError, ValueError):return JSONResponse({"error": "上游阅读文件长度无效"}, status_code=502)if length < 0 or (max_bytes is not None and length > max_bytes):return JSONResponse({"error": "阅读文件过大"}, status_code=413)content_range = upstream.headers.get("Content-Range")if status == 206:4 unmodified linesif (range_start > range_end or range_end >= total_lengthor (length is not None and length != range_end - range_start + 1)):return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)if max_bytes is not None and total_length > max_bytes:return JSONResponse({"error": "阅读文件过大"}, status_code=413)elif status == 416:match = re.fullmatch(r"bytes\s+\*/([0-9]{1,20})", str(content_range or ""))if match and max_bytes is not None and int(match.group(1)) > max_bytes:return JSONResponse({"error": "阅读文件过大"}, status_code=413)if request.method == "HEAD" or status == 304:return Response(status_code=status, headers=headers)10 unmodified linestry:async for chunk in upstream.content.iter_chunked(65536):total += len(chunk)if max_bytes is not None and total > max_bytes:raise ReaderDocumentLimitError("阅读文件过大")if cacheable:chunks.append(chunk)345 unmodified linesfinally:if not transferred:await subscription.release()
181 unmodified lines182183184185186187181 unmodified lines"reader-runtime.js","reader-format-adapters.js","reader-security.js","pdf-worker-wrapper.mjs"];for (const file of exact) {181 unmodified lines182183184185186187188181 unmodified lines"reader-runtime.js","reader-format-adapters.js","reader-security.js","reader-search-controller.mjs","pdf-worker-wrapper.mjs"];for (const file of exact) {
123456789101112131415ISC License
Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2022.
Permission to use, copy, modify, and/or distribute this software for anypurpose with or without fee is hereby granted, provided that the abovecopyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIESWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OFMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FORANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGESWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN ANACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OFOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.99 unmodified lines10010110210310410599 unmodified lines"reader-runtime.js","reader-format-adapters.js","reader-security.js","reader-pdf-text.js","reader-v3.mjs","reader-book-text.js",99 unmodified lines10010110210310410510699 unmodified lines"reader-runtime.js","reader-format-adapters.js","reader-security.js","reader-search-controller.mjs","reader-pdf-text.js","reader-v3.mjs","reader-book-text.js",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335// Shared search presentation and task ownership; format matching stays in Reader.export function createReaderSearchController({ document, runtime, signal, nextGeneration, isCurrent, updateSearch, backend, navigation, panel}) { const search = runtime.state.search; const state = { page: null, failedPage: null, complete: false, pdfInProgress: false, chapterInProgress: false, pageLoader: null }; let inputTimer = 0, disposed = false; let renderedResults = [], renderedOffset = -1; const listeners = []; const active = () => !disposed && !signal.aborted; const current = generation => active() && isCurrent(generation); const busy = () => state.pdfInProgress || state.chapterInProgress; const pagedMode = () => ["epub-chapters", "pdf", "pdf-pages", "foliate"].includes(backend.mode());
const view = document.createElement("section"); view.id = "full-search-view"; view.className = "reader-panel-view full-search-view"; view.dataset.panelView = "full-search"; view.hidden = true; view.innerHTML = '<div class="full-search-bar"><input id="full-search-input" class="full-search-input" type="search" placeholder="搜索正文" aria-label="搜索正文"><button id="full-search-clear" class="icon-button" type="button" aria-label="清除全文搜索" title="清除">×</button></div><div id="full-search-status" class="full-search-status" role="status">输入关键词搜索正文</div><div class="full-search-nav"><button id="full-search-prev" type="button" disabled>上一个</button><button id="full-search-next" type="button" disabled>下一个</button></div><div id="full-search-results" class="full-search-results"></div>'; document.querySelector("#history-panel").insertBefore(view, document.querySelector(".reader-panel-tabs")); const button = document.querySelector("#full-search-toggle"); button.textContent = "全文搜索"; button.setAttribute("aria-label", "全文搜索"); const input = view.querySelector("#full-search-input"); const status = view.querySelector("#full-search-status"); const results = view.querySelector("#full-search-results"); const clear = view.querySelector("#full-search-clear"); clear.hidden = true; const pagination = document.createElement("div"); pagination.className = "full-search-pagination"; pagination.hidden = true; pagination.innerHTML = '<button id="full-search-page-prev" type="button">上一页</button><label>第 <input id="full-search-page" type="number" min="1" value="1" aria-label="搜索结果页码"> 页 <span id="full-search-pages"></span></label><button id="full-search-page-next" type="button">下一页</button>'; results.before(pagination); const cancel = document.createElement("button"); cancel.type = "button"; cancel.id = "full-search-cancel"; cancel.className = "text-action"; cancel.textContent = "取消搜索"; cancel.hidden = true; status.after(cancel); const retry = document.createElement("button"); retry.type = "button"; retry.id = "full-search-retry"; retry.className = "text-action"; retry.textContent = "重试搜索"; retry.hidden = true; cancel.after(retry);
function listen(target, type, callback) { target.addEventListener(type, callback); listeners.push(() => target.removeEventListener(type, callback)); } function clearInputTimer() { clearTimeout(inputTimer); inputTimer = 0; } function updateButton(open) { button.textContent = open ? "关闭全文搜索" : "全文搜索"; button.setAttribute("aria-label", button.textContent); } function updateClear() { clear.hidden = !input.value; } function updateNavigation() { view.querySelectorAll(".full-search-nav button").forEach(node => { node.disabled = !search.results.length; }); } function updatePagination() { const page = state.page; pagination.hidden = !page || !page.total; if (!page) return; const pages = Math.ceil(page.total / page.pageSize); const pageInput = pagination.querySelector("#full-search-page"); pageInput.value = String(Math.floor(page.offset / page.pageSize) + 1); pageInput.max = String(Math.max(1, pages)); pageInput.style.setProperty("--page-width", `${pageInput.max.length}ch`); pagination.querySelector("#full-search-pages").textContent = `/ ${pages}`; pagination.querySelector("#full-search-page-prev").disabled = busy() || page.offset === 0; pagination.querySelector("#full-search-page-next").disabled = busy() || page.offset + page.pageSize >= page.total; pageInput.disabled = busy(); } function snippetDom(snippet) { const node = document.createElement("span"); node.className = "full-search-snippet"; if (snippet.prefix) node.append(snippet.prefix); node.append(snippet.text.slice(0, snippet.matchStart)); const mark = document.createElement("mark"); mark.className = "search-match"; mark.textContent = snippet.text.slice(snippet.matchStart, snippet.matchStart + snippet.matchLength); node.append(mark, snippet.text.slice(snippet.matchStart + snippet.matchLength)); if (snippet.suffix) node.append(snippet.suffix); return node; } function render() { updatePagination(); updateNavigation(); const offset = state.page?.offset || 0; if (renderedOffset === offset && results.childElementCount === search.results.length && renderedResults.length === search.results.length && search.results.every((result, index) => result === renderedResults[index])) return; const fragment = document.createDocumentFragment(); for (const [index, result] of search.results.entries()) { const row = document.createElement("button"); const location = document.createElement("small"); row.type = "button"; row.className = "full-search-result"; location.className = "full-search-location"; location.textContent = result.location; const rank = document.createElement("span"); rank.className = "full-search-rank"; rank.textContent = `${offset + index + 1}.`; row.append(rank, location, snippetDom(result.snippet)); row.addEventListener("click", () => activate(index)); fragment.appendChild(row); } results.replaceChildren(fragment); renderedResults = search.results.slice(); renderedOffset = offset; } function resetResults(query = search.query) { state.complete = false; state.pdfInProgress = state.chapterInProgress = false; state.page = state.failedPage = state.pageLoader = null; updateSearch({ query, results: [], index: -1 }); render(); } function cancelPending() { clearInputTimer(); nextGeneration(); navigation.begin(); backend.chapterClient()?.cancel(); backend.pdfClient()?.cancel(); resetResults(); } function close() { clearInputTimer(); if (busy()) state.complete = false; nextGeneration(); if (state.chapterInProgress) backend.chapterClient()?.cancel(); if (state.pdfInProgress) backend.pdfClient()?.cancel(); state.pdfInProgress = state.chapterInProgress = false; cancel.hidden = retry.hidden = true; panel.hide(); updateButton(false); } async function run() { if (!active()) return; clearInputTimer(); const query = input.value.trim(); const generation = nextGeneration(); backend.pdfClient()?.cancel(); navigation.begin(); backend.clearMarks(); resetResults(query); retry.hidden = true; retry.textContent = "重试搜索"; cancel.hidden = !pagedMode() || !query; state.pdfInProgress = ["pdf", "pdf-pages", "foliate"].includes(backend.mode()) && !!query; state.chapterInProgress = backend.mode() === "epub-chapters" && !!query; if (!query) { backend.chapterClient()?.cancel(); status.textContent = "输入关键词搜索正文"; return; } status.textContent = "正在搜索正文…"; try { await backend.search(query, generation); if (!current(generation)) return; state.complete = true; state.pdfInProgress = state.chapterInProgress = false; render(); const total = state.page?.total ?? search.results.length; status.textContent = total ? `${total}${!state.page && total === 100 ? "+" : ""} 个结果` : "未找到正文匹配"; } catch (error) { if (current(generation)) { status.textContent = error.message || "正文搜索不可用"; retry.hidden = !pagedMode(); } } finally { if (current(generation)) { state.pdfInProgress = state.chapterInProgress = false; updatePagination(); cancel.hidden = true; updateNavigation(); } } } function applyChapterPage(page) { state.page = page; updateSearch({ results: page.results.map(backend.chapterResult), index: -1 }); } async function loadPage(offset, selectLast = null) { if (!active() || busy() || !state.page || (!backend.chapterClient() && !state.pageLoader)) return; state.failedPage = null; const generation = nextGeneration(); navigation.begin(); if (!["foliate", "epub-chapters"].includes(backend.mode())) cancel.hidden = false; retry.hidden = true; status.textContent = `${state.page.total} 个结果`; try { const loader = state.pageLoader; const page = await (loader ? loader(offset, generation) : backend.chapterClient().page(offset)); if (!current(generation)) return; if (loader) { state.page = page; updateSearch({ results: page.results, index: -1 }); } else applyChapterPage(page); render(); status.textContent = `${page.total} 个结果`; if (selectLast !== null) await activate(selectLast ? page.results.length - 1 : 0, false); } catch (error) { if (current(generation)) { status.textContent = error.message || "搜索结果加载失败"; state.failedPage = { offset, selectLast, query: search.query }; retry.textContent = "重试本页"; retry.hidden = false; } } finally { if (current(generation)) cancel.hidden = true; } } async function activate(index, closePanel = true) { if (!active()) return; const result = search.results[index]; if (!result) return; const previousIndex = search.index; const panelSerial = panel.serial(); const searchGeneration = runtime.currentGeneration("search"); const generation = navigation.begin(); const ownsResult = () => current(searchGeneration) && search.results[index] === result; updateSearch({ index }); try { const activated = await backend.activate(result, generation); if (activated === false && navigation.current(generation) && ownsResult()) { updateSearch({ index: previousIndex }); status.textContent = "搜索结果定位失败,请重试"; return; } if (activated === false || !navigation.current(generation) || search.results[index] !== result) return; if (status.textContent === "搜索结果定位失败,请重试") status.textContent = `${state.page?.total ?? search.results.length} 个结果`; if (closePanel && panelSerial === panel.serial() && current(searchGeneration)) panel.close(); else if (!closePanel) results.children[index]?.scrollIntoView({ block: "nearest" }); } catch (error) { if (error?.name !== "AbortError" && navigation.current(generation) && ownsResult()) { updateSearch({ index: previousIndex }); status.textContent = backend.mode() === "epub-chapters" ? error.message || "搜索结果定位失败,请重试" : "搜索结果定位失败,请重试"; } navigation.reportError(error, generation); } } function move(step) { const page = state.page; if (page?.total) { const next = search.index < 0 ? (step > 0 ? 0 : -1) : search.index + step; if (next < 0) return loadPage(page.offset ? page.offset - page.pageSize : Math.floor((page.total - 1) / page.pageSize) * page.pageSize, true); if (next >= search.results.length) return loadPage( page.offset + page.pageSize < page.total ? page.offset + page.pageSize : 0, false); return activate(next, false); } if (search.results.length) return activate((search.index + step + search.results.length) % search.results.length, false); } function toggle() { if (!active()) return; if (panel.isOpen() && !view.hidden) return close(); panel.show(); updateButton(true); updateClear(); input.focus(); if (search.query !== input.value.trim() || !state.complete) run(); else if (state.failedPage) retry.hidden = false; } function queue() { if (!active()) return; cancelPending(); cancel.hidden = retry.hidden = true; status.textContent = input.value.trim() ? "正在搜索正文…" : "输入关键词搜索正文"; inputTimer = setTimeout(run, 180); }
listen(retry, "click", async () => { const failed = state.failedPage; if (!failed || search.query !== failed.query) return run(); if (backend.chapterClient()?.failed) { await run(); if (!state.complete || search.query !== failed.query) return; } return loadPage(failed.offset, failed.selectLast); }); listen(cancel, "click", () => { cancelPending(); cancel.hidden = true; retry.hidden = false; retry.textContent = "重试搜索"; status.textContent = "搜索已取消"; }); listen(pagination.querySelector("#full-search-page-prev"), "click", () => loadPage(state.page.offset - state.page.pageSize)); listen(pagination.querySelector("#full-search-page-next"), "click", () => loadPage(state.page.offset + state.page.pageSize)); listen(pagination.querySelector("#full-search-page"), "change", event => { if (!state.page || !Number.isFinite(event.target.valueAsNumber)) return; const page = Math.max(1, Math.min(Math.ceil(state.page.total / state.page.pageSize), Math.floor(event.target.valueAsNumber))); const offset = (page - 1) * state.page.pageSize; if (offset !== state.page.offset) loadPage(offset); }); listen(button, "click", toggle); listen(input, "input", event => { updateClear(); if (!event.isComposing) queue(); }); listen(input, "focus", panel.focus); listen(input, "compositionend", queue); listen(clear, "click", () => { input.value = ""; updateClear(); run(); input.focus(); }); listen(view.querySelector("#full-search-prev"), "click", () => move(-1)); listen(view.querySelector("#full-search-next"), "click", () => move(1));
function dispose() { if (disposed) return; disposed = true; clearInputTimer(); for (const remove of listeners.splice(0)) remove(); renderedResults = []; state.page = state.failedPage = state.pageLoader = null; } return Object.freeze({ state, elements: Object.freeze({ view, button, input, status, results, pagination, cancel, retry }), render, updatePagination, applyChapterPage, loadPage, run, close, activate, move, dispose });}137 unmodified lines1381391401411421433 unmodified lines147148149150151152137 unmodified lines.icon-button {width: 32px;height: 32px;border: 0;background: transparent;color: inherit;3 unmodified linescursor: pointer;border-radius: 4px;font-size: 18px;}.text-button {height: 32px;137 unmodified lines1381391401411421431441451461471483 unmodified lines152153154155156157158159160161162163164165166167168169170171172173137 unmodified lines.icon-button {width: 32px;height: 32px;flex: none;margin: 0;padding: 0;appearance: none;-webkit-appearance: none;border: 0;background: transparent;color: inherit;3 unmodified linescursor: pointer;border-radius: 4px;font-size: 18px;font-family: inherit;line-height: 1;}.icon-button svg {display: block;width: 18px;height: 18px;pointer-events: none;}.icon-button::-moz-focus-inner {padding: 0;border: 0;}.icon-button:focus-visible {outline: 2px solid var(--reader-focus-color);outline-offset: 1px;}.text-button {height: 32px;
58 unmodified lines5960616263646525 unmodified lines919293949596979858 unmodified lines</head><body><header class="reader-toolbar"><button id="back" class="icon-button" type="button">←</button><div class="reader-heading"><strong id="title">在线阅读</strong><button id="reader-path" class="reader-path" type="button" hidden></button>25 unmodified linestitle="下载原文件"target="_blank"rel="noopener noreferrer">⇩</a><span id="download-feedback" role="status" hidden></span></div><button id="history" class="icon-button" type="button">☰</button>58 unmodified lines59606162636465666768697025 unmodified lines9697989910010110210310410510610710858 unmodified lines</head><body><header class="reader-toolbar"><button id="back" class="icon-button" type="button" aria-label="返回" title="返回"><!-- Lucide arrow-left, ISC; see icons/LICENSE-lucide --><svg class="lucide lucide-arrow-left" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="m12 19-7-7 7-7" /><path d="M19 12H5" /></svg></button><div class="reader-heading"><strong id="title">在线阅读</strong><button id="reader-path" class="reader-path" type="button" hidden></button>25 unmodified linestitle="下载原文件"target="_blank"rel="noopener noreferrer"><!-- Lucide download, ISC; see icons/LICENSE-lucide --><svg class="lucide lucide-download" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="7 10 12 15 17 10" /><line x1="12" x2="12" y1="15" y2="3" /></svg></a><span id="download-feedback" role="status" hidden></span></div><button id="history" class="icon-button" type="button">☰</button>
123465 unmodified lines4694704714724734744754764774785146 unmodified lines5625562656275628562956305631563256335634563556361088 unmodified lines672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682428 unmodified lines685368546855685668576858685968606861686268636864686568666867686838 unmodified lines69076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696015 unmodified lines697669776978697969806981698236 unmodified lines70197020702170227023702470257026702770287029703070317032180 unmodified lines721372147215721672177218721972207221722272237224722572267227722872297230723172327233155 unmodified lines7389739073917392739373947395739673971 unmodified line7399740074017402740374047405740687 unmodified lines7494749574967497749874997500750188 unmodified lines759075917592759375947595759675977598759976007601760276037604760576067607760832 unmodified lines764176427643764476457646764776487649126 unmodified lines777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036import "/static/reader-resources.js";import "/static/reader-contract.js";import "/static/reader-request-manager.js";465 unmodified lineslet chapterSearchConfiguration = null;let chapterSearchModulePromise = null;let chapterSearchClient = null;let chapterSearchPage = null;let failedSearchPage = null;let chapterSearchInProgress = false;let fullSearchComplete = false;trackReaderResource(() => {chapterSearchClient?.dispose();chapterSearchClient = null;5146 unmodified lines});mediaElement = media;let sourceRetried = false;media.addEventListener("error", () => {if (readerAbortController.signal.aborted) return;if (!sourceRetried && sourceUrl !== contentUrl && validSource(sourceUrl)) {sourceRetried = true;media._readerSourceRetry = true;media.src = sourceUrl;media.load();return;}1088 unmodified lineschapterNext.addEventListener("click", () =>activateChapter(adjacentTocIndex(1)));const fullSearchView = document.createElement("section");fullSearchView.id = "full-search-view";fullSearchView.className = "reader-panel-view full-search-view";fullSearchView.dataset.panelView = "full-search";fullSearchView.hidden = true;fullSearchView.innerHTML ='<div class="full-search-bar"><input id="full-search-input" class="full-search-input" type="search" placeholder="搜索正文" aria-label="搜索正文"><button id="full-search-clear" class="icon-button" type="button" aria-label="清除全文搜索" title="清除">×</button></div><div id="full-search-status" class="full-search-status" role="status">输入关键词搜索正文</div><div class="full-search-nav"><button id="full-search-prev" type="button" disabled>上一个</button><button id="full-search-next" type="button" disabled>下一个</button></div><div id="full-search-results" class="full-search-results"></div>';document.querySelector("#history-panel").insertBefore(fullSearchView, document.querySelector(".reader-panel-tabs"));const fullSearchButton = document.querySelector("#full-search-toggle");fullSearchButton.textContent = "全文搜索";fullSearchButton.setAttribute("aria-label", "全文搜索");fullSearchButton.hidden = !capability.features.search || (capability.mode === "pdf-pages" && !ocrManifestUrl && !pdfHybridUrl);const fullSearchInput = fullSearchView.querySelector("#full-search-input"),fullSearchStatus = fullSearchView.querySelector("#full-search-status"),fullSearchResultsNode = fullSearchView.querySelector("#full-search-results"),fullSearchClear = fullSearchView.querySelector("#full-search-clear");let fullSearchInputTimer = 0;fullSearchClear.hidden = true;function updateFullSearchButton(open) {fullSearchButton.textContent = open ? "关闭全文搜索" : "全文搜索";fullSearchButton.setAttribute("aria-label", fullSearchButton.textContent);}function updateFullSearchClear() {fullSearchClear.hidden = !fullSearchInput.value;}const chapterSearchPagination = document.createElement("div");chapterSearchPagination.className = "full-search-pagination";chapterSearchPagination.hidden = true;chapterSearchPagination.innerHTML ='<button id="full-search-page-prev" type="button">上一页</button><label>第 <input id="full-search-page" type="number" min="1" value="1" aria-label="搜索结果页码"> 页 <span id="full-search-pages"></span></label><button id="full-search-page-next" type="button">下一页</button>';fullSearchResultsNode.before(chapterSearchPagination);const fullSearchCancel = document.createElement("button");fullSearchCancel.type = "button";fullSearchCancel.id = "full-search-cancel";fullSearchCancel.className = "text-action";fullSearchCancel.textContent = "取消搜索";fullSearchCancel.hidden = true;fullSearchStatus.after(fullSearchCancel);const fullSearchRetry = document.createElement("button");fullSearchRetry.type = "button";fullSearchRetry.id = "full-search-retry";fullSearchRetry.className = "text-action";fullSearchRetry.textContent = "重试搜索";fullSearchRetry.hidden = true;fullSearchCancel.after(fullSearchRetry);fullSearchRetry.addEventListener("click", async () => {const failed = failedSearchPage;if (!failed || searchState.query !== failed.query) return runFullSearch();if (chapterSearchClient?.failed) {await runFullSearch();if (!fullSearchComplete || searchState.query !== failed.query) return;}return loadChapterSearchPage(failed.offset, failed.selectLast);});fullSearchCancel.addEventListener("click", () => {nextReaderGeneration("search");beginReaderNavigation();chapterSearchClient?.cancel();pdfBookSearchClient?.cancel();pdfSearchInProgress = false;chapterSearchInProgress = false;chapterSearchPage = null;failedSearchPage = null;pdfSearchPageLoader = null;fullSearchComplete = false;updateSearchState({ results: [], index: -1 });renderFullSearchResults();fullSearchCancel.hidden = true;fullSearchRetry.hidden = false;fullSearchRetry.textContent = "重试搜索";fullSearchStatus.textContent = "搜索已取消";});chapterSearchPagination.querySelector("#full-search-page-prev").addEventListener("click", () =>loadChapterSearchPage(chapterSearchPage.offset - chapterSearchPage.pageSize));chapterSearchPagination.querySelector("#full-search-page-next").addEventListener("click", () =>loadChapterSearchPage(chapterSearchPage.offset + chapterSearchPage.pageSize));chapterSearchPagination.querySelector("#full-search-page").addEventListener("change", (event) => {if (!chapterSearchPage || !Number.isFinite(event.target.valueAsNumber)) return;const page = Math.max(1, Math.min(Math.ceil(chapterSearchPage.total / chapterSearchPage.pageSize),Math.floor(event.target.valueAsNumber)));const offset = (page - 1) * chapterSearchPage.pageSize;if (offset !== chapterSearchPage.offset) loadChapterSearchPage(offset);});// Full-text search: format matching, result presentation, and navigation.function fullSearchPageOffset(total, requestedOffset, pageSize = 50) {return Math.max(0, Math.min(Math.floor(Math.max(0, total - 1) / pageSize),28 unmodified lines});if (isReaderGenerationCurrent("search", generation)) applyChapterSearchPage(page);}function applyChapterSearchPage(page) {chapterSearchPage = page;updateSearchState({results: page.results.map((result) => ({...result,activate: (generation) => navigateChapterSearchResult(result, generation)})),index: -1});}async function navigateChapterSearchResult(result, generation) {const article = await chapterManifestLoader?.(result.chapterIndex);if (!article || !isReaderGenerationCurrent("navigation", generation)) return false;38 unmodified linesscheduleSave();return true;}function updateChapterSearchPagination() {const page = chapterSearchPage;chapterSearchPagination.hidden = !page || !page.total;if (!page) return;const pages = Math.ceil(page.total / page.pageSize);const input = chapterSearchPagination.querySelector("#full-search-page");input.value = String(Math.floor(page.offset / page.pageSize) + 1);input.max = String(Math.max(1, pages));input.style.setProperty("--page-width", `${input.max.length}ch`);chapterSearchPagination.querySelector("#full-search-pages").textContent = `/ ${pages}`;chapterSearchPagination.querySelector("#full-search-page-prev").disabled =pdfSearchInProgress || chapterSearchInProgress || page.offset === 0;chapterSearchPagination.querySelector("#full-search-page-next").disabled =pdfSearchInProgress || chapterSearchInProgress || page.offset + page.pageSize >= page.total;input.disabled = pdfSearchInProgress || chapterSearchInProgress;}async function loadChapterSearchPage(offset, selectLast = null) {if (pdfSearchInProgress || chapterSearchInProgress || !chapterSearchPage ||(!chapterSearchClient && !pdfSearchPageLoader)) return;failedSearchPage = null;const generation = nextReaderGeneration("search");beginReaderNavigation();if (!["foliate", "epub-chapters"].includes(capability.mode)) fullSearchCancel.hidden = false;fullSearchRetry.hidden = true;fullSearchStatus.textContent = `${chapterSearchPage.total} 个结果`;try {const pdfLoader = pdfSearchPageLoader;const page = await (pdfLoader ? pdfLoader(offset, generation) : chapterSearchClient.page(offset));if (!isReaderGenerationCurrent("search", generation)) return;if (pdfLoader) {chapterSearchPage = page;updateSearchState({ results: page.results, index: -1 });} else applyChapterSearchPage(page);renderFullSearchResults();fullSearchStatus.textContent = `${page.total} 个结果`;if (selectLast !== null)await activateFullSearchResult(selectLast ? page.results.length - 1 : 0, false);} catch (error) {if (isReaderGenerationCurrent("search", generation)) {fullSearchStatus.textContent = error.message || "搜索结果加载失败";failedSearchPage = { offset, selectLast, query: searchState.query };fullSearchRetry.textContent = "重试本页";fullSearchRetry.hidden = false;}} finally {if (isReaderGenerationCurrent("search", generation)) fullSearchCancel.hidden = true;}}async function fullSearchFoliateMatches(query, generation) {if (!epubRendition?.search) return [];const groups = [], firstPage = [];15 unmodified lines}};};pdfSearchPageLoader = async (requestedOffset, pageGeneration = readerRuntime.currentGeneration("search")) => {const pageSize = 50;const offset = fullSearchPageOffset(total, requestedOffset, pageSize);if (!offset) return { total, offset, pageSize, results: firstPage.slice() };36 unmodified linesfirstPage.push(toResult(item, group.label, index));}total += group.count;chapterSearchPage = { total, offset: 0, pageSize: 50, results: firstPage.slice() };updateSearchState({ results: chapterSearchPage.results, index: -1 });renderFullSearchResults();fullSearchStatus.textContent = `${total} 个结果(正在搜索…)`;await waitForReader();if (!isReaderGenerationCurrent("search", generation)) return [];}chapterSearchPage = { total, offset: 0, pageSize: 50, results: firstPage.slice() };return firstPage;}function fullSearchEscape(value) {180 unmodified linessuffix: end < text.length ? "…" : ""};}function fullSearchSnippetDom(snippet) {const node = document.createElement("span");node.className = "full-search-snippet";if (snippet.prefix) node.append(snippet.prefix);node.append(snippet.text.slice(0, snippet.matchStart));const mark = document.createElement("mark");mark.className = "search-match";mark.textContent = snippet.text.slice(snippet.matchStart,snippet.matchStart + snippet.matchLength);node.append(mark, snippet.text.slice(snippet.matchStart + snippet.matchLength));if (snippet.suffix) node.append(snippet.suffix);return node;}function createFullSearchHeadingLookup(root, offsets) {const entries = navigationState.tocEntries, boundaries = [];const headings = entries.filter(entry => entry.target);155 unmodified linesgroups.push(group);total += group.count;if (progressive && (start === 0 || (group.count && total <= 50) || groups.length % 8 === 0)) {pdfSearchPageLoader = page;chapterSearchPage = page(0);updateSearchState({ results: chapterSearchPage.results, index: -1 });renderFullSearchResults();fullSearchStatus.textContent = `${total} 个结果(正在搜索…)`;}1 unmodified lineif (!isReaderGenerationCurrent("search", generation)) return [];}if (progressive) {pdfSearchPageLoader = page;chapterSearchPage = page(0);}if (occurrence !== null) {if (!isReaderGenerationCurrent("navigation", navigationGeneration)) return [];87 unmodified linesfoliateScrollAnchors.remember();return true;}let pdfSearchPageLoader = null;let pdfSearchInProgress = false;async function ensurePdfBookSearchClient(manifest) {let textUrl = "";let partitioned = null;88 unmodified linesif (page.offset === 0) firstPageResults = results;return { ...page, results };};pdfSearchPageLoader = async offset => attach(await client.page(offset));const page = await client.search(query, partial => {if (!isReaderGenerationCurrent("search", generation)) return;chapterSearchPage = attach(partial);updateSearchState({ results: chapterSearchPage.results, index: -1 });renderFullSearchResults();fullSearchStatus.textContent = partial.total? `${partial.total} 个结果(正在搜索… ${partial.scanned} / ${partial.pages} 页)`: `正在搜索正文… ${partial.scanned} / ${partial.pages} 页`;});if (!isReaderGenerationCurrent("search", generation)) return [];chapterSearchPage = attach(page);return chapterSearchPage.results;}function makePdfSearchPageLoader(groups, total, pattern, firstPage) {32 unmodified linesfunction publishPdfSearchProgress(generation, groups, total, pattern, firstPage, scanned, pages) {if (!isReaderGenerationCurrent("search", generation)) return false;pdfSearchPageLoader = makePdfSearchPageLoader(groups, total, pattern, firstPage);chapterSearchPage = { total, offset: 0, pageSize: 50, results: firstPage.slice() };updateSearchState({ results: chapterSearchPage.results, index: -1 });renderFullSearchResults();fullSearchStatus.textContent = total? `${total} 个结果(正在搜索… ${scanned} / ${pages} 页)`126 unmodified lines}if (!hasText) throw new Error("此 PDF 尚无可搜索文字层,需要完成 OCR 后才能搜索正文");publishPdfSearchProgress(generation, groups, total, pattern, firstPage, pdf.numPages, pdf.numPages);return chapterSearchPage.results;}let fullSearchRenderedResults = [];let fullSearchRenderedOffset = -1;function renderFullSearchResults() {updateChapterSearchPagination();fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {button.disabled = !searchState.results.length;});const offset = chapterSearchPage?.offset || 0;if (fullSearchRenderedOffset === offset &&fullSearchResultsNode.childElementCount === searchState.results.length &&fullSearchRenderedResults.length === searchState.results.length &&searchState.results.every((result, index) => result === fullSearchRenderedResults[index])) return;const fragment = document.createDocumentFragment();for (const [index, result] of searchState.results.entries()) {const row = document.createElement("button"),location = document.createElement("small");row.type = "button";row.className = "full-search-result";location.className = "full-search-location";location.textContent = result.location;const rank = document.createElement("span");rank.className = "full-search-rank";rank.textContent = `${offset + index + 1}.`;row.append(rank, location, fullSearchSnippetDom(result.snippet));row.addEventListener("click", () => activateFullSearchResult(index));fragment.appendChild(row);}fullSearchResultsNode.replaceChildren(fragment);fullSearchRenderedResults = searchState.results.slice();fullSearchRenderedOffset = offset;}function closeFullSearchView() {clearTimeout(fullSearchInputTimer);fullSearchInputTimer = 0;if (pdfSearchInProgress || chapterSearchInProgress) fullSearchComplete = false;nextReaderGeneration("search");if (chapterSearchInProgress) chapterSearchClient?.cancel();if (pdfSearchInProgress) pdfBookSearchClient?.cancel();pdfSearchInProgress = false;chapterSearchInProgress = false;fullSearchCancel.hidden = true;fullSearchRetry.hidden = true;selectPanel(mediaElement ? "media" : "toc");updateFullSearchButton(false);}async function runFullSearch() {clearTimeout(fullSearchInputTimer);fullSearchInputTimer = 0;const query = fullSearchInput.value.trim();fullSearchComplete = false;failedSearchPage = null;const generation = nextReaderGeneration("search");pdfBookSearchClient?.cancel();beginReaderNavigation();clearFullSearchMarks();updateSearchState({ query, results: [], index: -1 });chapterSearchPage = null;pdfSearchPageLoader = null;updateChapterSearchPagination();fullSearchRetry.hidden = true;fullSearchRetry.textContent = "重试搜索";fullSearchCancel.hidden = !["epub-chapters", "pdf", "pdf-pages", "foliate"].includes(capability.mode) || !query;pdfSearchInProgress = ["pdf", "pdf-pages", "foliate"].includes(capability.mode) && !!query;chapterSearchInProgress = capability.mode === "epub-chapters" && !!query;fullSearchResultsNode.textContent = "";fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {button.disabled = true;});if (!query) {chapterSearchClient?.cancel();fullSearchStatus.textContent = "输入关键词搜索正文";return;}fullSearchStatus.textContent = "正在搜索正文…";try {if ((capability.mode === "pdf" || pdfHybridUrl) && !ocrManifestUrl) {if (pdfHybridUrl) await pdfHybridDocumentPromise;await fullSearchPdfMatches(query, generation);}else if (["pdf", "pdf-pages"].includes(capability.mode))publishSearchResults(generation, await searchConcentratedPdf(query, generation));else if (capability.mode === "foliate")publishSearchResults(generation, await fullSearchFoliateMatches(query, generation));else if (capability.mode === "epub-chapters") await searchChapterBook(query, generation);else if (["text", "markdown", "docx"].includes(capability.mode))publishSearchResults(generation,await fullSearchDomMatches(content, "阅读位置", query, generation, true));else if (capability.mode === "html")publishSearchResults(generation,htmlFrame?.contentDocument?.body? await fullSearchDomMatches(htmlFrame.contentDocument.body,"HTML 阅读位置",query,generation,true): []);else throw new Error("此格式没有可搜索文本");if (!isReaderGenerationCurrent("search", generation)) return;fullSearchComplete = true;pdfSearchInProgress = false;chapterSearchInProgress = false;renderFullSearchResults();fullSearchStatus.textContent = chapterSearchPage? chapterSearchPage.total? `${chapterSearchPage.total} 个结果`: "未找到正文匹配": searchState.results.length? `${searchState.results.length}${searchState.results.length === 100 ? "+" : ""} 个结果`: "未找到正文匹配";} catch (error) {if (isReaderGenerationCurrent("search", generation)) {pdfSearchInProgress = false;chapterSearchInProgress = false;fullSearchStatus.textContent = error.message || "正文搜索不可用";fullSearchRetry.hidden = !["epub-chapters", "pdf", "pdf-pages", "foliate"].includes(capability.mode);}} finally {if (isReaderGenerationCurrent("search", generation))pdfSearchInProgress = false;if (isReaderGenerationCurrent("search", generation)) {chapterSearchInProgress = false;updateChapterSearchPagination();}if (isReaderGenerationCurrent("search", generation)) fullSearchCancel.hidden = true;if (isReaderGenerationCurrent("search", generation))fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {button.disabled = !searchState.results.length;});}}async function activateFullSearchResult(index, closePanel = true) {const result = searchState.results[index];if (!result) return;const previousIndex = searchState.index;const panelSerial = readerPanelInteractionSerial;const searchGeneration = readerRuntime.currentGeneration("search");const generation = beginReaderNavigation();updateSearchState({ index });try {const activated = result.cfi? await navigateFoliateSearchResult(result, generation): await result.activate(generation);if (activated === false && isReaderGenerationCurrent("navigation", generation) &&isReaderGenerationCurrent("search", searchGeneration) && searchState.results[index] === result) {updateSearchState({ index: previousIndex });fullSearchStatus.textContent = "搜索结果定位失败,请重试";return;}if (activated === false ||!isReaderGenerationCurrent("navigation", generation) ||searchState.results[index] !== result)return;if (fullSearchStatus.textContent === "搜索结果定位失败,请重试")fullSearchStatus.textContent = `${chapterSearchPage?.total ?? searchState.results.length} 个结果`;if (closePanel && panelSerial === readerPanelInteractionSerial &&isReaderGenerationCurrent("search", searchGeneration))setReaderPanelOpen(false, true);else if (!closePanel) fullSearchResultsNode.children[index]?.scrollIntoView({ block: "nearest" });} catch (error) {if (error?.name !== "AbortError" && isReaderGenerationCurrent("navigation", generation) &&isReaderGenerationCurrent("search", searchGeneration) && searchState.results[index] === result) {updateSearchState({ index: previousIndex });fullSearchStatus.textContent = capability.mode === "epub-chapters"? error.message || "搜索结果定位失败,请重试": "搜索结果定位失败,请重试";}reportNavigationError(error, generation);}}function moveFullSearch(step) {if (chapterSearchPage?.total) {const page = chapterSearchPage;const next = searchState.index < 0 ? (step > 0 ? 0 : -1) : searchState.index + step;if (next < 0)return loadChapterSearchPage(page.offset? page.offset - page.pageSize: Math.floor((page.total - 1) / page.pageSize) * page.pageSize,true);if (next >= searchState.results.length)return loadChapterSearchPage(page.offset + page.pageSize < page.total ? page.offset + page.pageSize : 0,false);return activateFullSearchResult(next, false);}if (searchState.results.length)return activateFullSearchResult((searchState.index + step + searchState.results.length) % searchState.results.length,false);}function toggleFullSearch() {const panel = document.querySelector("#history-panel");if (panel.classList.contains("is-open") && !fullSearchView.hidden) {closeFullSearchView();return;}setReaderPanelOpen(true);selectPanel("full-search");updateFullSearchButton(true);updateFullSearchClear();fullSearchInput.focus();if (searchState.query !== fullSearchInput.value.trim() || !fullSearchComplete) runFullSearch();else if (failedSearchPage) fullSearchRetry.hidden = false;}fullSearchButton.addEventListener("click", toggleFullSearch);function queueFullSearch() {clearTimeout(fullSearchInputTimer);nextReaderGeneration("search");beginReaderNavigation();chapterSearchClient?.cancel();pdfBookSearchClient?.cancel();fullSearchComplete = false;pdfSearchInProgress = false;chapterSearchInProgress = false;chapterSearchPage = null;failedSearchPage = null;pdfSearchPageLoader = null;updateSearchState({ results: [], index: -1 });renderFullSearchResults();fullSearchCancel.hidden = true;fullSearchRetry.hidden = true;fullSearchStatus.textContent = fullSearchInput.value.trim() ? "正在搜索正文…" : "输入关键词搜索正文";fullSearchInputTimer = setTimeout(runFullSearch, 180);}fullSearchInput.addEventListener("input", (event) => {updateFullSearchClear();if (!event.isComposing) queueFullSearch();});fullSearchInput.addEventListener("focus", () => { readerPanelInteractionSerial++; });fullSearchInput.addEventListener("compositionend", queueFullSearch);fullSearchView.querySelector("#full-search-clear").addEventListener("click", () => {fullSearchInput.value = "";updateFullSearchClear();runFullSearch();fullSearchInput.focus();});fullSearchView.querySelector("#full-search-prev").addEventListener("click", () => moveFullSearch(-1));fullSearchView.querySelector("#full-search-next").addEventListener("click", () => moveFullSearch(1));function syncCapabilityControls() {content.dataset.mode = capability.mode || "unsupported";pageInvertToggle.hidden = !["pdf", "pdf-pages"].includes(capability.mode);1234465 unmodified lines4704714724734744754765146 unmodified lines562356245625562656275628562956305631563256335634563556361088 unmodified lines6725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677128 unmodified lines680068016802680368046805680638 unmodified lines684568466847684868496850685115 unmodified lines686768686869687068716872687336 unmodified lines69106911691269136914691569166917691869196920692169226923180 unmodified lines7104710571067107710871097110155 unmodified lines7266726772687269727072717272727372741 unmodified line7276727772787279728072817282728387 unmodified lines737173727373737473757376737788 unmodified lines746674677468746974707471747274737474747574767477747874797480748174827483748432 unmodified lines751775187519752075217522752375247525126 unmodified lines7652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691import { createReaderSearchController } from "./reader-search-controller.mjs";import "/static/reader-resources.js";import "/static/reader-contract.js";import "/static/reader-request-manager.js";465 unmodified lineslet chapterSearchConfiguration = null;let chapterSearchModulePromise = null;let chapterSearchClient = null;trackReaderResource(() => {chapterSearchClient?.dispose();chapterSearchClient = null;5146 unmodified lines});mediaElement = media;let sourceRetried = false;const originalMode = VoiceOfMLReader.capability(resolvedReaderData?.original_extension || extension).mode;const retryUrl = originalMode === mode && validSource(downloadUrl) ? downloadUrl : sourceUrl;media.addEventListener("error", () => {if (readerAbortController.signal.aborted) return;if (!sourceRetried && retryUrl !== media.src && validSource(retryUrl)) {sourceRetried = true;media._readerSourceRetry = true;media.src = retryUrl;media.load();return;}1088 unmodified lineschapterNext.addEventListener("click", () =>activateChapter(adjacentTocIndex(1)));const fullSearchController = createReaderSearchController({document, runtime: readerRuntime, signal: readerAbortController.signal,nextGeneration: () => nextReaderGeneration("search"),isCurrent: generation => isReaderGenerationCurrent("search", generation),updateSearch: updateSearchState,backend: {mode: () => capability.mode,search: searchReaderText,clearMarks: clearFullSearchMarks,chapterClient: () => chapterSearchClient,pdfClient: () => pdfBookSearchClient,chapterResult: result => ({ ...result,activate: generation => navigateChapterSearchResult(result, generation) }),activate: (result, generation) => result.cfi? navigateFoliateSearchResult(result, generation) : result.activate(generation)},navigation: {begin: beginReaderNavigation,current: generation => isReaderGenerationCurrent("navigation", generation),reportError: reportNavigationError},panel: {isOpen: () => document.querySelector("#history-panel").classList.contains("is-open"),serial: () => readerPanelInteractionSerial,show: () => { setReaderPanelOpen(true); selectPanel("full-search"); },hide: () => selectPanel(mediaElement ? "media" : "toc"),close: () => setReaderPanelOpen(false, true),focus: () => { readerPanelInteractionSerial++; }}});trackReaderResource(fullSearchController.dispose);const fullSearchSession = fullSearchController.state;const {render: renderFullSearchResults, applyChapterPage: applyChapterSearchPage,run: runFullSearch, close: closeFullSearchView} = fullSearchController;const {view: fullSearchView, button: fullSearchButton, input: fullSearchInput,status: fullSearchStatus} = fullSearchController.elements;// Format-specific search backends publish through the shared controller.function fullSearchPageOffset(total, requestedOffset, pageSize = 50) {return Math.max(0, Math.min(Math.floor(Math.max(0, total - 1) / pageSize),28 unmodified lines});if (isReaderGenerationCurrent("search", generation)) applyChapterSearchPage(page);}async function navigateChapterSearchResult(result, generation) {const article = await chapterManifestLoader?.(result.chapterIndex);if (!article || !isReaderGenerationCurrent("navigation", generation)) return false;38 unmodified linesscheduleSave();return true;}async function fullSearchFoliateMatches(query, generation) {if (!epubRendition?.search) return [];const groups = [], firstPage = [];15 unmodified lines}};};fullSearchSession.pageLoader = async (requestedOffset, pageGeneration = readerRuntime.currentGeneration("search")) => {const pageSize = 50;const offset = fullSearchPageOffset(total, requestedOffset, pageSize);if (!offset) return { total, offset, pageSize, results: firstPage.slice() };36 unmodified linesfirstPage.push(toResult(item, group.label, index));}total += group.count;fullSearchSession.page = { total, offset: 0, pageSize: 50, results: firstPage.slice() };updateSearchState({ results: fullSearchSession.page.results, index: -1 });renderFullSearchResults();fullSearchStatus.textContent = `${total} 个结果(正在搜索…)`;await waitForReader();if (!isReaderGenerationCurrent("search", generation)) return [];}fullSearchSession.page = { total, offset: 0, pageSize: 50, results: firstPage.slice() };return firstPage;}function fullSearchEscape(value) {180 unmodified linessuffix: end < text.length ? "…" : ""};}function createFullSearchHeadingLookup(root, offsets) {const entries = navigationState.tocEntries, boundaries = [];const headings = entries.filter(entry => entry.target);155 unmodified linesgroups.push(group);total += group.count;if (progressive && (start === 0 || (group.count && total <= 50) || groups.length % 8 === 0)) {fullSearchSession.pageLoader = page;fullSearchSession.page = page(0);updateSearchState({ results: fullSearchSession.page.results, index: -1 });renderFullSearchResults();fullSearchStatus.textContent = `${total} 个结果(正在搜索…)`;}1 unmodified lineif (!isReaderGenerationCurrent("search", generation)) return [];}if (progressive) {fullSearchSession.pageLoader = page;fullSearchSession.page = page(0);}if (occurrence !== null) {if (!isReaderGenerationCurrent("navigation", navigationGeneration)) return [];87 unmodified linesfoliateScrollAnchors.remember();return true;}async function ensurePdfBookSearchClient(manifest) {let textUrl = "";let partitioned = null;88 unmodified linesif (page.offset === 0) firstPageResults = results;return { ...page, results };};fullSearchSession.pageLoader = async offset => attach(await client.page(offset));const page = await client.search(query, partial => {if (!isReaderGenerationCurrent("search", generation)) return;fullSearchSession.page = attach(partial);updateSearchState({ results: fullSearchSession.page.results, index: -1 });renderFullSearchResults();fullSearchStatus.textContent = partial.total? `${partial.total} 个结果(正在搜索… ${partial.scanned} / ${partial.pages} 页)`: `正在搜索正文… ${partial.scanned} / ${partial.pages} 页`;});if (!isReaderGenerationCurrent("search", generation)) return [];fullSearchSession.page = attach(page);return fullSearchSession.page.results;}function makePdfSearchPageLoader(groups, total, pattern, firstPage) {32 unmodified linesfunction publishPdfSearchProgress(generation, groups, total, pattern, firstPage, scanned, pages) {if (!isReaderGenerationCurrent("search", generation)) return false;fullSearchSession.pageLoader = makePdfSearchPageLoader(groups, total, pattern, firstPage);fullSearchSession.page = { total, offset: 0, pageSize: 50, results: firstPage.slice() };updateSearchState({ results: fullSearchSession.page.results, index: -1 });renderFullSearchResults();fullSearchStatus.textContent = total? `${total} 个结果(正在搜索… ${scanned} / ${pages} 页)`126 unmodified lines}if (!hasText) throw new Error("此 PDF 尚无可搜索文字层,需要完成 OCR 后才能搜索正文");publishPdfSearchProgress(generation, groups, total, pattern, firstPage, pdf.numPages, pdf.numPages);return fullSearchSession.page.results;}async function searchReaderText(query, generation) {if ((capability.mode === "pdf" || pdfHybridUrl) && !ocrManifestUrl) {if (pdfHybridUrl) await pdfHybridDocumentPromise;await fullSearchPdfMatches(query, generation);}else if (["pdf", "pdf-pages"].includes(capability.mode))publishSearchResults(generation, await searchConcentratedPdf(query, generation));else if (capability.mode === "foliate")publishSearchResults(generation, await fullSearchFoliateMatches(query, generation));else if (capability.mode === "epub-chapters") await searchChapterBook(query, generation);else if (["text", "markdown", "docx"].includes(capability.mode))publishSearchResults(generation,await fullSearchDomMatches(content, "阅读位置", query, generation, true));else if (capability.mode === "html")publishSearchResults(generation,htmlFrame?.contentDocument?.body? await fullSearchDomMatches(htmlFrame.contentDocument.body,"HTML 阅读位置",query,generation,true): []);else throw new Error("此格式没有可搜索文本");}function syncCapabilityControls() {content.dataset.mode = capability.mode || "unsupported";pageInvertToggle.hidden = !["pdf", "pdf-pages"].includes(capability.mode);
402 unmodified lines4034044054064074084094104114124134144154164174184194204214224231 unmodified line425426427428429430431402 unmodified lineswhole_read.assert_not_awaited()self.assertEqual(response.status_code, status)self.assertEqual(response.headers["content-type"], mime)self.assertEqual(session.urls[0][1]["headers"], {"Accept-Encoding": "identity", **forwarded})if method != "HEAD":self.assertEqual([chunk async for chunk in response.body_iterator], [b"ab"])if forwarded:cached = await app.api_reader_bucket_resource(path, SimpleNamespace(method=method, headers=forwarded))self.assertEqual(cached.body, b"ab")self.assertEqual(len(session.urls), 1)self.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)async def test_bucket_media_preserves_resource_limit_and_cancellation_cleanup(self):path = f"media/video/native/{'a' * 64}/video.mp4"for status, headers in ((200, {"Content-Length": str(app.READER_RESOURCE_MAX_BYTES + 1)}),(206, {"Content-Length": "2", "Content-Range": f"bytes 0-1/{app.READER_RESOURCE_MAX_BYTES + 1}"}),):upstream = FakeResponse(status, headers)app.app.state.http_session = FakeSession([upstream])1 unmodified lineapp.app.state.reader_range_cache = OrderedDict()app.app.state.reader_range_cache_bytes = 0response = await app.api_reader_bucket_resource(path, SimpleNamespace(method="GET", headers={"Range": "bytes=0-1"}))self.assertEqual(response.status_code, 413)self.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)with patch.object(app, "open_download_response", AsyncMock(side_effect=asyncio.CancelledError)):402 unmodified lines4034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045051 unmodified line507508509510511512513402 unmodified lineswhole_read.assert_not_awaited()self.assertEqual(response.status_code, status)self.assertEqual(response.headers["content-type"], mime)self.assertNotIn("content-encoding", response.headers)self.assertEqual(session.urls[0][1]["headers"], {"Accept-Encoding": "identity", **forwarded})if method != "HEAD":self.assertEqual([chunk async for chunk in response.body_iterator], [b"ab"])if forwarded:cached = await app.api_reader_bucket_resource(path, SimpleNamespace(method=method, headers=forwarded))self.assertEqual(cached.body, b"ab")self.assertNotIn("content-encoding", cached.headers)self.assertEqual(len(session.urls), 1)self.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)async def test_media_remains_unencoded_through_real_gzip_middleware_and_range_cache(self):path = f"media/audio/native/{'a' * 64}/audio.mp3"payload = b"media" * 400for status in (200, 206):forwarded = {"Range": f"bytes=0-{len(payload) - 1}"} if status == 206 else {}headers = {"Content-Length": str(len(payload)), "Content-Encoding": "identity"}if status == 206:headers["Content-Range"] = f"bytes 0-{len(payload) - 1}/{len(payload) * 2}"upstream = FakeResponse(status, headers, chunks=(payload,))app.app.state.http_session = FakeSession([upstream])app.app.state.reader_range_cache = OrderedDict()app.app.state.reader_range_cache_bytes = 0for cached in (False, True) if status == 206 else (False,):with self.subTest(status=status, cached=cached):response = await app.api_reader_bucket_resource(path, SimpleNamespace(method="GET", headers=forwarded))messages = []async def serve(scope, receive, send):await response(scope, receive, send)async def receive():return {"type": "http.request", "body": b"", "more_body": False}async def send(message):messages.append(message)await app.GZipMiddleware(serve, minimum_size=1)({"type": "http", "method": "GET", "asgi": {"spec_version": "2.4"},"headers": [(b"accept-encoding", b"gzip")]}, receive, send)start = messages[0]self.assertEqual(start["status"], status)self.assertNotIn(b"content-encoding", dict(start["headers"]))self.assertEqual(dict(start["headers"])[b"content-length"], str(len(payload)).encode())self.assertEqual(b"".join(message.get("body", b"") for message in messages[1:]), payload)self.assertTrue(upstream.released)self.assertEqual(app.app.state.upstream_semaphore._value, 1)async def test_large_media_streams_metadata_and_ranges_without_whole_file_limit(self):total = app.READER_DOCUMENT_MAX_BYTES + 100for kind, suffix in (("audio", "mp3"), ("video", "mp4")):path = f"media/{kind}/native/{'a' * 64}/{kind}.{suffix}"for method, forwarded, status, headers in (("HEAD", {}, 200, {"Content-Length": str(total)}),("GET", {"Range": "bytes=0-1"}, 206,{"Content-Length": "2", "Content-Range": f"bytes 0-1/{total}"}),("GET", {"Range": "bytes=-2"}, 206,{"Content-Length": "2", "Content-Range": f"bytes {total - 2}-{total - 1}/{total}"}),("GET", {"Range": f"bytes={total}-"}, 416,{"Content-Length": "0", "Content-Range": f"bytes */{total}"}),):for source in ("bucket", "original"):with self.subTest(kind=kind, method=method, range=forwarded, source=source):upstream = FakeResponse(status, headers, chunks=() if status == 416 else (b"ab",))session = app.app.state.http_session = FakeSession([upstream])semaphore = app.app.state.upstream_semaphore = asyncio.Semaphore(1)app.app.state.reader_range_cache = OrderedDict()app.app.state.reader_range_cache_bytes = 0request = SimpleNamespace(method=method, headers=forwarded)if source == "bucket":response = await app.api_reader_bucket_resource(path, request)else:url = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/large.{suffix}"response = await app.api_reader_content(request, url=url, id=None)self.assertEqual(response.status_code, status)self.assertIsNone(session.urls[0][1]["timeout"].total)self.assertEqual(session.urls[0][1]["timeout"].sock_read, 60)if method != "HEAD":self.assertEqual(b"".join([chunk async for chunk in response.body_iterator]),b"" if status == 416 else b"ab")self.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)async def test_media_unknown_length_stream_does_not_use_document_body_limit(self):path = f"media/audio/native/{'a' * 64}/audio.mp3"upstream = FakeResponse(200, chunks=(b"abc", b"def"))app.app.state.http_session = FakeSession([upstream])with patch.object(app, "READER_DOCUMENT_MAX_BYTES", 2), patch.object(app, "READER_RESOURCE_MAX_BYTES", 2):response = await app.api_reader_bucket_resource(path, SimpleNamespace(method="GET", headers={}))self.assertEqual(response.status_code, 200)self.assertEqual([chunk async for chunk in response.body_iterator], [b"abc", b"def"])self.assertTrue(upstream.released)self.assertEqual(app.app.state.upstream_semaphore._value, 1)async def test_bucket_media_preserves_range_validation_and_cancellation_cleanup(self):path = f"media/video/native/{'a' * 64}/video.mp4"for status, headers in ((206, {"Content-Length": "2", "Content-Range": "invalid"}),(206, {"Content-Length": "2", "Content-Range": "bytes 0-2/100"}),(206, {"Content-Length": "2", "Content-Range": "bytes 99-100/100"}),):upstream = FakeResponse(status, headers)app.app.state.http_session = FakeSession([upstream])1 unmodified lineapp.app.state.reader_range_cache = OrderedDict()app.app.state.reader_range_cache_bytes = 0response = await app.api_reader_bucket_resource(path, SimpleNamespace(method="GET", headers={"Range": "bytes=0-1"}))self.assertEqual(response.status_code, 502)self.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)with patch.object(app, "open_download_response", AsyncMock(side_effect=asyncio.CancelledError)):
4 unmodified lines5678910110 unmodified lines1211221231241251261271 unmodified line1291301311321331341354 unmodified linesconst root = path.resolve(__dirname, '..')const reader = fs.readFileSync(path.join(root, 'static/reader.js'), 'utf8')const css = fs.readFileSync(path.join(root, 'static/reader.css'), 'utf8')const view = fs.readFileSync(path.join(root, 'static/foliate-reader/view.js'), 'utf8')for (const marker of ["import('./epub.js')", "import('./mobi.js')", "import('./fb2.js')", "import('./pdf.js')", "isFBZ(file)", "isFB2(file)"]) assert.ok(view.includes(marker), marker)110 unmodified linesassert.strictEqual(renderFoliateSource.includes('loaded = new Set'), false)assert.strictEqual(renderFoliateSource.includes('pending = new Map'), false)assert.match(reader, /stream\.insertBefore\(article, next \|\| null\)/)assert.match(reader, /foliateSectionLoader = \(index\)/)assert.doesNotMatch(reader, /^let navigationGeneration\b/m)assert.doesNotMatch(reader, /syncReaderState/)assert.doesNotMatch(reader, /^(?:let|var|const)\s+title\b/m)1 unmodified lineassert.doesNotMatch(reader, /readerRuntime\.updateFormat\(/)for (const domain of ['document', 'navigation', 'search', 'panel']) assert.match(reader, new RegExp(`readerRuntime\\.state\\.${domain}`))assert.match(reader, /readerRuntime\.currentGeneration\("pdf"\)/)assert.match(reader, /const generation = nextReaderGeneration\("search"\)/)assert.match(reader, /isReaderGenerationCurrent\("navigation", generation\)/)assert.match(reader, /registerReaderFormatAdapters\(\)/)assert.match(reader, /function disposeFormatResources\(mode\)/)4 unmodified lines5678910111213141516110 unmodified lines1271281291301311321331 unmodified line1351361371381391401411424 unmodified linesconst root = path.resolve(__dirname, '..')const reader = fs.readFileSync(path.join(root, 'static/reader.js'), 'utf8')const searchController = fs.readFileSync(path.join(root, 'static/reader-search-controller.mjs'), 'utf8')assertCode(reader, 'import { createReaderSearchController } from "./reader-search-controller.mjs"')assertCode(reader, 'trackReaderResource(fullSearchController.dispose)')assertCode(reader, 'backend: { mode: () => capability.mode, search: searchReaderText')assert.doesNotMatch(reader, /dataset\.panelView\s*=\s*"full-search"/)assert.doesNotMatch(searchController, /new Worker|\bfetch\(|import\(/)const css = fs.readFileSync(path.join(root, 'static/reader.css'), 'utf8')const view = fs.readFileSync(path.join(root, 'static/foliate-reader/view.js'), 'utf8')for (const marker of ["import('./epub.js')", "import('./mobi.js')", "import('./fb2.js')", "import('./pdf.js')", "isFBZ(file)", "isFB2(file)"]) assert.ok(view.includes(marker), marker)110 unmodified linesassert.strictEqual(renderFoliateSource.includes('loaded = new Set'), false)assert.strictEqual(renderFoliateSource.includes('pending = new Map'), false)assert.match(reader, /stream\.insertBefore\(article, next \|\| null\)/)assert.match(reader, /foliateSectionLoader\s*=\s*(?:\(index\)|index)\s*=>/)assert.doesNotMatch(reader, /^let navigationGeneration\b/m)assert.doesNotMatch(reader, /syncReaderState/)assert.doesNotMatch(reader, /^(?:let|var|const)\s+title\b/m)1 unmodified lineassert.doesNotMatch(reader, /readerRuntime\.updateFormat\(/)for (const domain of ['document', 'navigation', 'search', 'panel']) assert.match(reader, new RegExp(`readerRuntime\\.state\\.${domain}`))assert.match(reader, /readerRuntime\.currentGeneration\("pdf"\)/)assertCode(reader, 'nextGeneration: () => nextReaderGeneration("search")')assertCode(searchController, 'const generation = nextGeneration()')assert.match(reader, /isReaderGenerationCurrent\("navigation", generation\)/)assert.match(reader, /registerReaderFormatAdapters\(\)/)assert.match(reader, /function disposeFormatResources\(mode\)/)
57 unmodified lines58596061626364656667686970717257 unmodified lineswindow.__pdfProbeTask = fullSearchPdfMatches('needle', generation);window.__pdfProbeTask.catch(() => {});};window.__pdfProbePage = offset => pdfSearchPageLoader(offset);window.__pdfProbeTotal = () => chapterSearchPage.total;window.__cancelPdfProbe = () => {nextReaderGeneration('search'); chapterSearchPage = {total:123};};window.__retryCancelledPageProbe = () => loadPdfTextContent(2, {getTextContent:async()=>({items:[{str:'fresh demand'}],styles:{}})});window.__query = async query => {fullSearchInput.value = query;await runFullSearch();return chapterSearchPage?.total || 0;};window.__goChapter = index => navigationState.tocEntries[index-1].activate(beginReaderNavigation());window.__walkProbe = () => {57 unmodified lines58596061626364656667686970717257 unmodified lineswindow.__pdfProbeTask = fullSearchPdfMatches('needle', generation);window.__pdfProbeTask.catch(() => {});};window.__pdfProbePage = offset => fullSearchSession.pageLoader(offset);window.__pdfProbeTotal = () => fullSearchSession.page.total;window.__cancelPdfProbe = () => {nextReaderGeneration('search'); fullSearchSession.page = {total:123};};window.__retryCancelledPageProbe = () => loadPdfTextContent(2, {getTextContent:async()=>({items:[{str:'fresh demand'}],styles:{}})});window.__query = async query => {fullSearchInput.value = query;await runFullSearch();return fullSearchSession.page?.total || 0;};window.__goChapter = index => navigationState.tocEntries[index-1].activate(beginReaderNavigation());window.__walkProbe = () => {
1514 unmodified lines15151516151715181519152015217 unmodified lines15291530153115321533153415351536153715381539665 unmodified lines2205220622072208220922101514 unmodified linesself.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")self.assertEqual(requests, [book_path] * 3)def test_media_proxy_failure_retries_original_once(self):buffer = io.BytesIO()with wave.open(buffer, 'wb') as audio:audio.setparams((1, 2, 8000, 8000, 'NONE', 'not compressed'))7 unmodified linesroute.fulfill(status=206, content_type='audio/wav', body=data[start:],headers={'Accept-Ranges': 'bytes', 'Content-Range': f'bytes {start}-{len(data)-1}/{len(data)}'})self.page.route('https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/refactor.wav', original)self.open(self.reader_url('wav'))self.page.wait_for_function("() => document.querySelector('audio').readyState >= 1")self.assertEqual(len(requests), 1)self.assertEqual(self.page.locator('audio').evaluate('node => node.duration'), 1)self.page.evaluate("async () => { const media = document.querySelector('audio'); media.currentTime = 0.5; await VoiceOfMLReaderStore.put({url: media.src, mediaTime: 0.5}); }")self.page.reload()self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready' && document.querySelector('audio').currentTime === 0.5")self.assertEqual(len(requests), 2)665 unmodified linesself.assertTrue(self.page.locator("#full-search-next").is_disabled())self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")def test_pending_text_result_cannot_highlight_after_new_search(self):def hold_activation(route):response = route.fetch()1514 unmodified lines151515161517151815191520152115221523152415251526152715287 unmodified lines153615371538153915401541154215431544154515461547154815491550665 unmodified lines2216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122421514 unmodified linesself.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")self.assertEqual(requests, [book_path] * 3)def test_bucket_media_failure_retries_download_original_once(self):self.page.route('**/api/reader-bucket-resource**', lambda route: route.fulfill(status=503, body='unavailable'))self.assert_media_failure_retries_original_once(bucket=True)def test_media_proxy_failure_retries_original_once(self):self.assert_media_failure_retries_original_once()def assert_media_failure_retries_original_once(self, bucket=False):buffer = io.BytesIO()with wave.open(buffer, 'wb') as audio:audio.setparams((1, 2, 8000, 8000, 'NONE', 'not compressed'))7 unmodified linesroute.fulfill(status=206, content_type='audio/wav', body=data[start:],headers={'Accept-Ranges': 'bytes', 'Content-Range': f'bytes {start}-{len(data)-1}/{len(data)}'})self.page.route('https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/refactor.wav', original)options = {}if bucket:options = dict(url=self.origin + '/api/reader-bucket-resource?path=media/audio/native/' + 'a' * 64 + '/audio.wav',download='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/refactor.wav')self.open(self.reader_url('wav', **options))self.page.wait_for_function("() => document.querySelector('audio').readyState >= 1")self.assertEqual(len(requests), 1)self.assertEqual(self.page.locator('audio').evaluate('node => node.duration'), 1)self.page.evaluate("async () => { const media = document.querySelector('audio'); media.currentTime = 0.5; await VoiceOfMLReaderStore.put({url: new URL(location.href).searchParams.get('url'), mediaTime: 0.5}); }")self.page.reload()self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready' && document.querySelector('audio').currentTime === 0.5")self.assertEqual(len(requests), 2)665 unmodified linesself.assertTrue(self.page.locator("#full-search-next").is_disabled())self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")def test_disposal_cancels_debounced_full_search(self):self.page.add_init_script("""const nativeTimeout = window.setTimeout.bind(window);window.__searchDebounceCallbacks = 0;window.setTimeout = (callback, delay, ...args) => nativeTimeout(delay === 180 ? (...values) => {window.__searchDebounceCallbacks++;callback(...values);} : callback, delay, ...args);""")self.serve("needle " * 100)self.open(self.reader_url())self.page.evaluate("""() => {const input = document.querySelector('#full-search-input');input.value = 'needle';input.dispatchEvent(new Event('input', {bubbles: true}));window.dispatchEvent(new Event('voice-reader-dispose'));}""")self.page.wait_for_timeout(300)self.assertEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'disposed')self.assertEqual(self.page.evaluate('window.__searchDebounceCallbacks'), 0)self.assertEqual(self.page.locator('.full-search-result').count(), 0)def test_pending_text_result_cannot_highlight_after_new_search(self):def hold_activation(route):response = route.fetch()
12345621 unmodified lines2829303132333424 unmodified lines596061626364"""Focused browser checks for reader CSS, independent of format-engine suites."""import ioimport unittestimport urllib.parseimport zipfile21 unmodified linescls.playwright = sync_playwright().start()cls.addClassCleanup(cls.playwright.stop)try:cls.browser = cls.playwright.chromium.launch(headless=True)except PlaywrightError as error:raise unittest.SkipTest(str(error))cls.addClassCleanup(cls.browser.close)24 unmodified lines!document.getAnimations().some(animation => animation.playState === 'running')""")def assert_contrast(self, selector):result = self.page.locator(selector).first.evaluate("""element => {const rgb = value => value.match(/[\\d.]+/g).map(Number);123456721 unmodified lines2930313233343524 unmodified lines60616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Focused browser checks for reader CSS, independent of format-engine suites."""import ioimport osimport unittestimport urllib.parseimport zipfile21 unmodified linescls.playwright = sync_playwright().start()cls.addClassCleanup(cls.playwright.stop)try:cls.browser = getattr(cls.playwright, os.environ.get("READER_STYLE_BROWSER", "chromium")).launch(headless=True)except PlaywrightError as error:raise unittest.SkipTest(str(error))cls.addClassCleanup(cls.browser.close)24 unmodified lines!document.getAnimations().some(animation => animation.playState === 'running')""")def test_back_and_download_icons_have_stable_browser_independent_geometry(self):self.page.evaluate("""() => {document.querySelector('.page-controls').hidden = false;document.querySelector('.zoom-controls').hidden = false;}""")for theme in ("dark", "light"):self.page.evaluate("theme => document.documentElement.dataset.theme = theme", theme)for width in (1100, 390, 320):self.page.set_viewport_size({"width": width, "height": 900})for selector in ("#back", "#download"):with self.subTest(theme=theme, width=width, selector=selector):button = self.page.locator(selector)geometry = button.evaluate("""button => {const icon = button.querySelector('svg');if (!icon) return null;const b = button.getBoundingClientRect(), i = icon.getBoundingClientRect();const toolbar = button.closest('header').getBoundingClientRect();const style = getComputedStyle(button);return {width: b.width, height: b.height, iconWidth: i.width, iconHeight: i.height,dx: i.x + i.width / 2 - b.x - b.width / 2,dy: i.y + i.height / 2 - b.y - b.height / 2,fits: b.left >= 0 && b.right <= innerWidth && b.top >= toolbar.top && b.bottom <= toolbar.bottom,padding: style.padding, appearance: style.appearance,stroke: getComputedStyle(icon).stroke, color: style.color,hiddenIcon: icon.getAttribute('aria-hidden'), focusable: icon.getAttribute('focusable')};}""")self.assertIsNotNone(geometry)self.assertEqual((geometry["width"], geometry["height"]), (32, 32) if width > 600 else (26, 30))self.assertEqual((geometry["iconWidth"], geometry["iconHeight"]), (18, 18))self.assertAlmostEqual(geometry["dx"], 0, delta=0.5)self.assertAlmostEqual(geometry["dy"], 0, delta=0.5)self.assertTrue(geometry["fits"], geometry)self.assertEqual((geometry["padding"], geometry["appearance"]), ("0px", "none"))self.assertEqual(geometry["stroke"], geometry["color"])self.assertEqual((geometry["hiddenIcon"], geometry["focusable"]), ("true", "false"))self.assertTrue(button.get_attribute("title"))self.assertTrue(button.get_attribute("aria-label"))before = button.bounding_box()button.hover()button.focus()self.assertEqual(button.bounding_box(), before)self.assertEqual(button.evaluate("e => getComputedStyle(e).outlineStyle"), "solid")def assert_contrast(self, selector):result = self.page.locator(selector).first.evaluate("""element => {const rgb = value => value.match(/[\\d.]+/g).map(Number);
112 unmodified lines113114115116117118119120121122123124112 unmodified linesreader_css = (ROOT / "static/reader.css").read_text(encoding="utf-8")reader_html = (ROOT / "static/reader.html").read_text(encoding="utf-8")reader_store = (ROOT / "static/reader-store.js").read_text(encoding="utf-8")self.assertEqual(len(re.findall(r'dataset\.panelView\s*=\s*"full-search"', reader)), 1)self.assertNotIn("window.find", reader)for value in ('id="full-search-input"', 'id="full-search-status"', 'id="full-search-results"', 'id="full-search-prev"', 'id="full-search-next"'):self.assertIn(value, reader)self.assertIn("fullSearchSnippetDom", reader)assert_source_contains(self, 'textContent = "全文搜索"', reader)self.assertIn('circle cx="12" cy="12"', reader)self.assertIn("async function activateChapter", reader)assert_source_contains(self, "progressUndo.hidden = !previousProgressState", reader)112 unmodified lines113114115116117118119120121122123124125126112 unmodified linesreader_css = (ROOT / "static/reader.css").read_text(encoding="utf-8")reader_html = (ROOT / "static/reader.html").read_text(encoding="utf-8")reader_store = (ROOT / "static/reader-store.js").read_text(encoding="utf-8")search_controller = (ROOT / "static/reader-search-controller.mjs").read_text(encoding="utf-8")self.assertIn('import { createReaderSearchController } from "./reader-search-controller.mjs"', reader)self.assertEqual(len(re.findall(r'dataset\.panelView\s*=\s*"full-search"', search_controller)), 1)self.assertNotIn("window.find", reader)for value in ('id="full-search-input"', 'id="full-search-status"', 'id="full-search-results"', 'id="full-search-prev"', 'id="full-search-next"'):self.assertIn(value, search_controller)self.assertIn("snippetDom", search_controller)assert_source_contains(self, 'textContent = "全文搜索"', search_controller)self.assertIn('circle cx="12" cy="12"', reader)self.assertIn("async function activateChapter", reader)assert_source_contains(self, "progressUndo.hidden = !previousProgressState", reader)
app.py+20-9
scripts/check_reader_release.mjs+1
static/icons/LICENSE-lucideAdded+15
static/reader-resources.js+1
static/reader-search-controller.mjsAdded+335
static/reader.css+21
static/reader.html+12-2
static/reader.js+97-442
tests/test_async_proxy.py+86-4
tests/test_reader_architecture.js+9-2
tests/test_reader_optimizations.py+4-4
tests/test_reader_refactor.py+34-2
tests/test_reader_style.py+45-1
tests/test_static_contract.py+6-4