vomebook commited on
Commit ·
4fbb2dd
1
Parent(s): 4f4d61f
Add complete on-demand search for chapter books
Browse files- Dockerfile +1 -0
- scripts/build_static_assets.mjs +6 -1
- scripts/check_reader_release.mjs +2 -0
- static/reader-chapter-search-worker.mjs +177 -0
- static/reader-chapter-search.mjs +93 -0
- static/reader-contract.js +1 -1
- static/reader-runtime.js +1 -1
- static/reader.css +22 -3
- static/reader.js +174 -5
- static/sw.js +2 -0
- tests/test_reader_chapter_search.mjs +32 -0
- tests/test_reader_refactor.py +129 -0
- tests/test_reader_regression.js +1 -1
- tests/test_service_worker.js +18 -0
Dockerfile
CHANGED
|
@@ -22,6 +22,7 @@ RUN mkdir -p /out \
|
|
| 22 |
&& esbuild static/reader-navigation.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader-navigation.js \
|
| 23 |
&& esbuild static/reader-store.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader-store.js \
|
| 24 |
&& esbuild static/reader.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader.js \
|
|
|
|
| 25 |
&& esbuild static/style.css --minify --outfile=/out/style.css \
|
| 26 |
&& esbuild static/reader.css --minify --outfile=/out/reader.css \
|
| 27 |
&& node /build/build_static_assets.mjs \
|
|
|
|
| 22 |
&& esbuild static/reader-navigation.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader-navigation.js \
|
| 23 |
&& esbuild static/reader-store.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader-store.js \
|
| 24 |
&& esbuild static/reader.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/reader.js \
|
| 25 |
+
&& esbuild static/reader-chapter-search.mjs static/reader-chapter-search-worker.mjs --minify --format=esm --target=es2020 --charset=utf8 --legal-comments=none --outdir=/out --out-extension:.js=.mjs \
|
| 26 |
&& esbuild static/style.css --minify --outfile=/out/style.css \
|
| 27 |
&& esbuild static/reader.css --minify --outfile=/out/reader.css \
|
| 28 |
&& node /build/build_static_assets.mjs \
|
scripts/build_static_assets.mjs
CHANGED
|
@@ -5,8 +5,13 @@ import { extname, join } from "node:path";
|
|
| 5 |
const outputDir = process.env.STATIC_OUTPUT_DIR || "/out";
|
| 6 |
const replacements = new Map();
|
| 7 |
|
| 8 |
-
for (const filename of ["app.js", "style.css", "reader-contract.js", "reader-navigation.js", "reader-store.js", "reader.js", "reader.css"]) {
|
| 9 |
const source = join(outputDir, filename);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
const content = readFileSync(source);
|
| 11 |
const hash = createHash("sha256").update(content).digest("hex").slice(0, 12);
|
| 12 |
const extension = extname(filename);
|
|
|
|
| 5 |
const outputDir = process.env.STATIC_OUTPUT_DIR || "/out";
|
| 6 |
const replacements = new Map();
|
| 7 |
|
| 8 |
+
for (const filename of ["reader-chapter-search-worker.mjs", "reader-chapter-search.mjs", "app.js", "style.css", "reader-contract.js", "reader-navigation.js", "reader-store.js", "reader.js", "reader.css"]) {
|
| 9 |
const source = join(outputDir, filename);
|
| 10 |
+
if (["reader-chapter-search.mjs", "reader.js"].includes(filename)) {
|
| 11 |
+
let text = readFileSync(source, "utf8");
|
| 12 |
+
for (const [original, versioned] of replacements) text = text.split(original).join(versioned);
|
| 13 |
+
writeFileSync(source, text);
|
| 14 |
+
}
|
| 15 |
const content = readFileSync(source);
|
| 16 |
const hash = createHash("sha256").update(content).digest("hex").slice(0, 12);
|
| 17 |
const extension = extname(filename);
|
scripts/check_reader_release.mjs
CHANGED
|
@@ -22,6 +22,8 @@ const required = [
|
|
| 22 |
"reader-store.js",
|
| 23 |
"reader-request-manager.js",
|
| 24 |
"reader-chapter-repository.js",
|
|
|
|
|
|
|
| 25 |
"reader-scroll-anchor.js",
|
| 26 |
"reader-section-virtualizer.js",
|
| 27 |
"reader-runtime.js",
|
|
|
|
| 22 |
"reader-store.js",
|
| 23 |
"reader-request-manager.js",
|
| 24 |
"reader-chapter-repository.js",
|
| 25 |
+
"reader-chapter-search.mjs",
|
| 26 |
+
"reader-chapter-search-worker.mjs",
|
| 27 |
"reader-scroll-anchor.js",
|
| 28 |
"reader-section-virtualizer.js",
|
| 29 |
"reader-runtime.js",
|
static/reader-chapter-search-worker.mjs
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const PACKED_LIMIT = 64 * 1024 * 1024;
|
| 2 |
+
const TEXT_LIMIT = 256 * 1024 * 1024;
|
| 3 |
+
const PAGE_SIZE = 50;
|
| 4 |
+
const pause = () => new Promise(resolve => setTimeout(resolve, 0));
|
| 5 |
+
function cooperativeYield() {
|
| 6 |
+
let last = performance.now();
|
| 7 |
+
return async () => {
|
| 8 |
+
if (performance.now() - last < 8) return;
|
| 9 |
+
await pause();
|
| 10 |
+
last = performance.now();
|
| 11 |
+
};
|
| 12 |
+
}
|
| 13 |
+
const escapePattern = value => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
| 14 |
+
const aborted = () => new DOMException("Search cancelled", "AbortError");
|
| 15 |
+
|
| 16 |
+
async function readBounded(stream, limit, signal) {
|
| 17 |
+
const reader = stream.getReader(), chunks = [];
|
| 18 |
+
let size = 0;
|
| 19 |
+
const cancel = () => reader.cancel().catch(() => {});
|
| 20 |
+
signal.addEventListener("abort", cancel, { once: true });
|
| 21 |
+
try {
|
| 22 |
+
while (true) {
|
| 23 |
+
if (signal.aborted) throw aborted();
|
| 24 |
+
const { value, done } = await reader.read();
|
| 25 |
+
if (signal.aborted) throw aborted();
|
| 26 |
+
if (done) break;
|
| 27 |
+
size += value.byteLength;
|
| 28 |
+
if (size > limit) throw new Error("全文搜索数据超过大小限制");
|
| 29 |
+
chunks.push(value);
|
| 30 |
+
}
|
| 31 |
+
const result = new Uint8Array(size);
|
| 32 |
+
let offset = 0;
|
| 33 |
+
for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.length; }
|
| 34 |
+
return result;
|
| 35 |
+
} catch (error) {
|
| 36 |
+
await reader.cancel().catch(() => {});
|
| 37 |
+
throw error;
|
| 38 |
+
} finally {
|
| 39 |
+
signal.removeEventListener("abort", cancel);
|
| 40 |
+
reader.releaseLock();
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
export function validateIndex(data, chapters) {
|
| 45 |
+
if (data?.version !== 1 || data.kind !== "epub-search-index" ||
|
| 46 |
+
!Array.isArray(data.chapters) || data.chapters.length !== chapters.length)
|
| 47 |
+
throw new Error("全文搜索索引不完整,请重试");
|
| 48 |
+
for (let i = 0; i < chapters.length; i++) {
|
| 49 |
+
const item = data.chapters[i], expected = chapters[i];
|
| 50 |
+
if (item?.index !== expected.index || item.path !== expected.path || typeof item.text !== "string")
|
| 51 |
+
throw new Error("全文搜索索引与章节不一致");
|
| 52 |
+
item.title = expected.title || `章节 ${expected.index}`;
|
| 53 |
+
}
|
| 54 |
+
return data.chapters;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// Scan bounded pieces so a new query can cancel even one very large chapter.
|
| 58 |
+
// Keep counts, rather than one object per hit; all matches remain pageable.
|
| 59 |
+
export async function scanText(text, query, visit, current = () => true, yieldWork = pause) {
|
| 60 |
+
const pattern = new RegExp(escapePattern(query), "giu");
|
| 61 |
+
let next = 0;
|
| 62 |
+
for (let start = 0; start < text.length; start += 65536) {
|
| 63 |
+
if (!current()) throw aborted();
|
| 64 |
+
const part = text.slice(start, start + 65536 + query.length + 1);
|
| 65 |
+
pattern.lastIndex = Math.max(0, next - start);
|
| 66 |
+
let match;
|
| 67 |
+
while ((match = pattern.exec(part))) {
|
| 68 |
+
if (match.index >= 65536) break;
|
| 69 |
+
const offset = start + match.index;
|
| 70 |
+
next = offset + match[0].length;
|
| 71 |
+
if (visit(offset, match[0].length) === false) return;
|
| 72 |
+
}
|
| 73 |
+
await yieldWork();
|
| 74 |
+
}
|
| 75 |
+
if (!current()) throw aborted();
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
export async function countMatches(chapters, query, current) {
|
| 79 |
+
const counts = [];
|
| 80 |
+
const yieldWork = cooperativeYield();
|
| 81 |
+
let total = 0;
|
| 82 |
+
for (const chapter of chapters) {
|
| 83 |
+
let count = 0;
|
| 84 |
+
await scanText(chapter.text, query, () => { count++; }, current, yieldWork);
|
| 85 |
+
counts.push(count);
|
| 86 |
+
total += count;
|
| 87 |
+
}
|
| 88 |
+
return { counts, total };
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
export async function resultPage(chapters, query, counts, offset, current) {
|
| 92 |
+
const results = [];
|
| 93 |
+
const yieldWork = cooperativeYield();
|
| 94 |
+
let skip = offset;
|
| 95 |
+
for (let i = 0; i < chapters.length && results.length < PAGE_SIZE; i++) {
|
| 96 |
+
if (!current()) throw aborted();
|
| 97 |
+
if (skip >= counts[i]) { skip -= counts[i]; continue; }
|
| 98 |
+
const chapter = chapters[i];
|
| 99 |
+
await scanText(chapter.text, query, (start, length) => {
|
| 100 |
+
if (skip) { skip--; return; }
|
| 101 |
+
const before = Math.max(0, start - 72), after = Math.min(chapter.text.length, start + length + 88);
|
| 102 |
+
results.push({
|
| 103 |
+
chapterIndex: chapter.index, start, length,
|
| 104 |
+
location: `第 ${chapter.index} 章 · ${chapter.title}`,
|
| 105 |
+
snippet: { text: chapter.text.slice(before, after), matchStart: start - before,
|
| 106 |
+
matchLength: length, prefix: before ? "…" : "", suffix: after < chapter.text.length ? "…" : "" }
|
| 107 |
+
});
|
| 108 |
+
return results.length < PAGE_SIZE;
|
| 109 |
+
}, current, yieldWork);
|
| 110 |
+
}
|
| 111 |
+
return results;
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
let configuration, indexPromise, chapters, active = 0, session, loadController;
|
| 115 |
+
async function loadIndex() {
|
| 116 |
+
if (chapters) return chapters;
|
| 117 |
+
if (indexPromise) return indexPromise;
|
| 118 |
+
const controller = new AbortController();
|
| 119 |
+
loadController = controller;
|
| 120 |
+
const timer = setTimeout(() => controller.abort(), 60000);
|
| 121 |
+
indexPromise = (async () => {
|
| 122 |
+
const { index, chapters: expected } = configuration;
|
| 123 |
+
const url = new URL(index.url, self.location.origin);
|
| 124 |
+
if (url.origin !== self.location.origin || url.pathname !== "/api/reader-content" ||
|
| 125 |
+
!Number.isSafeInteger(index.bytes) || index.bytes <= 0 || index.bytes > PACKED_LIMIT ||
|
| 126 |
+
!/^[0-9a-f]{64}$/.test(index.sha256)) throw new Error("全文搜索索引无效");
|
| 127 |
+
const response = await fetch(url, { signal: controller.signal, credentials: "same-origin" });
|
| 128 |
+
if (!response.ok) throw new Error(`全文搜索加载失败(HTTP ${response.status}),请重试`);
|
| 129 |
+
const bytes = await readBounded(response.body, PACKED_LIMIT, controller.signal);
|
| 130 |
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
|
| 131 |
+
const sha = [...digest].map(value => value.toString(16).padStart(2, "0")).join("");
|
| 132 |
+
if (bytes.length !== index.bytes || sha !== index.sha256) throw new Error("全文搜索索引校验失败,请重试");
|
| 133 |
+
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
|
| 134 |
+
const text = await readBounded(stream, TEXT_LIMIT, controller.signal);
|
| 135 |
+
const loaded = validateIndex(JSON.parse(new TextDecoder().decode(text)), expected);
|
| 136 |
+
if (controller.signal.aborted) throw aborted();
|
| 137 |
+
chapters = loaded;
|
| 138 |
+
return loaded;
|
| 139 |
+
})().finally(() => {
|
| 140 |
+
clearTimeout(timer);
|
| 141 |
+
indexPromise = null;
|
| 142 |
+
if (loadController === controller) loadController = null;
|
| 143 |
+
});
|
| 144 |
+
return indexPromise;
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
if (typeof self !== "undefined" && typeof self.postMessage === "function") {
|
| 148 |
+
self.onmessage = async ({ data }) => {
|
| 149 |
+
if (data.type === "init") { configuration = data.configuration; return; }
|
| 150 |
+
if (data.type === "cancel") { active++; session = null; loadController?.abort(); return; }
|
| 151 |
+
const token = ++active, current = () => token === active;
|
| 152 |
+
try {
|
| 153 |
+
let offset = 0;
|
| 154 |
+
if (data.type === "search") {
|
| 155 |
+
session = null;
|
| 156 |
+
const query = String(data.query || "").trim().replace(/\s+/gu, " ");
|
| 157 |
+
if (!query || query.length > 2048) throw new Error("请输入 1–2048 个字符");
|
| 158 |
+
// A cancelled download must settle before a later search retries it.
|
| 159 |
+
if (loadController?.signal.aborted) await indexPromise.catch(() => {});
|
| 160 |
+
const book = await loadIndex();
|
| 161 |
+
if (!current()) return;
|
| 162 |
+
const counts = await countMatches(book, query, current);
|
| 163 |
+
session = { ...counts, query, id: data.id };
|
| 164 |
+
} else if (data.type === "page") {
|
| 165 |
+
if (!session || data.session !== session.id) throw aborted();
|
| 166 |
+
offset = Math.max(0, Math.min(Math.floor(data.offset / PAGE_SIZE) * PAGE_SIZE,
|
| 167 |
+
Math.max(0, Math.ceil(session.total / PAGE_SIZE) - 1) * PAGE_SIZE));
|
| 168 |
+
} else return;
|
| 169 |
+
const result = await resultPage(chapters, session.query, session.counts, offset, current);
|
| 170 |
+
if (current()) self.postMessage({ id: data.id, session: session.id, total: session.total,
|
| 171 |
+
offset, pageSize: PAGE_SIZE, results: result });
|
| 172 |
+
} catch (error) {
|
| 173 |
+
if (current()) self.postMessage({ id: data.id, error: error.name === "AbortError"
|
| 174 |
+
? "全文搜索已取消或加载超时,请重试" : error.message });
|
| 175 |
+
}
|
| 176 |
+
};
|
| 177 |
+
}
|
static/reader-chapter-search.mjs
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export function createChapterSearch(configuration) {
|
| 2 |
+
const worker = new Worker("/static/reader-chapter-search-worker.mjs", { type: "module" });
|
| 3 |
+
let sequence = 0, pending = null, disposed = false, session = null, failure = null;
|
| 4 |
+
const cancelPending = () => {
|
| 5 |
+
pending?.reject(new DOMException("Search cancelled", "AbortError"));
|
| 6 |
+
pending = null;
|
| 7 |
+
};
|
| 8 |
+
worker.onmessage = ({ data }) => {
|
| 9 |
+
if (!pending || pending.id !== data.id) return;
|
| 10 |
+
const task = pending;
|
| 11 |
+
pending = null;
|
| 12 |
+
if (data.error) task.reject(new Error(data.error));
|
| 13 |
+
else { session = data.session; task.resolve(data); }
|
| 14 |
+
};
|
| 15 |
+
worker.onerror = event => {
|
| 16 |
+
event.preventDefault();
|
| 17 |
+
failure = new Error("全文搜索组件加载失败,请重试");
|
| 18 |
+
pending?.reject(failure);
|
| 19 |
+
pending = null;
|
| 20 |
+
};
|
| 21 |
+
worker.postMessage({ type: "init", configuration });
|
| 22 |
+
function request(type, values) {
|
| 23 |
+
if (disposed) return Promise.reject(new DOMException("Reader closed", "AbortError"));
|
| 24 |
+
if (failure) return Promise.reject(failure);
|
| 25 |
+
cancelPending();
|
| 26 |
+
return new Promise((resolve, reject) => {
|
| 27 |
+
const id = ++sequence;
|
| 28 |
+
pending = { id, resolve, reject };
|
| 29 |
+
worker.postMessage({ type, id, ...values });
|
| 30 |
+
});
|
| 31 |
+
}
|
| 32 |
+
return {
|
| 33 |
+
get failed() { return !!failure; },
|
| 34 |
+
search: query => request("search", { query }),
|
| 35 |
+
page: offset => request("page", { offset, session }),
|
| 36 |
+
cancel() { cancelPending(); session = null; worker.postMessage({ type: "cancel" }); },
|
| 37 |
+
dispose() { disposed = true; cancelPending(); worker.terminate(); }
|
| 38 |
+
};
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
// Reproduce the bundle's HTMLParser text extraction: skip script/style/noscript,
|
| 42 |
+
// separate text nodes, decode character references, and collapse whitespace.
|
| 43 |
+
// Runs map normalized offsets back to the exact text nodes being displayed.
|
| 44 |
+
export function chapterTextMap(roots) {
|
| 45 |
+
const runs = [], chunks = [];
|
| 46 |
+
let length = 0, pendingSpace = null;
|
| 47 |
+
const decoder = document.createElement("textarea");
|
| 48 |
+
const append = (text, node, start, end, linear) => {
|
| 49 |
+
if (!text) return;
|
| 50 |
+
if (pendingSpace && length) {
|
| 51 |
+
chunks.push(" ");
|
| 52 |
+
runs.push({ ...pendingSpace, from: length, to: ++length, linear: false });
|
| 53 |
+
}
|
| 54 |
+
pendingSpace = null;
|
| 55 |
+
chunks.push(text);
|
| 56 |
+
runs.push({ node, start, end, linear, from: length, to: length + text.length });
|
| 57 |
+
length += text.length;
|
| 58 |
+
};
|
| 59 |
+
for (const root of roots.filter(Boolean)) {
|
| 60 |
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
| 61 |
+
while (walker.nextNode()) {
|
| 62 |
+
const node = walker.currentNode;
|
| 63 |
+
if (node.parentElement?.closest("script,style,noscript")) continue;
|
| 64 |
+
if (length) pendingSpace = { node: null, start: 0, end: 0 };
|
| 65 |
+
// Python's Unicode whitespace also includes NEL and the four separators.
|
| 66 |
+
const pattern = /&(?:#[xX][0-9a-fA-F]+;?|#\d+;?|[a-zA-Z][a-zA-Z0-9]+;?)|[\s\u0085\u001c-\u001f]+|[^&\s\u0085\u001c-\u001f]+|&/gu;
|
| 67 |
+
for (const match of node.data.matchAll(pattern)) {
|
| 68 |
+
const raw = match[0], start = match.index, end = start + raw.length;
|
| 69 |
+
let text = raw;
|
| 70 |
+
if (raw.startsWith("&")) { decoder.innerHTML = raw; text = decoder.value; }
|
| 71 |
+
if (/^[\s\u0085\u001c-\u001f]+$/u.test(text)) {
|
| 72 |
+
pendingSpace ||= { node, start, end };
|
| 73 |
+
} else append(text, node, start, end, text === raw);
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
return {
|
| 78 |
+
text: chunks.join(""),
|
| 79 |
+
parts(start, end, body) {
|
| 80 |
+
const output = [];
|
| 81 |
+
for (const run of runs) {
|
| 82 |
+
if (run.to <= start || run.from >= end || !run.node || !body.contains(run.node)) continue;
|
| 83 |
+
const part = { node: run.node,
|
| 84 |
+
start: run.linear ? run.start + Math.max(start - run.from, 0) : run.start,
|
| 85 |
+
end: run.linear ? run.end - Math.max(run.to - end, 0) : run.end };
|
| 86 |
+
const last = output[output.length - 1];
|
| 87 |
+
if (last?.node === part.node) last.end = part.end;
|
| 88 |
+
else output.push(part);
|
| 89 |
+
}
|
| 90 |
+
return output;
|
| 91 |
+
}
|
| 92 |
+
};
|
| 93 |
+
}
|
static/reader-contract.js
CHANGED
|
@@ -151,7 +151,7 @@
|
|
| 151 |
},
|
| 152 |
"epub-chapters": {
|
| 153 |
toc: true,
|
| 154 |
-
search:
|
| 155 |
zoom: true,
|
| 156 |
bookmarks: true,
|
| 157 |
pagination: false,
|
|
|
|
| 151 |
},
|
| 152 |
"epub-chapters": {
|
| 153 |
toc: true,
|
| 154 |
+
search: true,
|
| 155 |
zoom: true,
|
| 156 |
bookmarks: true,
|
| 157 |
pagination: false,
|
static/reader-runtime.js
CHANGED
|
@@ -21,7 +21,7 @@
|
|
| 21 |
},
|
| 22 |
"epub-chapters": {
|
| 23 |
toc: true,
|
| 24 |
-
search:
|
| 25 |
zoom: true,
|
| 26 |
bookmarks: true,
|
| 27 |
pagination: false,
|
|
|
|
| 21 |
},
|
| 22 |
"epub-chapters": {
|
| 23 |
toc: true,
|
| 24 |
+
search: true,
|
| 25 |
zoom: true,
|
| 26 |
bookmarks: true,
|
| 27 |
pagination: false,
|
static/reader.css
CHANGED
|
@@ -366,7 +366,8 @@ body {
|
|
| 366 |
gap: 6px;
|
| 367 |
padding: 0 12px 8px;
|
| 368 |
}
|
| 369 |
-
.full-search-nav button
|
|
|
|
| 370 |
flex: 1;
|
| 371 |
min-height: 30px;
|
| 372 |
border: 1px solid #464c52;
|
|
@@ -375,7 +376,8 @@ body {
|
|
| 375 |
color: inherit;
|
| 376 |
cursor: pointer;
|
| 377 |
}
|
| 378 |
-
.full-search-nav button:disabled
|
|
|
|
| 379 |
opacity: 0.4;
|
| 380 |
cursor: default;
|
| 381 |
}
|
|
@@ -383,6 +385,22 @@ body {
|
|
| 383 |
min-height: 0;
|
| 384 |
overflow: auto;
|
| 385 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
.full-search-result {
|
| 387 |
display: block;
|
| 388 |
width: 100%;
|
|
@@ -412,7 +430,8 @@ body {
|
|
| 412 |
line-height: 1.55;
|
| 413 |
overflow-wrap: anywhere;
|
| 414 |
}
|
| 415 |
-
:root[data-theme="light"] .full-search-nav button
|
|
|
|
| 416 |
border-color: #c7ccd0;
|
| 417 |
}
|
| 418 |
:root[data-theme="light"] .full-search-result {
|
|
|
|
| 366 |
gap: 6px;
|
| 367 |
padding: 0 12px 8px;
|
| 368 |
}
|
| 369 |
+
.full-search-nav button,
|
| 370 |
+
.full-search-pagination button {
|
| 371 |
flex: 1;
|
| 372 |
min-height: 30px;
|
| 373 |
border: 1px solid #464c52;
|
|
|
|
| 376 |
color: inherit;
|
| 377 |
cursor: pointer;
|
| 378 |
}
|
| 379 |
+
.full-search-nav button:disabled,
|
| 380 |
+
.full-search-pagination button:disabled {
|
| 381 |
opacity: 0.4;
|
| 382 |
cursor: default;
|
| 383 |
}
|
|
|
|
| 385 |
min-height: 0;
|
| 386 |
overflow: auto;
|
| 387 |
}
|
| 388 |
+
.full-search-pagination:not([hidden]) {
|
| 389 |
+
display: flex;
|
| 390 |
+
align-items: center;
|
| 391 |
+
gap: 6px;
|
| 392 |
+
padding: 0 12px 8px;
|
| 393 |
+
font-size: 12px;
|
| 394 |
+
}
|
| 395 |
+
.full-search-pagination label { white-space: nowrap; }
|
| 396 |
+
.full-search-pagination input {
|
| 397 |
+
width: 4em;
|
| 398 |
+
padding: 4px;
|
| 399 |
+
border: 1px solid #929aa1;
|
| 400 |
+
border-radius: 4px;
|
| 401 |
+
color: inherit;
|
| 402 |
+
background: transparent;
|
| 403 |
+
}
|
| 404 |
.full-search-result {
|
| 405 |
display: block;
|
| 406 |
width: 100%;
|
|
|
|
| 430 |
line-height: 1.55;
|
| 431 |
overflow-wrap: anywhere;
|
| 432 |
}
|
| 433 |
+
:root[data-theme="light"] .full-search-nav button,
|
| 434 |
+
:root[data-theme="light"] .full-search-pagination button {
|
| 435 |
border-color: #c7ccd0;
|
| 436 |
}
|
| 437 |
:root[data-theme="light"] .full-search-result {
|
static/reader.js
CHANGED
|
@@ -337,6 +337,11 @@ try {
|
|
| 337 |
let saveTimer = 0;
|
| 338 |
let saveDeadline = 0;
|
| 339 |
let chapterManifestLoader = null;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
let folderNavigationTarget = null;
|
| 341 |
let bookmarkInvoker = null;
|
| 342 |
const bookmarkInertSiblings = new Map();
|
|
@@ -2210,6 +2215,14 @@ function sanitizeReaderDocument(doc, { preserveEpubStyles = false } = {}) {
|
|
| 2210 |
function sanitizeEpubDocument(doc) {
|
| 2211 |
return sanitizeReaderDocument(normalizeEpubDocument(doc), { preserveEpubStyles: true });
|
| 2212 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2213 |
|
| 2214 |
function epubContentBody(doc) {
|
| 2215 |
const nestedBody = [...doc.querySelectorAll("body")].find((body) => body !== doc.body);
|
|
@@ -3027,6 +3040,13 @@ async function renderChapterManifest(prepared) {
|
|
| 3027 |
const chapterPrefetchCount = 6;
|
| 3028 |
const chapterBudget = VoiceOfMLReaderSecurity.createByteBudget();
|
| 3029 |
if (!manifestBase) throw new Error("EPUB_INVALID_MANIFEST_PATH");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3030 |
const chapterUrl = (chapter) => trustedChapterUrl(chapter.path, manifestBase);
|
| 3031 |
const resourceUrl = (raw, base, attribute) => {
|
| 3032 |
const value = String(raw || "").trim();
|
|
@@ -3098,9 +3118,7 @@ async function renderChapterManifest(prepared) {
|
|
| 3098 |
let inserted = false;
|
| 3099 |
try {
|
| 3100 |
assertReaderActive();
|
| 3101 |
-
const doc =
|
| 3102 |
-
new DOMParser().parseFromString(new TextDecoder().decode(bytes), "text/html")
|
| 3103 |
-
);
|
| 3104 |
for (const element of doc.querySelectorAll("*")) {
|
| 3105 |
for (const name of ["src", "href", "poster", "xlink:href"])
|
| 3106 |
if (element.hasAttribute(name)) {
|
|
@@ -3115,6 +3133,8 @@ async function renderChapterManifest(prepared) {
|
|
| 3115 |
article.className = "reader-markdown reader-epub-chapter";
|
| 3116 |
article.dataset.chapter = String(chapter.index);
|
| 3117 |
article.innerHTML = doc.body ? doc.body.innerHTML : "";
|
|
|
|
|
|
|
| 3118 |
const marker = frame.querySelector(
|
| 3119 |
`.reader-chapter-sentinel[data-chapter="${chapter.index}"]`
|
| 3120 |
);
|
|
@@ -4216,7 +4236,128 @@ fullSearchButton.hidden = !capability.features.search;
|
|
| 4216 |
const fullSearchInput = fullSearchView.querySelector("#full-search-input"),
|
| 4217 |
fullSearchStatus = fullSearchView.querySelector("#full-search-status"),
|
| 4218 |
fullSearchResultsNode = fullSearchView.querySelector("#full-search-results");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4219 |
// Full-text search: format matching, result presentation, and navigation.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4220 |
async function fullSearchFoliateMatches(query, generation) {
|
| 4221 |
const results = [];
|
| 4222 |
if (!epubRendition?.search) return results;
|
|
@@ -4455,6 +4596,7 @@ async function fullSearchPdfMatches(query, generation) {
|
|
| 4455 |
return output;
|
| 4456 |
}
|
| 4457 |
function renderFullSearchResults() {
|
|
|
|
| 4458 |
fullSearchResultsNode.textContent = "";
|
| 4459 |
for (const [index, result] of searchState.results.entries()) {
|
| 4460 |
const row = document.createElement("button"),
|
|
@@ -4477,11 +4619,16 @@ async function runFullSearch() {
|
|
| 4477 |
beginReaderNavigation();
|
| 4478 |
clearFullSearchMarks();
|
| 4479 |
updateSearchState({ query, results: [], index: -1 });
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4480 |
fullSearchResultsNode.textContent = "";
|
| 4481 |
fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {
|
| 4482 |
button.disabled = true;
|
| 4483 |
});
|
| 4484 |
if (!query) {
|
|
|
|
| 4485 |
fullSearchStatus.textContent = "输入关键词搜索正文";
|
| 4486 |
return;
|
| 4487 |
}
|
|
@@ -4491,6 +4638,8 @@ async function runFullSearch() {
|
|
| 4491 |
publishSearchResults(generation, await fullSearchPdfMatches(query, generation));
|
| 4492 |
else if (capability.mode === "foliate")
|
| 4493 |
publishSearchResults(generation, await fullSearchFoliateMatches(query, generation));
|
|
|
|
|
|
|
| 4494 |
else if (["text", "markdown", "docx"].includes(capability.mode))
|
| 4495 |
publishSearchResults(
|
| 4496 |
generation,
|
|
@@ -4511,13 +4660,18 @@ async function runFullSearch() {
|
|
| 4511 |
else throw new Error("此格式没有可搜索文本");
|
| 4512 |
if (!isReaderGenerationCurrent("search", generation)) return;
|
| 4513 |
renderFullSearchResults();
|
| 4514 |
-
fullSearchStatus.textContent =
|
|
|
|
|
|
|
| 4515 |
? `${searchState.results.length}${searchState.results.length === 100 ? "+" : ""} 个结果`
|
| 4516 |
: "未找到正文匹配";
|
| 4517 |
} catch (error) {
|
| 4518 |
-
if (isReaderGenerationCurrent("search", generation))
|
| 4519 |
fullSearchStatus.textContent = error.message || "正文搜索不可用";
|
|
|
|
|
|
|
| 4520 |
} finally {
|
|
|
|
| 4521 |
if (isReaderGenerationCurrent("search", generation))
|
| 4522 |
fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {
|
| 4523 |
button.disabled = !searchState.results.length;
|
|
@@ -4542,10 +4696,21 @@ async function activateFullSearchResult(index, closePanel = true) {
|
|
| 4542 |
if (closePanel) setReaderPanelOpen(false, true);
|
| 4543 |
else fullSearchResultsNode.children[index]?.scrollIntoView({ block: "nearest" });
|
| 4544 |
} catch (error) {
|
|
|
|
|
|
|
| 4545 |
reportNavigationError(error, generation);
|
| 4546 |
}
|
| 4547 |
}
|
| 4548 |
function moveFullSearch(step) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4549 |
if (searchState.results.length)
|
| 4550 |
return activateFullSearchResult(
|
| 4551 |
(searchState.index + step + searchState.results.length) % searchState.results.length,
|
|
@@ -4557,6 +4722,10 @@ function toggleFullSearch() {
|
|
| 4557 |
if (panel.classList.contains("is-open") && !fullSearchView.hidden) {
|
| 4558 |
beginReaderNavigation();
|
| 4559 |
nextReaderGeneration("search");
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4560 |
clearFullSearchMarks();
|
| 4561 |
updateSearchState({ results: [], index: -1 });
|
| 4562 |
renderFullSearchResults();
|
|
|
|
| 337 |
let saveTimer = 0;
|
| 338 |
let saveDeadline = 0;
|
| 339 |
let chapterManifestLoader = null;
|
| 340 |
+
let chapterSearchConfiguration = null;
|
| 341 |
+
let chapterSearchModulePromise = null;
|
| 342 |
+
let chapterSearchClient = null;
|
| 343 |
+
let chapterSearchPage = null;
|
| 344 |
+
trackReaderResource(() => { chapterSearchClient?.dispose(); chapterSearchClient = null; });
|
| 345 |
let folderNavigationTarget = null;
|
| 346 |
let bookmarkInvoker = null;
|
| 347 |
const bookmarkInertSiblings = new Map();
|
|
|
|
| 2215 |
function sanitizeEpubDocument(doc) {
|
| 2216 |
return sanitizeReaderDocument(normalizeEpubDocument(doc), { preserveEpubStyles: true });
|
| 2217 |
}
|
| 2218 |
+
function parseChapterDocument(text) {
|
| 2219 |
+
// Parse generated XHTML before HTML's void-element rules can swallow children
|
| 2220 |
+
// of prefixed elements such as <html:meta/> (including the following title).
|
| 2221 |
+
const xml = new DOMParser().parseFromString(text, "application/xhtml+xml");
|
| 2222 |
+
if (!xml.querySelector("parsererror"))
|
| 2223 |
+
text = new XMLSerializer().serializeToString(normalizeEpubDocument(xml));
|
| 2224 |
+
return sanitizeEpubDocument(new DOMParser().parseFromString(text, "text/html"));
|
| 2225 |
+
}
|
| 2226 |
|
| 2227 |
function epubContentBody(doc) {
|
| 2228 |
const nestedBody = [...doc.querySelectorAll("body")].find((body) => body !== doc.body);
|
|
|
|
| 3040 |
const chapterPrefetchCount = 6;
|
| 3041 |
const chapterBudget = VoiceOfMLReaderSecurity.createByteBudget();
|
| 3042 |
if (!manifestBase) throw new Error("EPUB_INVALID_MANIFEST_PATH");
|
| 3043 |
+
const searchIndex = manifest.search_index;
|
| 3044 |
+
chapterSearchConfiguration = searchIndex?.path === "epub-search-index.json.gz" &&
|
| 3045 |
+
Number.isSafeInteger(searchIndex.bytes) && searchIndex.bytes > 0 &&
|
| 3046 |
+
/^[0-9a-f]{64}$/.test(searchIndex.sha256 || "")
|
| 3047 |
+
? { chapters: manifest.chapters, index: { ...searchIndex,
|
| 3048 |
+
url: readerContentUrl(new URL(searchIndex.path, manifestBase).href) } }
|
| 3049 |
+
: null;
|
| 3050 |
const chapterUrl = (chapter) => trustedChapterUrl(chapter.path, manifestBase);
|
| 3051 |
const resourceUrl = (raw, base, attribute) => {
|
| 3052 |
const value = String(raw || "").trim();
|
|
|
|
| 3118 |
let inserted = false;
|
| 3119 |
try {
|
| 3120 |
assertReaderActive();
|
| 3121 |
+
const doc = parseChapterDocument(new TextDecoder().decode(bytes));
|
|
|
|
|
|
|
| 3122 |
for (const element of doc.querySelectorAll("*")) {
|
| 3123 |
for (const name of ["src", "href", "poster", "xlink:href"])
|
| 3124 |
if (element.hasAttribute(name)) {
|
|
|
|
| 3133 |
article.className = "reader-markdown reader-epub-chapter";
|
| 3134 |
article.dataset.chapter = String(chapter.index);
|
| 3135 |
article.innerHTML = doc.body ? doc.body.innerHTML : "";
|
| 3136 |
+
// The generated text index includes head text (e.g. the chapter title).
|
| 3137 |
+
article._chapterSearchHead = doc.head ? document.importNode(doc.head, true) : null;
|
| 3138 |
const marker = frame.querySelector(
|
| 3139 |
`.reader-chapter-sentinel[data-chapter="${chapter.index}"]`
|
| 3140 |
);
|
|
|
|
| 4236 |
const fullSearchInput = fullSearchView.querySelector("#full-search-input"),
|
| 4237 |
fullSearchStatus = fullSearchView.querySelector("#full-search-status"),
|
| 4238 |
fullSearchResultsNode = fullSearchView.querySelector("#full-search-results");
|
| 4239 |
+
const chapterSearchPagination = document.createElement("div");
|
| 4240 |
+
chapterSearchPagination.className = "full-search-pagination";
|
| 4241 |
+
chapterSearchPagination.hidden = true;
|
| 4242 |
+
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>';
|
| 4243 |
+
fullSearchResultsNode.before(chapterSearchPagination);
|
| 4244 |
+
const fullSearchCancel = document.createElement("button");
|
| 4245 |
+
fullSearchCancel.type = "button";
|
| 4246 |
+
fullSearchCancel.id = "full-search-cancel";
|
| 4247 |
+
fullSearchCancel.className = "text-action";
|
| 4248 |
+
fullSearchCancel.textContent = "取消搜索";
|
| 4249 |
+
fullSearchCancel.hidden = true;
|
| 4250 |
+
fullSearchStatus.after(fullSearchCancel);
|
| 4251 |
+
const fullSearchRetry = document.createElement("button");
|
| 4252 |
+
fullSearchRetry.type = "button";
|
| 4253 |
+
fullSearchRetry.id = "full-search-retry";
|
| 4254 |
+
fullSearchRetry.className = "text-action";
|
| 4255 |
+
fullSearchRetry.textContent = "重试搜索";
|
| 4256 |
+
fullSearchRetry.hidden = true;
|
| 4257 |
+
fullSearchCancel.after(fullSearchRetry);
|
| 4258 |
+
fullSearchRetry.addEventListener("click", runFullSearch);
|
| 4259 |
+
fullSearchCancel.addEventListener("click", () => {
|
| 4260 |
+
nextReaderGeneration("search");
|
| 4261 |
+
beginReaderNavigation();
|
| 4262 |
+
chapterSearchClient?.cancel();
|
| 4263 |
+
chapterSearchPage = null;
|
| 4264 |
+
updateSearchState({ results: [], index: -1 });
|
| 4265 |
+
renderFullSearchResults();
|
| 4266 |
+
fullSearchCancel.hidden = true;
|
| 4267 |
+
fullSearchRetry.hidden = false;
|
| 4268 |
+
fullSearchStatus.textContent = "搜索已取消";
|
| 4269 |
+
});
|
| 4270 |
+
chapterSearchPagination.querySelector("#full-search-page-prev").addEventListener("click", () =>
|
| 4271 |
+
loadChapterSearchPage(chapterSearchPage.offset - chapterSearchPage.pageSize));
|
| 4272 |
+
chapterSearchPagination.querySelector("#full-search-page-next").addEventListener("click", () =>
|
| 4273 |
+
loadChapterSearchPage(chapterSearchPage.offset + chapterSearchPage.pageSize));
|
| 4274 |
+
chapterSearchPagination.querySelector("#full-search-page").addEventListener("change", event => {
|
| 4275 |
+
if (!chapterSearchPage || !Number.isFinite(event.target.valueAsNumber)) return;
|
| 4276 |
+
loadChapterSearchPage((event.target.valueAsNumber - 1) * chapterSearchPage.pageSize);
|
| 4277 |
+
});
|
| 4278 |
// Full-text search: format matching, result presentation, and navigation.
|
| 4279 |
+
function chapterSearchModule() {
|
| 4280 |
+
if (!chapterSearchModulePromise)
|
| 4281 |
+
chapterSearchModulePromise = import("/static/reader-chapter-search.mjs")
|
| 4282 |
+
.catch(error => { chapterSearchModulePromise = null; throw error; });
|
| 4283 |
+
return chapterSearchModulePromise;
|
| 4284 |
+
}
|
| 4285 |
+
async function searchChapterBook(query, generation) {
|
| 4286 |
+
if (!chapterSearchConfiguration) throw new Error("本书暂无完整全文搜索索引");
|
| 4287 |
+
const module = await chapterSearchModule();
|
| 4288 |
+
if (!isReaderGenerationCurrent("search", generation)) return;
|
| 4289 |
+
if (chapterSearchClient?.failed) { chapterSearchClient.dispose(); chapterSearchClient = null; }
|
| 4290 |
+
if (!chapterSearchClient) chapterSearchClient = module.createChapterSearch(chapterSearchConfiguration);
|
| 4291 |
+
const page = await chapterSearchClient.search(query);
|
| 4292 |
+
if (isReaderGenerationCurrent("search", generation)) applyChapterSearchPage(page);
|
| 4293 |
+
}
|
| 4294 |
+
function applyChapterSearchPage(page) {
|
| 4295 |
+
chapterSearchPage = page;
|
| 4296 |
+
updateSearchState({ results: page.results.map(result => ({ ...result,
|
| 4297 |
+
activate: generation => navigateChapterSearchResult(result, generation) })), index: -1 });
|
| 4298 |
+
}
|
| 4299 |
+
async function navigateChapterSearchResult(result, generation) {
|
| 4300 |
+
const article = await chapterManifestLoader?.(result.chapterIndex);
|
| 4301 |
+
if (!article || !isReaderGenerationCurrent("navigation", generation)) return false;
|
| 4302 |
+
const module = await chapterSearchModule();
|
| 4303 |
+
if (!isReaderGenerationCurrent("navigation", generation)) return false;
|
| 4304 |
+
clearFullSearchMarks();
|
| 4305 |
+
const mapping = module.chapterTextMap([article._chapterSearchHead, article]);
|
| 4306 |
+
const match = result.snippet.text.slice(result.snippet.matchStart,
|
| 4307 |
+
result.snippet.matchStart + result.snippet.matchLength);
|
| 4308 |
+
let start = result.start;
|
| 4309 |
+
if (mapping.text.slice(start, start + result.length) !== match) {
|
| 4310 |
+
// A browser may repair malformed source HTML differently from HTMLParser.
|
| 4311 |
+
// Relocate only by a unique full excerpt; never guess between repeated hits.
|
| 4312 |
+
const found = mapping.text.indexOf(result.snippet.text);
|
| 4313 |
+
if (found < 0 || mapping.text.indexOf(result.snippet.text, found + 1) >= 0)
|
| 4314 |
+
throw new Error("已加载章节,但未能准确定位这处文字");
|
| 4315 |
+
start = found + result.snippet.matchStart;
|
| 4316 |
+
}
|
| 4317 |
+
const parts = mapping.parts(start, start + result.length, article);
|
| 4318 |
+
const [mark] = highlightTextParts(parts);
|
| 4319 |
+
(mark || article).scrollIntoView({ block: "center" });
|
| 4320 |
+
const tocIndex = navigationState.tocEntries.findIndex(entry => entry.chapterIndex === result.chapterIndex);
|
| 4321 |
+
if (tocIndex >= 0) { updateNavigationState({ currentChapterIndex: tocIndex }); updateTocCurrentMark(); }
|
| 4322 |
+
updateProgressTools();
|
| 4323 |
+
scheduleSave();
|
| 4324 |
+
return true;
|
| 4325 |
+
}
|
| 4326 |
+
function updateChapterSearchPagination() {
|
| 4327 |
+
const page = chapterSearchPage;
|
| 4328 |
+
chapterSearchPagination.hidden = !page || !page.total;
|
| 4329 |
+
if (!page) return;
|
| 4330 |
+
const pages = Math.ceil(page.total / page.pageSize);
|
| 4331 |
+
const input = chapterSearchPagination.querySelector("#full-search-page");
|
| 4332 |
+
input.value = String(Math.floor(page.offset / page.pageSize) + 1);
|
| 4333 |
+
input.max = String(Math.max(1, pages));
|
| 4334 |
+
chapterSearchPagination.querySelector("#full-search-pages").textContent = `/ ${pages}`;
|
| 4335 |
+
chapterSearchPagination.querySelector("#full-search-page-prev").disabled = page.offset === 0;
|
| 4336 |
+
chapterSearchPagination.querySelector("#full-search-page-next").disabled = page.offset + page.pageSize >= page.total;
|
| 4337 |
+
}
|
| 4338 |
+
async function loadChapterSearchPage(offset, selectLast = null) {
|
| 4339 |
+
if (!chapterSearchPage || !chapterSearchClient) return;
|
| 4340 |
+
const generation = nextReaderGeneration("search");
|
| 4341 |
+
beginReaderNavigation();
|
| 4342 |
+
fullSearchCancel.hidden = false;
|
| 4343 |
+
fullSearchRetry.hidden = true;
|
| 4344 |
+
fullSearchStatus.textContent = "正在加载搜索结果…";
|
| 4345 |
+
try {
|
| 4346 |
+
const page = await chapterSearchClient.page(offset);
|
| 4347 |
+
if (!isReaderGenerationCurrent("search", generation)) return;
|
| 4348 |
+
applyChapterSearchPage(page);
|
| 4349 |
+
renderFullSearchResults();
|
| 4350 |
+
fullSearchStatus.textContent = `${page.total} 个结果`;
|
| 4351 |
+
if (selectLast !== null) await activateFullSearchResult(selectLast ? page.results.length - 1 : 0, false);
|
| 4352 |
+
} catch (error) {
|
| 4353 |
+
if (isReaderGenerationCurrent("search", generation)) {
|
| 4354 |
+
fullSearchStatus.textContent = error.message || "搜索结果加载失败";
|
| 4355 |
+
fullSearchRetry.hidden = false;
|
| 4356 |
+
}
|
| 4357 |
+
} finally {
|
| 4358 |
+
if (isReaderGenerationCurrent("search", generation)) fullSearchCancel.hidden = true;
|
| 4359 |
+
}
|
| 4360 |
+
}
|
| 4361 |
async function fullSearchFoliateMatches(query, generation) {
|
| 4362 |
const results = [];
|
| 4363 |
if (!epubRendition?.search) return results;
|
|
|
|
| 4596 |
return output;
|
| 4597 |
}
|
| 4598 |
function renderFullSearchResults() {
|
| 4599 |
+
updateChapterSearchPagination();
|
| 4600 |
fullSearchResultsNode.textContent = "";
|
| 4601 |
for (const [index, result] of searchState.results.entries()) {
|
| 4602 |
const row = document.createElement("button"),
|
|
|
|
| 4619 |
beginReaderNavigation();
|
| 4620 |
clearFullSearchMarks();
|
| 4621 |
updateSearchState({ query, results: [], index: -1 });
|
| 4622 |
+
chapterSearchPage = null;
|
| 4623 |
+
updateChapterSearchPagination();
|
| 4624 |
+
fullSearchRetry.hidden = true;
|
| 4625 |
+
fullSearchCancel.hidden = capability.mode !== "epub-chapters" || !query;
|
| 4626 |
fullSearchResultsNode.textContent = "";
|
| 4627 |
fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {
|
| 4628 |
button.disabled = true;
|
| 4629 |
});
|
| 4630 |
if (!query) {
|
| 4631 |
+
chapterSearchClient?.cancel();
|
| 4632 |
fullSearchStatus.textContent = "输入关键词搜索正文";
|
| 4633 |
return;
|
| 4634 |
}
|
|
|
|
| 4638 |
publishSearchResults(generation, await fullSearchPdfMatches(query, generation));
|
| 4639 |
else if (capability.mode === "foliate")
|
| 4640 |
publishSearchResults(generation, await fullSearchFoliateMatches(query, generation));
|
| 4641 |
+
else if (capability.mode === "epub-chapters")
|
| 4642 |
+
await searchChapterBook(query, generation);
|
| 4643 |
else if (["text", "markdown", "docx"].includes(capability.mode))
|
| 4644 |
publishSearchResults(
|
| 4645 |
generation,
|
|
|
|
| 4660 |
else throw new Error("此格式没有可搜索文本");
|
| 4661 |
if (!isReaderGenerationCurrent("search", generation)) return;
|
| 4662 |
renderFullSearchResults();
|
| 4663 |
+
fullSearchStatus.textContent = chapterSearchPage
|
| 4664 |
+
? (chapterSearchPage.total ? `${chapterSearchPage.total} 个结果` : "未找到正文匹配")
|
| 4665 |
+
: searchState.results.length
|
| 4666 |
? `${searchState.results.length}${searchState.results.length === 100 ? "+" : ""} 个结果`
|
| 4667 |
: "未找到正文匹配";
|
| 4668 |
} catch (error) {
|
| 4669 |
+
if (isReaderGenerationCurrent("search", generation)) {
|
| 4670 |
fullSearchStatus.textContent = error.message || "正文搜索不可用";
|
| 4671 |
+
fullSearchRetry.hidden = capability.mode !== "epub-chapters";
|
| 4672 |
+
}
|
| 4673 |
} finally {
|
| 4674 |
+
if (isReaderGenerationCurrent("search", generation)) fullSearchCancel.hidden = true;
|
| 4675 |
if (isReaderGenerationCurrent("search", generation))
|
| 4676 |
fullSearchView.querySelectorAll(".full-search-nav button").forEach((button) => {
|
| 4677 |
button.disabled = !searchState.results.length;
|
|
|
|
| 4696 |
if (closePanel) setReaderPanelOpen(false, true);
|
| 4697 |
else fullSearchResultsNode.children[index]?.scrollIntoView({ block: "nearest" });
|
| 4698 |
} catch (error) {
|
| 4699 |
+
if (capability.mode === "epub-chapters" && isReaderGenerationCurrent("navigation", generation))
|
| 4700 |
+
fullSearchStatus.textContent = error.message || "搜索结果定位失败";
|
| 4701 |
reportNavigationError(error, generation);
|
| 4702 |
}
|
| 4703 |
}
|
| 4704 |
function moveFullSearch(step) {
|
| 4705 |
+
if (chapterSearchPage?.total) {
|
| 4706 |
+
const page = chapterSearchPage;
|
| 4707 |
+
const next = searchState.index < 0 ? (step > 0 ? 0 : -1) : searchState.index + step;
|
| 4708 |
+
if (next < 0) return loadChapterSearchPage(page.offset ? page.offset - page.pageSize
|
| 4709 |
+
: Math.floor((page.total - 1) / page.pageSize) * page.pageSize, true);
|
| 4710 |
+
if (next >= searchState.results.length) return loadChapterSearchPage(
|
| 4711 |
+
page.offset + page.pageSize < page.total ? page.offset + page.pageSize : 0, false);
|
| 4712 |
+
return activateFullSearchResult(next, false);
|
| 4713 |
+
}
|
| 4714 |
if (searchState.results.length)
|
| 4715 |
return activateFullSearchResult(
|
| 4716 |
(searchState.index + step + searchState.results.length) % searchState.results.length,
|
|
|
|
| 4722 |
if (panel.classList.contains("is-open") && !fullSearchView.hidden) {
|
| 4723 |
beginReaderNavigation();
|
| 4724 |
nextReaderGeneration("search");
|
| 4725 |
+
chapterSearchClient?.cancel();
|
| 4726 |
+
chapterSearchPage = null;
|
| 4727 |
+
fullSearchCancel.hidden = true;
|
| 4728 |
+
fullSearchRetry.hidden = true;
|
| 4729 |
clearFullSearchMarks();
|
| 4730 |
updateSearchState({ results: [], index: -1 });
|
| 4731 |
renderFullSearchResults();
|
static/sw.js
CHANGED
|
@@ -27,6 +27,8 @@ const PRECACHE_URLS = [
|
|
| 27 |
"/icons/icon-512.png"
|
| 28 |
];
|
| 29 |
const READER_RUNTIME_PATHS = new Set([
|
|
|
|
|
|
|
| 30 |
"/static/reader-navigation.js",
|
| 31 |
"/static/reader-contract.js",
|
| 32 |
"/static/reader-store.js",
|
|
|
|
| 27 |
"/icons/icon-512.png"
|
| 28 |
];
|
| 29 |
const READER_RUNTIME_PATHS = new Set([
|
| 30 |
+
"/static/reader-chapter-search.mjs",
|
| 31 |
+
"/static/reader-chapter-search-worker.mjs",
|
| 32 |
"/static/reader-navigation.js",
|
| 33 |
"/static/reader-contract.js",
|
| 34 |
"/static/reader-store.js",
|
tests/test_reader_chapter_search.mjs
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import { countMatches, resultPage, scanText, validateIndex } from "../static/reader-chapter-search-worker.mjs";
|
| 3 |
+
|
| 4 |
+
const chapters = [
|
| 5 |
+
{ index: 1, title: "开头", path: "chapters/1.xhtml", text: "手机 手。机 a+b [term] " + "needle ".repeat(125) },
|
| 6 |
+
{ index: 2, title: "结尾", path: "chapters/2.xhtml", text: "needle ".repeat(130) + "远方命中" }
|
| 7 |
+
];
|
| 8 |
+
const counted = await countMatches(chapters, "needle", () => true);
|
| 9 |
+
assert.equal(counted.total, 255);
|
| 10 |
+
assert.deepEqual(counted.counts, [125, 130]);
|
| 11 |
+
const all = [];
|
| 12 |
+
for (let offset = 0; offset < counted.total; offset += 50) {
|
| 13 |
+
const page = await resultPage(chapters, "needle", counted.counts, offset, () => true);
|
| 14 |
+
assert.ok(page.length <= 50);
|
| 15 |
+
all.push(...page);
|
| 16 |
+
}
|
| 17 |
+
assert.equal(new Set(all.map(item => `${item.chapterIndex}:${item.start}`)).size, 255);
|
| 18 |
+
assert.equal(all.at(-1).chapterIndex, 2);
|
| 19 |
+
for (const query of ["手机", "手。机", "a+b", "[term]", "远方命中"]) {
|
| 20 |
+
assert.equal((await countMatches(chapters, query, () => true)).total, 1, query);
|
| 21 |
+
}
|
| 22 |
+
const boundaryText = "x".repeat(65534) + "跨边界😀" + "y".repeat(65536) + "跨边界😀";
|
| 23 |
+
const found = [];
|
| 24 |
+
await scanText(boundaryText, "跨边界😀", (start, length) => found.push([start, length]));
|
| 25 |
+
assert.deepEqual(found.map(([start, length]) => boundaryText.slice(start, start + length)), ["跨边界😀", "跨边界😀"]);
|
| 26 |
+
let current = true;
|
| 27 |
+
const cancelled = scanText("x".repeat(1000000), "x", () => { current = false; }, () => current);
|
| 28 |
+
await assert.rejects(cancelled, { name: "AbortError" });
|
| 29 |
+
assert.equal(validateIndex({ version: 1, kind: "epub-search-index", chapters }, chapters).length, 2);
|
| 30 |
+
assert.throws(() => validateIndex({ version: 1, kind: "epub-search-index", chapters: chapters.slice(0, 1) }, chapters));
|
| 31 |
+
assert.throws(() => validateIndex({ version: 1, kind: "epub-search-index", chapters: [chapters[1], chapters[0]] }, chapters));
|
| 32 |
+
console.log("chapter search: complete counts, paging, literal matches, Unicode boundaries, cancellation and index identity passed");
|
tests/test_reader_refactor.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
| 1 |
"""Local Reader behavior regressions; all document/network fixtures stay offline."""
|
| 2 |
|
| 3 |
import io
|
|
|
|
|
|
|
| 4 |
import json
|
| 5 |
import unittest
|
| 6 |
import urllib.parse
|
|
@@ -484,6 +486,133 @@ class ReaderRefactorTest(unittest.TestCase):
|
|
| 484 |
self.assertEqual(download["link"], [record["download"]])
|
| 485 |
self.assertEqual(seen, [record["title"] + ".mobi" for record in records])
|
| 486 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 487 |
def test_chapter_manifest_migrates_position_saved_by_foliate(self):
|
| 488 |
source = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/chapter-manifest.json"
|
| 489 |
manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
|
|
|
|
| 1 |
"""Local Reader behavior regressions; all document/network fixtures stay offline."""
|
| 2 |
|
| 3 |
import io
|
| 4 |
+
import gzip
|
| 5 |
+
import hashlib
|
| 6 |
import json
|
| 7 |
import unittest
|
| 8 |
import urllib.parse
|
|
|
|
| 486 |
self.assertEqual(download["link"], [record["download"]])
|
| 487 |
self.assertEqual(seen, [record["title"] + ".mobi" for record in records])
|
| 488 |
|
| 489 |
+
def serve_chapter_search(self, index_failure=None, namespaced=False):
|
| 490 |
+
base = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/foliate-original-v1/epub-chapters/"
|
| 491 |
+
chapters, texts, bodies = [], [], {}
|
| 492 |
+
for index in range(1, 13):
|
| 493 |
+
path = f"chapters/chapter-{index:04d}.xhtml"
|
| 494 |
+
title = f"Chapter {index}"
|
| 495 |
+
if index == 12:
|
| 496 |
+
body = ("<h1>最后一章</h1><p>前言 &amp; <span>独特</span><em>词语</em> 尾声</p>"
|
| 497 |
+
+ "".join(f"<p>第{i}处needle结束</p>" for i in range(155))
|
| 498 |
+
+ "<p>手机 手。机</p>")
|
| 499 |
+
text = "最后一章 前言 & 独特 词语 尾声 " + " ".join(f"第{i}处needle结束" for i in range(155)) + " 手机 手。机"
|
| 500 |
+
if namespaced:
|
| 501 |
+
body = ('<html:html xmlns:html="http://www.w3.org/1999/xhtml"><html:head>'
|
| 502 |
+
'<html:meta/><html:title>原始标题</html:title></html:head><html:body>'
|
| 503 |
+
+ body + '</html:body></html:html>')
|
| 504 |
+
text = "原始标题 " + text
|
| 505 |
+
else:
|
| 506 |
+
body = f"<h1>{title}</h1><p style='height:12000px'>普通正文</p>"
|
| 507 |
+
text = title + " 普通正文"
|
| 508 |
+
bodies[base + path] = body
|
| 509 |
+
chapters.append({"index": index, "path": path, "title": title, "bytes": len(body.encode())})
|
| 510 |
+
texts.append({"index": index, "path": path, "title": title, "text": text})
|
| 511 |
+
packed = gzip.compress(json.dumps({"version": 1, "kind": "epub-search-index", "chapters": texts}, ensure_ascii=False).encode(), mtime=0)
|
| 512 |
+
manifest = {"version": 1, "kind": "epub-chapters", "chapters": chapters,
|
| 513 |
+
"search_index": {"path": "epub-search-index.json.gz", "bytes": len(packed), "sha256": hashlib.sha256(packed).hexdigest()}}
|
| 514 |
+
requests = []
|
| 515 |
+
def serve(route):
|
| 516 |
+
raw = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["url"][0]
|
| 517 |
+
requests.append(raw)
|
| 518 |
+
if raw.endswith("chapter-manifest.json"):
|
| 519 |
+
route.fulfill(content_type="application/json", body=json.dumps(manifest))
|
| 520 |
+
elif raw.endswith("epub-search-index.json.gz"):
|
| 521 |
+
attempt = sum(item.endswith("epub-search-index.json.gz") for item in requests)
|
| 522 |
+
if index_failure and index_failure(route, attempt, packed):
|
| 523 |
+
return
|
| 524 |
+
route.fulfill(content_type="application/gzip", body=packed)
|
| 525 |
+
else:
|
| 526 |
+
route.fulfill(content_type="text/html", body=bodies[raw])
|
| 527 |
+
# Worker fetches belong to the context, not to the page's route table.
|
| 528 |
+
self.context.route("**/api/reader-content**", serve)
|
| 529 |
+
self.open(self.reader_url("epub-chapters", url=base + "chapter-manifest.json"))
|
| 530 |
+
return requests, base
|
| 531 |
+
|
| 532 |
+
def test_chapter_search_is_lazy_complete_paged_and_navigates_unloaded_repeated_hits(self):
|
| 533 |
+
requests, base = self.serve_chapter_search()
|
| 534 |
+
self.assertFalse(any(item.endswith("epub-search-index.json.gz") for item in requests))
|
| 535 |
+
self.assertNotIn(base + "chapters/chapter-0012.xhtml", requests)
|
| 536 |
+
self.search("needle")
|
| 537 |
+
self.assertEqual(self.page.locator("#full-search-status").text_content(), "155 个结果")
|
| 538 |
+
self.assertEqual(self.page.locator(".full-search-result").count(), 50)
|
| 539 |
+
self.assertNotIn(base + "chapters/chapter-0012.xhtml", requests)
|
| 540 |
+
page_input = self.page.locator("#full-search-page")
|
| 541 |
+
page_input.fill("4")
|
| 542 |
+
page_input.press("Enter")
|
| 543 |
+
page_input.blur()
|
| 544 |
+
self.page.wait_for_function("() => document.querySelectorAll('.full-search-result').length === 5")
|
| 545 |
+
self.page.locator(".full-search-result").last.click()
|
| 546 |
+
self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter[data-chapter=\"12\"] mark.full-search-highlight')")
|
| 547 |
+
mark = self.page.locator(".reader-epub-chapter mark.full-search-highlight")
|
| 548 |
+
self.assertEqual(mark.text_content(), "needle")
|
| 549 |
+
self.assertEqual(mark.locator("..").text_content(), "第154处needle结束")
|
| 550 |
+
# Previous-result navigation crosses a result-page boundary exactly.
|
| 551 |
+
self.page.locator("#history").click()
|
| 552 |
+
self.page.locator("#full-search-toggle").click()
|
| 553 |
+
self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '155 个结果'")
|
| 554 |
+
self.page.locator("#full-search-prev").click()
|
| 555 |
+
self.page.wait_for_function("() => document.querySelector('#full-search-page').value === '4'")
|
| 556 |
+
self.page.locator("#full-search-next").click()
|
| 557 |
+
self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter mark')?.parentElement.textContent === '第0处needle结束'")
|
| 558 |
+
self.assertEqual(self.page.locator("#full-search-page").input_value(), "1")
|
| 559 |
+
self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 1)
|
| 560 |
+
|
| 561 |
+
def test_chapter_search_maps_inline_nodes_entities_and_repeated_searches(self):
|
| 562 |
+
requests, _ = self.serve_chapter_search(namespaced=True)
|
| 563 |
+
self.search("独特 词语")
|
| 564 |
+
self.assertEqual(self.page.locator("#full-search-status").text_content(), "1 个结果")
|
| 565 |
+
self.page.locator(".full-search-result").click()
|
| 566 |
+
self.page.wait_for_function("() => document.querySelectorAll('.reader-epub-chapter mark.full-search-highlight').length === 2")
|
| 567 |
+
self.assertEqual(self.page.locator(".reader-epub-chapter mark.full-search-highlight").all_text_contents(), ["独特", "词语"])
|
| 568 |
+
self.page.locator("#history").click()
|
| 569 |
+
self.page.locator("#full-search-toggle").click()
|
| 570 |
+
self.page.locator("#full-search-input").fill("手机")
|
| 571 |
+
self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果' && document.querySelector('.full-search-result')?.textContent.includes('手机')")
|
| 572 |
+
self.page.locator(".full-search-result").click()
|
| 573 |
+
self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter mark.full-search-highlight')?.textContent === '手机'")
|
| 574 |
+
self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 1)
|
| 575 |
+
|
| 576 |
+
def test_chapter_search_retries_a_failed_index_and_rejects_corrupt_bytes(self):
|
| 577 |
+
def failure(route, attempt, packed):
|
| 578 |
+
if attempt == 1:
|
| 579 |
+
route.fulfill(status=503, body="temporarily unavailable")
|
| 580 |
+
return True
|
| 581 |
+
if attempt == 2:
|
| 582 |
+
route.fulfill(content_type="application/gzip", body=packed[:-1] + bytes([packed[-1] ^ 1]))
|
| 583 |
+
return True
|
| 584 |
+
requests, _ = self.serve_chapter_search(failure)
|
| 585 |
+
self.page.locator("#history").click()
|
| 586 |
+
self.page.locator("#full-search-toggle").click()
|
| 587 |
+
self.page.locator("#full-search-input").fill("needle")
|
| 588 |
+
self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent.includes('503')")
|
| 589 |
+
self.page.locator("#full-search-retry").click()
|
| 590 |
+
self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent.includes('校验失败')")
|
| 591 |
+
self.page.locator("#full-search-retry").click()
|
| 592 |
+
self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '155 个结果'")
|
| 593 |
+
self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 3)
|
| 594 |
+
|
| 595 |
+
def test_chapter_search_cancelled_download_cannot_publish_stale_results(self):
|
| 596 |
+
held = []
|
| 597 |
+
def hold(route, attempt, packed):
|
| 598 |
+
if attempt == 1:
|
| 599 |
+
held.append((route, packed))
|
| 600 |
+
return True
|
| 601 |
+
requests, _ = self.serve_chapter_search(hold)
|
| 602 |
+
self.page.locator("#history").click()
|
| 603 |
+
self.page.locator("#full-search-toggle").click()
|
| 604 |
+
with self.context.expect_event("request", predicate=lambda request: "epub-search-index" in request.url):
|
| 605 |
+
self.page.locator("#full-search-input").fill("needle")
|
| 606 |
+
self.page.locator("#full-search-cancel").click()
|
| 607 |
+
self.assertEqual(self.page.locator("#full-search-status").text_content(), "搜索已取消")
|
| 608 |
+
self.page.locator("#full-search-input").fill("手机")
|
| 609 |
+
self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
|
| 610 |
+
self.assertEqual(self.page.locator(".full-search-result").count(), 1)
|
| 611 |
+
self.assertEqual(sum(item.endswith("epub-search-index.json.gz") for item in requests), 2)
|
| 612 |
+
for route, packed in held:
|
| 613 |
+
route.fulfill(content_type="application/gzip", body=packed)
|
| 614 |
+
self.assertEqual(self.page.locator("#full-search-status").text_content(), "1 个结果")
|
| 615 |
+
|
| 616 |
def test_chapter_manifest_migrates_position_saved_by_foliate(self):
|
| 617 |
source = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/chapter-manifest.json"
|
| 618 |
manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
|
tests/test_reader_regression.js
CHANGED
|
@@ -18,7 +18,7 @@ for (const extension of ['epub', 'mobi', 'azw3', 'fb2', 'fbz']) assert.strictEqu
|
|
| 18 |
for (const extension of sandbox.self.VoiceOfMLReader.articleExtensions) assert.deepStrictEqual(Object.keys(sandbox.self.VoiceOfMLReader.capability(extension).features).sort(), ['bookmarks', 'media', 'pagination', 'search', 'toc', 'zoom'])
|
| 19 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').mode, 'pdf-pages')
|
| 20 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').features.toc, true)
|
| 21 |
-
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('epub-chapters').features.search,
|
| 22 |
for (const extension of ['mp3', 'm4a', 'flac', 'mpga', 'audio']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'audio')
|
| 23 |
for (const extension of ['mp4', 'mov', 'video']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'video')
|
| 24 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').mode, null)
|
|
|
|
| 18 |
for (const extension of sandbox.self.VoiceOfMLReader.articleExtensions) assert.deepStrictEqual(Object.keys(sandbox.self.VoiceOfMLReader.capability(extension).features).sort(), ['bookmarks', 'media', 'pagination', 'search', 'toc', 'zoom'])
|
| 19 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').mode, 'pdf-pages')
|
| 20 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').features.toc, true)
|
| 21 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('epub-chapters').features.search, true)
|
| 22 |
for (const extension of ['mp3', 'm4a', 'flac', 'mpga', 'audio']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'audio')
|
| 23 |
for (const extension of ['mp4', 'mov', 'video']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'video')
|
| 24 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').mode, null)
|
tests/test_service_worker.js
CHANGED
|
@@ -49,7 +49,25 @@ async function check(failure) {
|
|
| 49 |
events.fetch({request:{url,mode},respondWith(){throw Error('unexpected interception: '+url)}});
|
| 50 |
}
|
| 51 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
(async()=>{
|
| 53 |
for(const failure of ['none','core','network','status','invalid','payload']) await check(failure);
|
|
|
|
| 54 |
console.log('HF service worker: manifest failure isolation, fixed cache activation and API/TXT/navigation bypass passed');
|
| 55 |
})().catch(error=>{console.error(error);process.exitCode=1;});
|
|
|
|
| 49 |
events.fetch({request:{url,mode},respondWith(){throw Error('unexpected interception: '+url)}});
|
| 50 |
}
|
| 51 |
}
|
| 52 |
+
async function checkSearchRuntimeCache(hasOldCache) {
|
| 53 |
+
const events = {}, updates = [];
|
| 54 |
+
const fresh = {ok:true, version:'current', clone(){return this;}};
|
| 55 |
+
const old = hasOldCache ? {ok:true, version:'previous'} : undefined;
|
| 56 |
+
vm.runInNewContext(source, {
|
| 57 |
+
URL, Set, console,
|
| 58 |
+
self:{location:{hostname:'localhost'},addEventListener:(name,fn)=>events[name]=fn},
|
| 59 |
+
caches:{open:async()=>({match:async()=>old,put:async(key,value)=>updates.push(value.version)})},
|
| 60 |
+
fetch:async()=>fresh,
|
| 61 |
+
});
|
| 62 |
+
for(const name of ['reader-chapter-search.mjs','reader-chapter-search-worker.mjs']) {
|
| 63 |
+
let completion;
|
| 64 |
+
events.fetch({request:{url:'https://localhost/static/'+name,mode:'cors'},respondWith(value){completion=value;}});
|
| 65 |
+
assert.strictEqual((await completion).version,'current');
|
| 66 |
+
}
|
| 67 |
+
assert.deepStrictEqual(updates,['current','current']);
|
| 68 |
+
}
|
| 69 |
(async()=>{
|
| 70 |
for(const failure of ['none','core','network','status','invalid','payload']) await check(failure);
|
| 71 |
+
for(const old of [false,true]) await checkSearchRuntimeCache(old);
|
| 72 |
console.log('HF service worker: manifest failure isolation, fixed cache activation and API/TXT/navigation bypass passed');
|
| 73 |
})().catch(error=>{console.error(error);process.exitCode=1;});
|